#MNIST手書き数字データをJavaScriptに変換するスクリプト。
#2015/4/10

print "/**\n";
print " * THE MNIST DATABASE of handwritten digits\n";
print " * http://yann.lecun.com/exdb/mnist/\n";
print " * 1,000 from a test set of 10,000 examples,\n";
print " * and 6,000 from a train set of 60,000 examples.\n";
print " * Converted into JavaScript by Studio Kikoro 2015/4/10.\n";
print " */\n\n";

convert('TEST', 1000, 't10k-labels.idx1-ubyte', 't10k-images.idx3-ubyte');
convert('TRAIN', 6000, 'train-labels.idx1-ubyte', 'train-images.idx3-ubyte');

sub convert {
  local($type, $max, $labelFile, $imageFile) = @_;
  undef @Label;
  undef @Image;

  ##################### load label
  #print "----\n";
  #print "open label\n";
  open(F, $labelFile); binmode(F);
  sysread(F, $magic, 4); $magic = vec($magic, 0, 32); #print "magic=$magic\n";
  sysread(F, $count, 4); $count = vec($count, 0, 32); #print "count=$count\n";
  for ($i = 0; $i < $count; ++$i) {
      last if $max <= $i;
      sysread(F, $label, 1);
      $Label[$i] = $label;
  }
  #print "read=".@Label."\n";
  close(F);

  ##################### load image
  #print "----\n";
  #print "open image\n";
  open(F, $imageFile); binmode(F);
  sysread(F, $magic, 4); $magic = vec($magic, 0, 32); #print "magic=$magic\n";
  sysread(F, $count, 4); $count = vec($count, 0, 32); #print "count=$count\n";
  sysread(F, $Rows,  4); $Rows  = vec($Rows,  0, 32); #print "rows=$Rows\n";
  sysread(F, $Cols,  4); $Cols  = vec($Cols,  0, 32); #print "cols=$Cols\n";
  for ($i = 0; $i < $count; ++$i) {
      last if $max <= $i;
      sysread(F, $image, $Rows * $Cols);
      $Image[$i] = $image;
  }
  #print "read=".@Image."\n";
  close(F);

  ##################### print label
  print "var ".$type."_LABELS = [\n";
  for ($i = 0; $i < @Label; ++$i) {
      print " " if $i % 10 == 0;
      $label = $Label[$i];
      $label = vec($label, 0, 8);
      print "$label";
      print "," if $i < @Label - 1;
      print "\n" if $i % 10 == 9;
  }
  print "];\n\n";

  ##################### print image
  print "var ".$type."_PIXELS = [\n";
  for ($i = 0; $i < @Image; ++$i) {
      print " [\n";
      $image = $Image[$i];

      #28x28->14x14縮小。
      for ($row = 0; $row < $Rows; $row += 2) {
          print "  ";
          for ($col = 0; $col < $Cols; $col += 2) {
              $pixel =
                  (vec($image, ($row + 0) * $Cols + ($col + 0), 8) +
                   vec($image, ($row + 0) * $Cols + ($col + 1), 8) +
                   vec($image, ($row + 1) * $Cols + ($col + 0), 8) +
                   vec($image, ($row + 1) * $Cols + ($col + 1), 8)) / 4;
              print "$pixel";
              print "," unless $col == $Cols - 2 && $row == $Rows - 2;
          }
          print "\n";
      }

      print " ]";
      print "," if $i < @Image - 1;
      print "\n";
  }
  print "];\n\n";
}

