#!/usr/bin/perl

# convert an ASCII dpr file into a StateFile World (Version 1) file

# 1. Open DPR File
# 2. Open World File
# 3. Write out header info
# 4. Convert ASCII data to _sim data

sub main();

sub openDPR( $ );
sub openWorld( $ );
sub processData();

sub getNextDPRLine();

main();

sub main() {
    
    # arg processing -- dpr, world
    $dprFile = shift @ARGV;
    $worldFile = shift @ARGV;

    # 1
    openDPR( $dprFile );

    # 2 & 3
    openWorld( $worldFile );

    # 4
    processData();
}

sub getNextDPRLine() {
    while ($nextDPRLine = <DPR>) {
	next if (!$nextDPRLine);
	next if ($nextDPRLine =~ /^\s+\#/);
	next if ($nextDPRLine =~ /^\s+$/);
	return $nextDPRLine;
    }
    return ""; # eof
}


sub openDPR( $ ) {
    my $dprFileName = shift @_;

    die "Can't open DPR file $dprFileName\n" 
	unless open( DPR, "$dprFileName" );

}

sub openWorld( $ ) {
    my $worldFileName = shift @_;
    
    die "Can't open World file $worldFileName\n"
	unless open( WORLD, ">$worldFileName" );

    binmode( WORLD );

    my $magic = 0x434C4159;

    my $version = 1;
    my $modChunkId = 2;
    my $bodChunkId = 3;

    # file magic
    print WORLD pack("NC", $magic, 1); 
    # mod chunk
    print WORLD pack("CN", $modChunkId, 37);

    # _sim header
    print WORLD pack("C1a*NC1a*C1a*C1", 
		     4,"_sim", 1, 8, "cccCCCCC", 
		     17, "x:y:z:r:g:b:a:bat", 0 );
    # body chunk
    print WORLD pack("CN", $bodChunkId, 0xFFFFFFFF); 


}

sub processData() {
    
    # read in ASCII representation.
    
    # Format:
    #   catomId
    #   x,y,z
    #   yaw, pitch, roll
    #   r,g,b,a
    while ( $dprLine = getNextDPRLine() ) {
	chomp( $dprLine );
	my @line = split( ',', $dprLine );
	
	my $id = $line[0];
	
	# write out Version 1 _sim module data
	print WORLD pack("NNN", $id, 12, 8);
	print WORLD pack("cccCCCCC", 
			 $line[1], $line[2], $line[3],
			 $line[7] * 255, $line[8] * 255, $line[9] * 255, 
			 $line[10] * 255,
			 0);
    }



}
