use strict;
use warnings;
use Params;

my %params = Params::get(qw/-i -o -t -T/);

my $infile = $params{-i};
my $sprefix = $params{-t};
my $tprefix = $params{-T};
my $sname = $params{-o};

open my $inmaterials, "<", $infile
	or die "$infile: $!";
open my $shaderfh, ">", $sname
	or die "$sname: $!";

sub gets()
{
	return 0
		unless defined ($_ = <$inmaterials>);
	y/\r//d;
	chomp;
	return 1;
}

while(gets())
{
	if(/^\[MaterialBegin\]$/)
	{
		my $name = "";
		my $flags = 0;
		my $opacity = 255;
		my $texture = "";
		my @color = (255, 255, 255);
		while(gets())
		{
			if(/^Name=\s*(.*)$/)
			{
				$name = $1;
			}
			elsif(/^Color24=\s*(.*)$/)
			{
				@color = split /\s+/, $1;
			}
			elsif(/^Opacity=\s*(.*)$/)
			{
				$opacity = $1;
			}
			elsif(/^Flags=\s*(.*)$/)
			{
				$flags = $1;
			}
			elsif(/^Texture=\s*(.*)$/)
			{
				$texture = $1;
				$texture =~ s/\.(jpg|png|tga|pcx|bmp)$//i;
			}
			elsif(/^\[MaterialEnd\]$/)
			{
				last;
			}
		}
		my $shader = "$sprefix$name";

		print $shaderfh "$shader\n";
		print $shaderfh "{\n";
		my @f = split /_/, $flags;
		if($f[0] eq 'texture')
		{
			print $shaderfh "	{\n";
			print $shaderfh "		map \"$tprefix$texture\"\n";
			print $shaderfh "	}\n";
		}
		elsif($f[0] eq 'solid')
		{
			print $shaderfh "	q3map_rgbgen const ( @{[map { $_ / 255.0 } @color]} )\n";
		}
		else
		{
			die "Invalid flag 0: $f[0]";
		}

		if($f[1] eq 'gouraud')
		{
			print $shaderfh "	{\n";
			print $shaderfh "		map \$lightmap\n";
			print $shaderfh "	}\n";
		}
		elsif($f[1] eq 'constant')
		{
			print $shaderfh "	surfaceparm nolightmap\n"; # fullbright
			# in theory, the thrid value is the solid value
		}
		else
		{
			die "Invalid flag 1: $f[1]";
		}
		print $shaderfh "}\n";
		print $shaderfh "\n";
	}
}

close $shaderfh;
