use strict;
use warnings;

open my $INMODEL, "+<", "gem.mdl";
binmode $INMODEL;


#parse the header for useful info
my $header_structure = "llffffffffffllllllllf";
read $INMODEL, my $header, 21*4;
my @header_array = unpack $header_structure, $header;

print join ", ", @header_array;

my $skin_count = $header_array[12];
my $skin_width = $header_array[13];
my $skin_height = $header_array[14];
my $vert_count = $header_array[15];
my $tri_count = $header_array[16];

#skip all the skins
seek $INMODEL, $skin_count* ($skin_width*$skin_height+4), 1;
#skip the text coords
seek $INMODEL, $vert_count*12, 1;
#skip the triangles
seek $INMODEL, $tri_count*16, 1;

until(eof $INMODEL)
{
	print tell $INMODEL;
	print "\n";
	read $INMODEL, my $isgroup, 4;
	$isgroup = unpack ("l", $isgroup);
	if($isgroup == 0)
	{
		print "ungrouped\n";
		#skip the frame header
		seek $INMODEL, 24, 1;
		for(my $j=0;$j<$vert_count;$j++)
		{
			#skip the vertex coords
			seek $INMODEL, 3, 1;
			#write a fixed normal
			print $INMODEL pack("C",int(rand(162)));
		}
		#fix the read head
		seek $INMODEL, 0, 1;
	}
	else
	{
		read $INMODEL, my $grouplength, 4;
		$grouplength = unpack ("l", $grouplength);
		print $grouplength;
		print " in group\n";
		#skip the group header
		seek $INMODEL, 8+$grouplength*4, 1;
		for(my $i =0; $i <$grouplength; $i++)
		{
			#skip the frame header
			seek $INMODEL, 24, 1;
			for(my $j=0;$j<$vert_count;$j++)
			{
				#skip the vertex coords
				seek $INMODEL, 3, 1;
				#write a fixed normal
				#write a fixed normal
				print $INMODEL pack("C",int(rand(162)));
			}
			#fix the read head
			seek $INMODEL, 0, 1;
		}
	}
}