#! /usr/bin/perl

while ($ARGV[0] =~ /(\w+):(\w+)(:\w+)?/) {
	$bitname{$2} = $1;
	$flag{$2} = $3;
	push @prefix, $2;
	shift;
}

print "/* auto generated by bitname scirpt */\n";
while (<>) {
	chomp;
	if (/^(typedef\s+)?enum\s+(\w+)\s*{\s*(\/\*.*\*\/)?$/) {
		$name = $2;
		print "\nstatic const struct bitname ${name}_bitname[] = {\n";
		while (<>) {
			if (/^\s*([A-Za-z_]\w*)\s*(.)/) {
				$tmp = $id = $1;
				$n = $2;
				$tmp =~ s/^[^_]+_// || $tmp =~ s/^_[^_]{1,5}//;
				$tmp =~ tr/A-Z/a-z/;
				if ($n eq '=') {
					print "\t{ $id,\t\"", $tmp, "\" },\n";
				} else {
					print "\t{ 1<<$id,\t\"", $tmp, "\" },\n";
				}
			}
			if (/}/) {
				print "\t{ 0,\tNULL }\n};\n";
				last;
			}
		}
	} elsif (/^#define\s+(\w+)\s+(0x\w{1,16}|\d+u?[lL]*|\([<>\w]+\))/) {
		$id = $1;
		$v = eval "$2";
		foreach $prefix (@prefix) {
			if ($id =~ /^$prefix/) {
				if ($flag{$prefix}) {
					$list{$prefix} .= $id . " ";
					last;
				}
				for ($i = 0; $i < 64; $i++) {
					if ($v == 1<<$i) {
						$list{$prefix} .= $id . " ";
						last;
					}
				}
				last;
			}
		}
	}
}

foreach $prefix (@prefix) {
	if ($list{$prefix}) {
		print "\nstatic const struct bitname ", $bitname{$prefix}, "[] = {\n";
		foreach (split / /, $list{$prefix}) {
			($tmp = substr($_, length $prefix)) =~ tr/A-Z/a-z/;
			if ($flag{$prefix}) {
				print "\t{ 1<<$_,\t\"$tmp\" },\n";
			} else {
				print "\t{ $_,\t\"$tmp\" },\n";
			}
		}
		print "\t{ 0,\tNULL }\n};\n";
	}
}
