#!/usr/bin/perl

# cpp2sgml -- turn C preprocessor defines to SGML entities

# Author: Adam Di Carlo <aph@debian.org>
# $Revision: 1.4 $

# This script is placed under the GPL v2.
#
# Additionally, I would appreciate notice from any parties
# using this script, since that might indicate it should be extended
# and maintained on its own.

# Bugs: assumes &quot; entity and <var> element are defined, not DTD portable

$file = join('', <>);

while ( $file =~ s {
	 	    ^\#define\s+	# match the first #define
	  	    (\w+)\s+		# match the name of the macro
	  	    "(.*?)"\s*$		# match the value
	  	   }[]smx 
	) {
    ($macro, $val) = ($1, $2);
    $val =~ s/\\"/\&quot;/g;	# remove quotations (not DTD portable) \\"
    $val =~ s/\\n/\n/g;		# interpret embedded '\n'
    $val =~ s/\\//g;		# strip embedded backslashes (?)
    $val =~ s|%s|<var>var</var>|g; # variable
    $val =~ s|%d|<var>num</var>|g; # variable
    $val = '"``' . $val . '\'\'"';
    $collect{$macro} = $val;
}

# create an alternator string with all macros
$allkeys = join("|", keys %collect);

foreach $key (keys %collect) {
    # be clever and interpolate macros within macros
    if ( $collect{$key} =~ s/"($allkeys)"/$collect{$1}/g ) {
	$collect{$key} =~ s/(.)"``/$1/g;
	$collect{$key} =~ s/''"(.)/$1/g;
    }
    ($sgmlkey = $key) =~ s/_/-/g;
    print "<!entity $sgmlkey $collect{$key}>\n";
}


