#!/usr/bin/perl

my $gcluto_batch = "./gcluto-batch";

main();


sub main()
{
   my $IN = 3;
   my $OUT = STDOUT;
   
   if (scalar(@ARGV) != 2) { Usage(); exit(1); }
   
   my ($dataFile, $partFile) = @ARGV;
   
   open($IN, "$gcluto_batch '$dataFile' '$partFile' |") or die;
   
   WriteVRML($IN, $OUT);
   
   close($IN);
}


sub WriteVRML()
{
   my ($IN, $OUT) = @_;
   my ($width, $height, $x, $y, $z, $a, $b, $c, $d, $i);
   my @line;
   my $maxheight = 60;
   my $flagheight = 40;
   my $nclusters;
   my $label;
   
   ($width, $height) = split '\t', <$IN>;
   
########   
   print $OUT <<EOF;
#VRML V2.0 utf8
DEF terrain Coordinate { point [ 
EOF
#######
   
   for ($y=0; $y<$height; $y++) {
      @line = split '\t', <$IN>;
      for ($x=0; $x<$width; $x++) {
         printf $OUT "%d %d %.2f,", $x, $y, $maxheight * $line[$x];
      }
   }

#######
   print $OUT <<EOF;
]}
         
DEF colors Color { color [ 
EOF
#######

   for ($y=0; $y<$height; $y++) {
      @line = split ' ', <$IN>;
      for ($x=0; $x<$width; $x++) {
         printf $OUT "%.2f %.2f %.2f,", 
                     $line[3*$x], $line[3*$x+1], $line[3*$x+2];
      }
   }
   
   $a = -$width/2 * .1;
   $b = -$height/2 * .1;
   
#######   
   print $OUT <<EOF;
]}

Transform { translation $a $b 0 children [         
Transform {
   rotation 1 0 0 -.8
   scale .1 .1 .1

   children [
      Shape {   
           geometry IndexedFaceSet { coordIndex [ 
EOF
######

   for ($y=0; $y<$height-1; $y++) {
      for ($x=0; $x<$width-1; $x++) {
         $a = $x + ($y * $width);
         $b = $a + 1;
         $c = $a + $width;
         $d = $c + 1;
         printf $OUT "%d,%d,%d,-1,%d,%d,%d,-1,", $a, $b, $c, $c, $b, $d;
      }
   }

######
   print $OUT <<EOF;
] coord USE terrain color USE colors }} 
EOF
######

   $nclusters = <$IN>;
   for ($i=0; $i<$nclusters; $i++) {
      ($label, $y, $x, $z) = split '\t', <$IN>;
      
      printf $OUT "Shape{geometry IndexedLineSet{ coordIndex [0,1,-1] ".
         "color Color { color [1 1 1, 1 1 1] } ".
         "coord Coordinate { point [ %d %d %.1f, %d %d %d]}}} ", 
        $x, $y, $z * $maxheight, $x, $y, $flagheight;
      printf $OUT "Transform { rotation 1 0 0 1.6 translation $x $y $flagheight ".
                  "children Billboard { children [ Text { ".
                  "string \"$label\" fontStyle FontStyle { size 5 }} ]} }";
   
   }

######
print $OUT <<EOF;
]}
]}
EOF
######
}


sub Usage()
{
   print "mtn-vrml <datafile.mat> <solution.clustering.x>\n";
}
