# args: $translationFileName $mapFileName $outputMapFileName $materialDir

$translationFileName = shift;
$mapFileName = shift;
$outputMapFileName = shift;
$materialDir = shift;

open TRANSLATIONFILE, "<$translationFileName" || die;
while( <TRANSLATIONFILE> )
{
	if( /^(\S+)\s+(\S+)$/ )
	{
		$lval = $1;
		$rval = $2;
		$rval =~ s/\.tga/\.vmt/i;
		$lval =~ tr/A-Z/a-z/;
#		print "\"$lval\"->\"$rval\"\n";
		$trans{$lval} = $rval;
	}
}

close TRANSLATIONFILE;

open INPUTMAPFILE, "<$mapFileName" || die;
open OUTPUTMAPFILE, ">$outputMapFileName" || die;
while( $inputLine = <INPUTMAPFILE> )
{
	# ( -456 -352 352 ) ( -456 352 352 ) ( 376 352 352 ) DEV_MEASUREWALL01C [ 1 0 0 0 ] [ 0 -1 0 0 ] 0 1 1 0 0 0
	if( $inputLine =~ /^(\s*\(\s*\S+\s+\S+\s+\S+\s*\)\s*\(\s*\S+\s+\S+\s+\S+\s*\)\s*\(\s*\S+\s+\S+\s+\S+\s*\)\s*)(\S+)(\s+.*)/ )
	{
		$oldname = $2;
		$oldname =~ tr/A-Z/a-z/;

		if( defined $trans{$oldname} )
		{
			print OUTPUTMAPFILE "$1$trans{$oldname}$3\n";
		}
		else
		{
			if( !defined $alreadyComplained{$oldname} )
			{
				print STDERR "error: no mapping for \"$oldname\".\n";
				$alreadyComplained{$oldname} = 1;
			}
			print OUTPUTMAPFILE $inputLine;
		}
	}
	else
	{
		print OUTPUTMAPFILE $inputLine;
	}
}

close INPUTMAPFILE;
close OUTPUTMAPFILE;

# build vmt files for the new materials if they don't exist already
print "\n\n";
foreach $wadfile (keys %trans)
{
#	if( -e "$materialDir/$trans{$wadfile}" )
#	{
#		print "skipping $materialDir/$trans{$wadfile}\n";
#	}
#	else
	{
#		print "creating $materialDir/$trans{$wadfile}\n";
		open MATFILE, ">$materialDir/$trans{$wadfile}" || die;

		
		# output base texture with no file extension
		$textureName = $trans{$wadfile};
		$textureName =~ s/\.vmt//i;
		printf MATFILE "\$baseTexture = $textureName\n";

		# output surface props
		if( $wadfile =~ /^sky$/ )
		{
			print MATFILE "\$compileSky = true\n"
		}
		elsif( $wadfile =~ /^hint$/ )
		{
			print MATFILE "\$compileHint = true\n";
		}
		elsif( $wadfile =~ /^skip$/ )
		{
			print MATFILE "\$compileSkip = true\n";
		}
		elsif( $wadfile =~ /^nodraw$/ )
		{
			print MATFILE "\$compileNodraw = true\n";
		}
		elsif( $wadfile =~ /^origin/ )
		{
			print MATFILE "\$compileOrigin = true\n";
		}
		elsif( $wadfile =~ /^water/ )
		{
			print MATFILE "\$compileWater = true\n";
		}
		elsif( $wadfile =~ /^clip$/ )
		{
			print MATFILE "\$compileClip = true\n";
		}
		elsif( $wadfile =~ /^\%fog$/ )
		{
			print MATFILE "\$compileFog = true\n";
		}
		elsif( $wadfile =~ /^aaatrigger$/ )
		{
			print MATFILE "\$compileTrigger = true\n";
		}
		else
		{
			print MATFILE "\$shader = \"BaseTimesLightmap( \$baseTexture = \$baseTexture );\"\n";
		}
		close MATFILE;
	}
}
