#!/usr/bin/perl -W

# combined extract varname / extract comment script

# usage: 'get_name.pl global.h'

$struct_found = 0;
$cbyte_count = 0;


while($l = <>) {
    chomp $l;

    if ($l =~ /^\s*($|\/\/)/) {  # skip empty lines or lines consisting of comments only
	next;
    }
    
    if ($l =~ /^\s*struct config_t\s*{/) { # find config_t structure
	$struct_found = 1;
    } elsif ($l =~ /\s*};/) {
	$struct_found = 0;
    } elsif ($struct_found == 1) { # examine structure

	($str) = ($l =~ /\s*\/\/\s*(.{1,200})/);	# comments after 2nd // ignored : (\s*\/\/)?

	$str =~ s/_/\\_/g;  # handle underscores in comment
	$str =~ s/%/\\%/g;  # handle percentage
	$str =~ s/</\$<\$/g;  # less than in math mode
	$str =~ s/(\w+)\^(\d+)/\$$1\^$2\$/g;  # raise to the power of...
	
	if ($l =~ /uint8_t ([\[\]\w]+)\s*;/) {  # check if the line contains something we know

	    if ($1 =~ /(\w+)\[(\d+)\]/) {  # found an array "test[]"
		$varname = $1;
		$varsize = $2;

		$varname =~ s/_/\\_/g;  # handle underscores in varname

		printf("%02x[%x]", $cbyte_count, $varsize);
		print ", \\texttt{$varname}, $str\\\\\n";
#		print "$cbyte_count, \\texttt{$varname}, $str\\\\\n";

	    } else {  # found a variable "test"
		$varname = $1;
		$varsize = 1;

		$varname =~ s/_/\\_/g;  # handle underscores in varname

		printf("%02x", $cbyte_count);
		print ", \\texttt{$varname}, $str\\\\\n";
#		print "$cbyte_count, \\texttt{$varname}, $str\\\\\n";

	    }

	    $cbyte_count += $varsize;

	} else {
	    print "Ooops, can't understand \"$l\"\n";
	}
    }
}

#$version = "unknown";
#open(VER, "global_h_version") or die "can't open global_h_version";

#while($l = <VER>) {
#    chomp $l;

#    if ($l =~ /Working revision:\s+(\d+\.\d+)/) {
#	$version = $1;
#    }
#}
#close VER;

$version = "unknown";
$file = "../../CVS/Entries";
open(VER, "$file") or die "can't open $file";

while($l = <VER>) {
    chomp $l;

    if ($l =~ /global\.h\/(\d+\.\d+)/) {
	$version = $1;
    }
}
close VER;


print "\\newline\n";
print "{\\small{global.h version: $version}}\n";

