#!/usr/bin/env perl

# Norman Kuring		30-Apr-2020	Initial development using methodology
#					provided by Alan Holmes.

use strict;

my ($file,$band) = @ARGV;

defined $file or die "Usage:
$0 HawkEye_L1A_file band_number
";
-e $file or die "The file \"$file\" does not exist\n";
$band =~ /^[1-8]$/ or die "The band must be an integer between 1 and 8.\n";

unless($file =~ /^\//){
  my $pwd = `pwd`;
  chop $pwd;
  substr($file,0,0) = "$pwd/";
}

### Set up a work space ####################################################
my $cleanup = &workspace;

my $cmd = "h5dump -d /earth_view_data/band_$band -b -o band $file 2>&1";
my $meta = `$cmd`;
my ($hgt,$wid) = $meta =~ /DATASPACE\s+SIMPLE\D+(\d+)\D+(\d+)/;
$wid == 1800 or die "Expected width=1800 got $wid instead.\n";

my $expected_size = $wid*$hgt*2;
my $actual_size = -s "band" ;
if($actual_size != $expected_size){
  die "Expected $wid*$hgt*2=$expected_size bytes of band data but got $actual_size bytes instead\n";
}

# Get the dark count values from the bottom of the image.
# Average the pixels from the last 32 lines of the image save 1.
my $offset = $actual_size - 33*$wid*2;
open F,'<',"band" or die "Could not open band ($!)";
seek F,$offset,0 or die "Error seeking to dark pixel area ($!)";
my @dark = (0) x $wid;
for(my $i=0; $i<32; $i++){
  my $data;
  read F,$data,$wid*2 or die "Error reading dark pixels ($!)";
  my @pix = unpack "S*",$data;
  @dark = map { $dark[$_] + $pix[$_] } 0 .. $#dark;
}
@dark = map $_/32, @dark;

# Read the flat-field values from Alan.
my $fffile = "/data1/work/code/HawkEye_flat_fields/GGG-Band${band}FlatFile.txt";
open FF,'<',$fffile or die "Could not open $fffile ($!)";
<FF>;<FF>;	# Skip two header records.
my @flat;
while(<FF>){
  push @flat, (split ' ')[1];
}
close FF;
# Put a 1 at the beginning to get 1800 values;
unshift @flat,1;

seek F,0,0;
my $data;
while(read F,$data,$wid*2){
  my @pix = unpack "S*",$data;
  @pix = map {
               my $v = int( ($pix[$_] - $dark[$_])/$flat[$_] + 0.5 );
               $v < 0 and $v = 0;
               $v > 65535 and $v = 65535;
               $v;
             } 0 .. $#pix;
  $data = pack "S*",@pix;
  print $data;
}
close F;

### Clean up the work space ################################################
&$cleanup;



# Create a workspace and go there then return a subroutine
# that will get rid of the workspace.
sub workspace{
  my $tmpdir = join '','/dev/shm/',(split /\//,$0)[-1],'.',time,'.',$$;
  mkdir $tmpdir,0755 or die "Could not create directory, $tmpdir ($!)";
  chdir $tmpdir or die "Could not cd to $tmpdir ($!)";
  return sub{
    chdir;
    system("/bin/rm -r $tmpdir") == 0 or die "Could not remove $tmpdir ($!)";
  };
}

sub doit{
  my $cmd = join ' ', split ' ', shift;
  system($cmd) == 0 or die "Error executing $cmd ($!)";
}
