#!/usr/bin/perl -w
#
use strict;
use File::Glob ':globally';
my @list = <*.{c}>;
my @exes;
my @files;
my @objs;
my @helpers = qw(printlib.c);
my @helpers_objs;

sub file_is_helper($@)
{
	my ($file, @helpers) = @_;

	foreach my $helper (@helpers) {
		if ($file eq $helper) {
			return 1;
		}
	}
	return 0;
}

foreach my $file (@list) {
	chomp($file);
#	printf("file: $file\n");
	if (file_is_helper($file, @helpers)) {
		next;
	}
	push(@files, $file);
	my $exe = $file;
	$exe =~ s/.c$/.exe/g;
	push(@exes, $exe);
}

print("CFLAGS = /nologo /Zi /MT /Gm- /W4 /FR\n");
print("LIBS = kernel32.lib gdi32.lib user32.lib shell32.lib \\\n");
print("\tadvapi32.lib ole32.lib ws2_32.lib rpcrt4.lib\n");
print("WINSPOOL_LIBS = winspool.lib\n\n");

print("all: @exes\n");
print("\n");

print(".cpp.obj:\n");
print("\tcl /c \$(CFLAGS) \$*.cpp\n\n");

print(".c.obj:\n");
print("\tcl /c \$(CFLAGS) \$*.c\n\n");

print("clean: cleantmp\n");
print("\t-del *.dll 2>nul\n\n");
print("cleantmp:\n");
print("\t-del *~ *.o *.obj *.sbr *.bsc *.pdb *.lib *.ilk *.exp 2>nul\n");
print("\t-del test_s.c test_c.c test.h 2>nul\n\n");

#print("ctags:\n");
#print("\tctags `find . -name \"*.[ch]\" | grep -v include/proto\.h`\n");
#print("\tctags --c-kinds=-p -a `find /usr/i686-pc-mingw32/sys-root/mingw/include -name \"*.[ch]\" | grep -v /CVS/`\n");
#print("\n");

#print("proto:\n");
#print("\tmkproto.pl printlib.c --private=printlib.h --public=proto_pub.h --srcdir=. --builddir=.\n");
#print("\n");

print("###############################\n");
print("# helpers\n");
print("###############################\n\n");

foreach my $helper (@helpers) {
	my $obj = $helper;
	$obj =~ s/.c$/.obj/g;
	printf("%s: %s\n\n", $obj, $helper);
	push(@helpers_objs, $obj);
}

print("###############################\n");
print("# binaries\n");
print("###############################\n\n");

foreach my $file (@files) {
	my $exe = $file;
	my $obj = $file;
	my $pdb = $file;
	$exe =~ s/.c$/.exe/g;
	$obj =~ s/.c$/.obj/g;
	$pdb =~ s/.c$/.pdb/g;
#	print "exe: $exe\n";
	printf("%s: %s\n\n", $obj, $file);
	printf("%s: %s %s\n", $exe, $obj, @helpers_objs);
	printf("\tcl \$(CFLAGS) /Fe\$@ %s %s \\\n", $obj, @helpers_objs);
	printf("\t/link /incremental:no /subsystem:console \$(LIBS) \$(WINSPOOL_LIBS)\n\n");
}
