#!/usr/bin/perl

# Take a stream of numbers of length <numrows> * <numcols> numbers and
# create a <numrows> by <numcols> image from them.  Stretches min to
# 0 and max to 255.

# Matt Dailey 2000

# Check args, usage

if (@ARGV != 2) {
  print STDERR "usage: flt_to_img.pl <numrows> <numcols>\n";
  exit -1;
}
$numrows = shift;
$numcols = shift;
if ($numrows <= 0 || $numcols <= 0) { die "use non-neg ints for rows/cols!"; }
$num_expected = $numrows * $numcols;

# Read the data from standard input.

@data = ();
$num = 0;
$min = 1e+100;
$max = -1e+100;
while(<>) {
  chop; 
  @tdata = split(/\s+/);
  for ($i=0; $i<@tdata; $i++) {
    $data[@data] = $tdata[$i]; $num++;
    if ($tdata[$i] < $min) { $min = $tdata[$i]; }
    if ($tdata[$i] > $max) { $max = $tdata[$i]; }
  }
}
$num == $num_expected || die "numrows/numcols inconsistent with data size";

# Output as a PGM image

print "P2\n$numrows $numcols\n255\n";
$index = 0;
for ($i=0; $i<$numrows; $i++) {
  for ($j=0; $j<$numcols; $j++) {
    $val = int(($data[$index] - $min) / ($max - $min) * 255);
    if ($val > 255 || $val < 0) { die "impossible error"; }
    if ($j>0) { print " "; }
    print "$val";
    $index++;
  }
  print "\n";
}

