#!/usr/bin/perl

# cpp2sgml -- turn C preprocessor defines to SGML entities

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

# 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 a &quot; entity is defined

$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|<em>var</em>|g; # variable should be var for debiandoc
    $val =~ s|%d|<em>num</em>|g; # variable should be var for debiandoc
    $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;
#	$collect{$key} = "\"$collect{$key}\"";
    }
    ($sgmlkey = $key) =~ s/_/-/g;
    print "<!entity $sgmlkey $collect{$key}>\n";
}


