#!/usr/bin/perl -w

# Fixes .rc files generated by Microsoft Developer Studio so that windres will
# correctly interpret them. To ensure correct paths to files, execute this script
# from the same place you will execute windres.

use strict;

my $Infile;
my $Outfile;
my $PathPrefix;

# Process command line arguments
for ( my $i = 0; $i < scalar @ARGV; $i++ ) {{

	# Output file
	if ( $ARGV[$i] =~ /^-o/i ) {
		if ( $ARGV[$i] =~ /^-o$/i ) {
			$i++;
			if ( $i < scalar @ARGV ) {
				$Outfile = $ARGV[$i];
			}
		} else {
			$ARGV[$i] =~ /(?<=-o)(.*)/i;
			$Outfile = $1;
		}
		next;
	}

	# Input file
	$Infile = $ARGV[$i];
}}

unless ( $Infile and $Outfile ) {
	die "Usage: $0 <input file> -o <output file>\n\n";
}

if ( $Infile =~ /.*(?=\/.*$)/ ) {
	$PathPrefix = "$&/";
} else {
	$PathPrefix = "";
}

open( INFILE, $Infile ) or die "\nError: Couldn't open INPUT file $Infile: $!";
open( OUTFILE, ">$Outfile" ) or die "\nError: Couldn't open OUTPUT file $Outfile: $!";

print "Converting $Infile for use with windres...\n";

# first define missing constants and include needed files
print OUTFILE << "marker";
// This file is a windres compatible version of $Infile
// It was fixed by $0 (perl $])

// afxres.h cannot be redistributed, so define constants and include files needed here
#ifndef _MSC_VER

 #include <windows.h>

 #ifndef IDC_STATIC
  #define IDC_STATIC (-1)
 #endif

 #ifndef DS_SHELLFONT
  #define DS_SHELLFONT (DS_SETFONT | DS_FIXEDSYS)
 #endif

#endif

marker

while ( my $line = <INFILE> ) {
	chomp $line;
	if ( $line =~ /^\#include \"afxres.h\"/ ) {
		print OUTFILE "#ifdef _MSC_VER\n";
		print OUTFILE "$line\n";
		print OUTFILE "#endif\n";
	} else {
		# add NOT WS_POPUP to all windows with WS_CHILD specified
		$line =~ s/(?<!NOT\s)(WS_CHILD)/$1 \| NOT WS_POPUP/;

		# Fix FONT statements (remove rubbish after font name)
		if ( $line =~ /(^FONT\s+\w+,\s*".*")/ ) {
			$line = $1;
		}

		# prepend the path to the original .rc file to all bitmap, font, and icon resources with a relative path
		if ( $line =~ /^\w+\s+(BITMAP|FONT|ICON)\s/ ) {
			$line =~ s/(?<=")([^:]+")/$PathPrefix$1/;
		}

		print OUTFILE "$line\n";
	}
}

close( OUTFILE );
close( INFILE );
