#!/usr/bin/perl -W

# combined extract varname / extract comment script

# usage: 'get_name.pl global.h'

$struct_found = 0;
$cbyte_count = 0;

$nameID = "";
$commentID = "";

open NAME, ">v3const.ini";
print NAME "\n;name=array,type,offset,shape,units,scale,translate,lo,hi, digits;\n";

#open COMMENT, ">magicstr.txt";
#print COMMENT "\n// Automatically generated file (bin/get_name.pl), DO NOT EDIT directly\n\n";


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

	# limited to 48 characters per displayed string
	($str) = ($l =~ /\s*\/\/\s*(.{1,70})/);	# comments after 2nd // ignored : (\s*\/\/)?
	
	$magicNname = $nameID . $cbyte_count;
	$magicCname = $commentID . $cbyte_count;


	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;
		print NAME "$varname\=array,U08,$magicNname,\[$varsize\],\" \",1,1,0,255,1;$str\n";
		$Carr .= $magicCname .",\n";
		$Narr .= $magicNname .",\n";

		for ($i=1; $i<$varsize; $i++) {
		    # a little space consuming (but space saving on the simple program...)
		    # the previous non-NULL pointer will need to be searched
		    $Carr .= "NULL,";
		    $Narr .= "NULL,";
		}
		$Carr .= "\n";
		$Narr .= "\n";

	    } else {  # found a variable "test"
		$varname = $1;
		$varsize = 1;
		print NAME "$varname\=scalar,U08,$magicNname,\" \",1,1,0,255,1;$str\n";
		#print NAME "char $magicNname\[\] PROGMEM = \"$varname\";\n";
		#print COMMENT "char $magicCname\[\] PROGMEM = \"$str\";\n";
		$Carr .= $magicCname .",\n";
		$Narr .= $magicNname .",\n";
	    }

	    $cbyte_count += $varsize;

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

# ----------- Done with global.h parsing ---------

#print NAME "\nPGM_VOID_P varstr[] PROGMEM = {\n $Narr NULL\n};\n";	# with the unnecessary NULL we just spare some coding for the last ','
close NAME;

# we pad variables to multiple of 16, so avr does not display silly things
# at the end (but we can still write to silly places - the igntable)
$i = 16 - (($cbyte_count) % 16);

$magicCname = $commentID . $cbyte_count;
if($i > 0){
 #   print COMMENT "char $magicCname\[\] PROGMEM = \"No more variable, go back, don't touch\";\n";
		$Carr .= $magicCname .",\n";
    $i--;
}

# if $i is still more than 0, we padd NULL pointers
while($i > 0){
    $Carr .= "NULL,";			# the previous non-NULL pointer will need to be searched
    $i--;
}

#print COMMENT "\nPGM_VOID_P magicstr[] PROGMEM = {\n $Carr \nNULL\n};\n";	# with the unnecessary NULL we just spare some coding for the last ','
#close COMMENT;
