#!/usr/bin/perl

# Routine to reformat the PDS IMG files in the Stardust directory into FITS 
# files with detached PDS labels in a new directory.

$SRCDIR = "../WORK/NAV_IMG_NEW";
$NEWDIR = "../data/navigation";
#$NEWDIR = "..";
$SPICEFILE = "../WORK/label_additions.tab";

$TMPLBL = "TMP.LBL";
$TMPHDR = "TMP.HDR";
$TMPDAT = "TMP.DAT";

opendir(SRC,$SRCDIR);
foreach $file (readdir(SRC))
  { next if ($file !~ /\.IMG$/);

    run_label($file);

    system "spltimg < $SRCDIR/$file | swpinv | fitspad -n > $TMPDAT";

    $fits = "$NEWDIR/$file";
    $fits =~ tr/A-Z/a-z/;
    $fits =~ s/\.img$/.fit/;

    system "cat $TMPHDR $TMPDAT > $fits";
    unlink $TMPHDR;
    unlink $TMPDAT;
 }
closedir(SRC);


#===========================================================================

sub run_label

  # Open image file, read it to create new PDS label and FITS header.

{ local ($file) = $_[0];
  my ($img,$label,$not_done);
  my ($fitsfile,$junk);

  $img = "$SRCDIR/$file";
  $label = "$NEWDIR/$file";
  $label =~ tr/A-Z/a-z/;
  $label =~ s/\.img/.lbl/;
  $fitsfile = $file;
  $fitsfile =~ s/IMG/FIT/;

    $sfile = "$file";
    $sfile =~ tr/A-Z/a-z/;
    $sfile =~ s/\.img$//;

  # Open the various files:

  open(IMG,$img) || die "Could not open source image pipe ($!)";
  open(LBL,"| fixlen -c > $label") || die "Could not open label pipe ($!)";
  open(HDR,"| fixlen -r 81 | mkstrm | fitspad >$TMPHDR") || 
    die "Could not open header pipe ($!)";

  # read the new spice info from the relevant file
  open(SPICE,$SPICEFILE) || die "Could not open source file";
  $not_done = 1;
  while (($line=<SPICE>) && $not_done)
    {if ($line =~ $sfile) 
        {@spice = split(/  /,$line);
         $sunvec = $spice[1];
         $enorth = $spice[2];
         $xpos = $spice[3];
         $ypos = $spice[4];
         } 
    }
  # Digging through the label file:

  $not_done = 1;
  while (($line=<IMG>) && $not_done)
    { next if ($line =~ /LABEL_RECORDS/);
      next if ($line =~ /CHECKSUM/);
      next if ($line =~ /MAXIMUM/);
      next if ($line =~ /MINIMUM/); 
      next if ($line =~ /^ *MEAN *=/);
      next if ($line =~ /STANDARD_DEVIATION/);

      if ($line =~ /RECORD_BYTES/)
        { $line =~ s/4096/2880/;}
      elsif ($line =~ /FILE_RECORDS/)
        { $line =~ s/1024/1455/; }

      elsif ($line =~ /LINES /)
        { $line =~ s/1022/1024/; }

      elsif ($line =~ /LINE_SAMPLES/)
        { $line =~ s/1024/1022/; }

      elsif ($line =~ /LINE_DISPLAY_DIRECTION/)
        { $line =~ s/'DOWN'/\"UP\"/; }

      elsif ($line =~ /\^IMAGE/)
        { printf LBL "^FITS_HEADER                   = (\"$fitsfile\",1)\n";
          $line =~ s/3/("$fitsfile",2)/;
        }

      elsif ($line =~ /SAMPLE_TYPE/)
        { printf LBL "  AXIS_ORDER_TYPE              = \"FIRST_INDEX_FASTEST\"\n";
          printf LBL "  UNIT                         = \"W/m^2/sR\"\n";
          $line =~ s/PC_REAL/IEEE_REAL/;
        } 
      elsif ($line =~ /^\s*END\s*$/)
        { $not_done = 0; }

      elsif ($line =~ /^\s*OBJECT\s+=/)
        { printf LBL "OBJECT                         = FITS_HEADER\n";
          printf LBL "  HEADER_TYPE                  = \"FITS\"\n";
          printf LBL "  BYTES                        = 2880\n";
          printf LBL "  RECORDS                      = 1\n";
          printf LBL "END_OBJECT                     = FITS_HEADER\n";
          printf LBL "\n";
        }

      elsif ($line =~ /MISSING_CONSTANT/)
        { $line =~ s/=.*$/= 0.00/; }

      elsif ($line =~ /_DISPLAY_DIRECTION/)
        { $line =~ s/'/"/g; }                     #'

      elsif ($line =~ /START_TIME\s*=\s*(\S+)\s/)
        { $start = $1; }

      elsif ($line =~ /STOP_TIME\s*=\s*(\S+)\s/)
        { $stop = $1; }

      elsif ($line =~ /TIME_FROM_CLOSEST_APPROACH\s*= (.*)</)
        { $cat_time = $1; }

      elsif ($line =~ /TARGET_NAME\s+=\s*"(.*)"/)
        { $target_name = $1; 
#          $line =~ s/N\/A/CALIBRATION_FIELD/;
#          $target_name =~ s/N\/A/CALIBRATION_FIELD/;
        }
      elsif ($line =~ /EXPOSURE_DURATION\s+=\s+([0-9.]+)</)
        { $exposure = $1; }

      elsif ($line =~ /MISSION_NAME/)
        { $junk = <IMG>; }  # Discard extra INSTRUMENT_HOST_NAME line 

      elsif ($line =~ /FRAME_SEQUENCE_NUMBER\s*=\s*(\S+)\s/)
        { $frame = $1; }

      elsif ($line =~ /SCAN_MIRROR_RATE/)
        { $line =~ s/SEC/SECOND/; }

      elsif ($line =~ /RIGHT_ASCENSION\s*= (.*)</)
        { $ra = $1; }

      elsif ($line =~ /DECLINATION\s*= (.*)</)
        { $dec = $1; }

      elsif ($line =~ /PHASE_ANGLE\s*= (.*)</)
        { $phase = $1; }

      elsif ($line =~ /TARGET_CENTER_DISTANCE\s*= (.*)</)
        { $range = $1; }

      elsif ($line =~ /HORIZONTAL_PIXEL_SCALE\s*= (.*)</)
        { $pixscl = $1; }

      elsif ($line =~ /TWIST_ANGLE\s+=\s+([0-9.]+)</)
        { $twist = $1; }

      $line =~ s/</ </;
      printf LBL $line;

      }
  close(IMG);
  close(LBL);


      $celn = 180.-$twist;
      if ($celn lt 0.) {$celn = $celn + 360.};
      @start_time = split(/T/,$start);
      @start_time1 = split(/Z/,$start_time[1]);
      @stop_time = split(/T/,$stop);
      @stop_time1 = split(/Z/,$stop_time[1]);

  # Writing the FITS header:

  printf HDR "SIMPLE  =                    T\n";
  printf HDR "BITPIX  =                  -32\n";
  printf HDR "NAXIS   =                    2\n";
  printf HDR "NAXIS1  =                 1022\n";
  printf HDR "NAXIS2  =                 1024\n";
  printf HDR "FRAMENUM= %20.20s / Frame sequence number\n", $frame;  
  printf HDR "MISSION = \'STARDUST\'\n";
  printf HDR "INSTRUM = \'NAVCAM\'\n";
  printf HDR "FILTER  = \'OPNAV\'\n";
  printf HDR "WAVELEN =                698.8 / Central wavelength of filter (nm)\n";
  printf HDR "DATE-OBS= %-20.20s / Date of observation\n", $start_time[0];
  printf HDR "STARTTIM= %-20.20s / Start time of observation\n", $start_time1[0];
  printf HDR "STOPTIME= %-20.20s / Start time of observation\n", $stop_time1[0];
  printf HDR "TARGET  = \'$target_name\'\n";
  printf HDR "EXPOSURE= %20.1f / Exposure time (ms)\n", $exposure;
  printf HDR "RA      = %20.20s / Right Ascension (deg)\n",$ra;
  printf HDR "DEC     = %20.20s / Declination (deg)\n",$dec;
  printf HDR "PHASE   = %20.20s / Solar phase angle (deg)\n",$phase;
  printf HDR "RANGE   = %20.20s / Spacecraft to target distance (km)\n",$range;
  printf HDR "CATIME  = %20.20s / Time from closest approach (days)\n", $cat_time;
  printf HDR "PIXSCALE= %20.20s / Pixel scale (m/pix)\n",$pixscl;
  printf HDR "TWISTANG= %20.3f / Twist angle (deg)\n", $twist;
  printf HDR "CELESTN = %20.3f / Celestial north clock angle (deg)\n", $celn;
  printf HDR "ECLIPTN = %20.3f / Ecliptic north clock angle (deg)\n", $enorth;
  printf HDR "SUNVEC  = %20.3f / Sunward vector clock angle (deg)\n", $sunvec;
  if ($xpos !~ -999)
  {printf HDR "X_POS   = %20.3f / Approximate X position of the target\n",$xpos};
  if ($xpos !~ -999)
  {printf HDR "Y_POS   = %20.3f / Approximate Y position of the target\n",$ypos};
   printf HDR "END\n";
  close(HDR);

  # That's it for the label.

  return;
  }

#=============================================================================