use utf8;
use strict;

sub ShowAPIs {
	my $apis_ref = $_[0];
	my @apis = @$apis_ref;
	foreach my $api_ref (@apis) {
		my %api = %{$api_ref};
		print $api{"dll"}, " ", $api{"symbol"}, "@",  $api{"param_bytes"}, "\n";
	}
}

sub ReadSymbleList {
	open(FILE, "symbol_list.txt") || die "Cannot open file.";

	my(%table, $val, $key);
	my($symbols);

	my @apis = ();
	while (my $line = <FILE>) {
		if ($line =~ /^\s*(\w+)\s+(\w+)@(\d+)/) {
			my %api = (
				"dll" => $1,
				"symbol" => $2,
				"param_bytes" => $3
				);
			push(@apis, \%api);
		}
	}
	close(FILE);

	return @apis;
}

sub CreateAsm() {
	my($dll, $symbol, $param_bytes) = @_;

	my $template = "templ_nasm.asm.in";
	my $filename = "$symbol.asm";
	open(IN, $template) || die "cannot open $template";
	open(OUT, ">$filename") || die "cannot open $filename";

	while (my $line = <IN>) {
		$line =~ s/%SYMBOL%/$symbol/;
		$line =~ s/%PARAM_BYTES%/$param_bytes/;
		$line =~ s/%DLL%/$dll/;
		print OUT $line;
	}
	close(IN);
	close(OUT);
}

sub CreateAsmArray() {
	my $apis_ref = $_[0];
	my @apis = @$apis_ref;
	foreach my $api_ref (@apis) {
		my %api = %{$api_ref};
		my $dll = $api{"dll"};
		my $symbol = $api{"symbol"};
		my $param_bytes = $api{"param_bytes"};
		&CreateAsm($dll, $symbol, $param_bytes);
	}
}

sub CreateMakefile() {
	my $apis_ref = $_[0];
	my @apis = @$apis_ref;
	my $top = <<"EOS";
# generated by perl script

NASM = ../../buildtools/nasm/nasm.exe
NASM_FLAGS = -f win32 -g -F cv8

all: all_objs

clean:
	rm -rf *.obj *.asm

generate:
	perl generate.pl

all_objs: \\
EOS
	open(OUT, ">Makefile") || die "Cannot open file.";
	print OUT $top;
	foreach my $api_ref (@apis) {
		my %api = %{$api_ref};
		my $symbol = $api{"symbol"};
		print OUT "	$symbol.obj \\\n";
	}
	print OUT "\n";
	foreach my $api_ref (@apis) {
		my %api = %{$api_ref};
		my $dll = $api{"dll"};
		my $symbol = $api{"symbol"};
		my $param_bytes = $api{"param_bytes"};
		print OUT "$symbol.obj: $symbol.asm\n";
		print OUT "	\${NASM} \${NASM_FLAGS} $symbol.asm -o \$@\n";
		print OUT "\n";
	}
	close(OUT);
}

sub CreateAsmCmake() {
	my $apis_ref = $_[0];
	my @apis = @$apis_ref;

	open(OUT, ">list_asm.cmake") || die "Cannot open file.";
	my $top = <<"EOS";
# generated by perl script

set(SRC
EOS
	print OUT $top;
	foreach my $api_ref (@apis) {
		my %api = %{$api_ref};
		my $symbol = $api{"symbol"};
		print OUT "  $symbol.asm\n";
#		print OUT "  ${ASM_DIR}/$symbol.asm\n";
	}
	print OUT "  )\n";
	close(OUT);
}

sub CreateObjCmake() {
	my $apis_ref = $_[0];
	my @apis = @$apis_ref;

	open(OUT, ">list_obj.cmake") || die "Cannot open file.";
	my $top = <<"EOS";
# generated by perl script

set(SRC
EOS
	print OUT $top;
	foreach my $api_ref (@apis) {
		my %api = %{$api_ref};
		my $symbol = $api{"symbol"};
		print OUT "  \${OBJ_DIR}/$symbol.obj\n";
	}
	print OUT "  )\n";
	close(OUT);
}

my @apis = &ReadSymbleList();
ShowAPIs(\@apis);
&CreateAsmArray(\@apis);
&CreateMakefile(\@apis);
&CreateAsmCmake(\@apis);
&CreateObjCmake(\@apis);

exit(0);
