#!/usr/bin/tcl
# ParseCC.tcl

proc usage {} {
	puts stderr "usage: tcl ParseCC.tcl path"
	puts stderr ""
	puts stderr "path = the full path to mgmtcc.h (ex: \"/Source/Inc/mgmtcc.h\")."
	puts stderr ""
	puts stderr "Errorlevels:"
	puts stderr ""
	puts stderr "0 = Success"
	puts stderr "1 = No path specified"
	puts stderr "2 = Path not found"
	puts stderr "3 = No country code entries found."
}

proc make_country {country} {
	set result ""

	set length [string length $country]
	for {set i 0} {$i < $length} {incr i} {
		set char [string index $country $i]
		switch -regexp --  $char {
			_		{ append result - }
			default { append result [string tolower $char] }
		}
	}

	return $result
}

proc make_code {code1 code2} {

	scan $code1 "%c" value1
	scan $code2 "%c" value2
	
	return [expr {($value1 << 8) | $value2}]
}

proc parse {path} {
	if {[catch "set fd [open $path r]"] == 0} {
		set entries 0

		while {![eof $fd]} {
			set line [gets $fd]

			if {![regexp -- {^#define[ \t]+COUNTRY_CODE_([A-Z_]+)[ \t]+MAKE_COUNTRY_CODE\('([A-Z])',[ \t]+'([A-Z])'\)} $line UNUSED country code1 code2]} {
				continue;
			}
			
			if {$entries > 0} {
				puts stdout ","
			}
			puts -nonewline stdout "\t[make_country $country]([make_code $code1 $code2])"

			incr entries
		}

		if {$entries == 0} {
			puts stderr "No country code entries found."
			set result 3
		} else {
			puts stdout ""
			flush stdout
			puts stderr "$entries country code entries parsed."
			set result 0
		}
	} else {
		puts stderr "Unable to open \"$path\"."
		set result 2
	}


	return $result
}

# the main branch

set result 1

if {$argc != 1} {
	usage
} else {
	set path [lindex $argv 0]
	set result [parse $path]
}

exit $result