#!/usr/local/bin/perl -w

sub range( $ )
{
    my $number = shift(@_);
    my $round  = int($number + .5 * ($number <=> 0));
    if (($round % 2) > 0)
    {
	return [ $round, ];
    }
    else
    {
	return [ $round-1, $round+1 ];
    }
}

my $file = shift @ARGV;

open(IN,"$file") || die();
open(OUT,">$file-cube") || die();

$read = "";
$read = <IN> until $read =~ /startCatoms/;

%space = ();
%idList = ();

while(chomp($read = <IN>))
{
    my ($Oid,$X,$Y,$Z,undef) = split(',',$read);

    my @rX = @{ range( $X ) };
    my @rY = @{ range( $Y ) };
    my @rZ = @{ range( $Z ) };

    for my $xx (@rX) {
	next unless ($xx > -1);
	for my $yy (@rY) {
	    next unless ($yy > -1);
	    for my $zz (@rZ) {
		next unless ($zz > -1);
		my $id = "";
		$id = rand() * 1000000 while(!$id && $id<20 && defined $idList{$id});
		$idList{ $id } = $Oid;
		$space{"$xx/$yy/$zz"} = int($id);
	    }
	}
    }
}

print OUT "# Cubic Representation of $file\n";
print OUT "EPSILON=0.01\n";
print OUT "GRAVITY=9.8\n";
print OUT "FRICTION=0.01\n";
print OUT "NUM_CATOMS=",scalar keys %space,"\n";
print OUT "CATOM_RADIUS=1\n";
print OUT "FEATURES=6\n";
print OUT "\n~startCatoms\n";

for my $coord (sort keys %space)
{
    if ($space{$coord})
    {
	print OUT "$space{$coord},";
    }
    else
    {
	my $id = "";
	$id = rand() * 1000000 while(!$id && $id<20 && defined $idList{$id});
	print OUT int($id),",";
    }
    my @C = split( '/', $coord );
    print OUT join(',',@C);
    print OUT ",1,1,3,0.25,0.25,0.25,0\n";
}
