#!/usr/bin/perl

# Routine to make preliminary PDS labels from the information in the 
# FITS headers of the IRIM FITS files.
#
# Format: % makelbl irim.fit
#
# Output is to irim.lbl
#
# 28 Apr 2006, A.C.Raugh
#=======================================================================

if (@ARGV==0)
  { die "Usage: makelbl irim.fits\n"; }

foreach $file (@ARGV)
  { if ($file !~ /\.fit/)
      { printf STDERR "$file is not a FITS file, is it?\n";
        next;
      }

    # Find and open files:

    $name = $file;
    $name =~ s/\.fit//;

    $outfile = "$name.lbl";

    $FILE = $file;
    $FILE =~ tr/a-z/A-Z/;

    open(FIT,$file) || die "Could not open $file for reading ($!)";
    open(LBL,"| ppodl -p >$outfile") || 
        die "Could not open $outfile for writing ($!)";

    # We'll completely parse the FITS header first, then write the label.

    $processing_level = ($file =~ /irim4/)? "2" : "3";
    $cc = 0;
    read FIT, $line, 80;
    $lc = 1;
    while ($line !~ /^END /)
      { if ($line =~ /^NAXIS1/)
          { $samples = substr($line,27,3); }
        elsif ($line =~ /^NAXIS2/)
          { $lines   = substr($line,27,3); }
        elsif ($line =~ /^OBJECT/)
          { $target = substr($line,11,60);
            $target =~ s/'\s+$//;
            if ($target =~ /HALLEY/)
              { $target = "1P/HALLEY 1 (1682 Q1)";
                undefine $target_desc if ($target_desc);
              }
            else
              { $target =~ s/\s+$//;
                $target_desc = $target;
                $target = "CALIBRATION";
              }
          }
        elsif ($line =~ /^FILE-NUM/)
          { $filenum = substr($line,24,6); }
        elsif ($line =~ /^DATE-OBS/)
          { $dd = substr($line,11,2);
            $mm = substr($line,14,2);
            $yy = substr($line,17,2);
            $date = "19$yy-$mm-${dd}T";
          }
        elsif ($line =~ /^TIME-OBS/)
          { $d = substr($line,20,10);
            $d = $d * 24.0;
            $hh = int($d);
            $d = ($d - $hh) * 60.0;
            $mm = int($d);
            $d = ($d - $mm) * 60.0;
            $ss = int($d + 0.5);
            $time = sprintf "%02d:%02d:%02d",$hh, $mm, $ss;
          }
        elsif ($line =~ /^LONG-OBS/)
          { $dd = substr($line,11,3);
            $mm = substr($line,15,2);
            $ss = substr($line,18,2);
            $val = ($dd * 1.0) + ($mm / 60.0) + ($ss / 3600.0);
            $obs_long = sprintf "%8.4f",$val;
          }
        elsif ($line =~ /^LAT--OBS/)
          { $s  = substr($line,11,1);
            $dd = substr($line,12,2);
            $mm = substr($line,15,2);
            $ss = substr($line,18,2);
            $val = ($dd * 1.0) + ($mm / 60.0) + ($ss / 3600.0);
            $obs_lat = sprintf "%s%07.4f",$s,$val;
          }
        elsif ($line =~ /^SYSTEM/)
          { $system = substr($line,11,8); }
        elsif ($line =~ /^OBSERVER/)
          { $line =~ /'(.*)'\s+$/;
            $observer = $1;
          }
        elsif ($line =~ /^INSTRUME/)
          { $instrument = substr($line,11,60);
            $instrument =~ s/'\s+$//;
          }
        elsif ($line =~ /^OBSVTORY/)
          { $observatory = substr($line,11,60);
            $observatory =~ s/'\s+//;
          }
        elsif ($line =~ /^LOCATION/)
          { $location = substr($line,11,60);
            $location =~ s/'\s+//;
          }
        elsif ($line =~ /^TELESCOP/)
          { $telescope = substr($line,11,60);
            $telescope =~ s/'\s+//;
          }
        elsif ($line =~ /^FILTER/)
          { $filter_name = substr($line,11,20);
            $filter_name =~ s/\s*'\s+//;
          }
        elsif ($line =~ /^BUNIT/)
          { $unit = substr($line,11,20);
            $unit =~ s/\s*'\s+//;
          }
        elsif ($line =~ /^DATAMIN/)
          { $minimum = substr($line,11,20);
            $minimum =~ s/\s+//g;
          }
        elsif ($line =~ /^DATAMAX/)
          { $maximum = substr($line,11,20);
            $maximum =~ s/\s+//g;
          }
        elsif ($line =~ /^BSCALE/)
          { $scale = substr($line,11,20);
            $scale =~ s/\s+//g;
          }
        elsif ($line =~ /^BZERO/)
          { $offset = substr($line,11,20);
            $offset =~ s/\s+//g;
          }
        elsif ($line =~ /^PIXSCALE/)
          { $val = substr($line,11,20);
            $val =~ s/\s+//g;
            $pixel_scale = "($val,$val)";
          }
        elsif ($line =~ /^COMMENT/)
          { $val = substr($line,10,70);
            $val =~ s/\s+$//;
            $val =~ s/"/''/g;
            $comment[$cc] = "  $val";
            $cc++;

            if ($line =~ /RAW /)
              { $processing_level = 1; }
          }
        elsif ($line =~ /^HISTORY/)
          { $val = substr($line,10,70);
            $val =~ s/\s+$//;
            $comment[$cc] = "  $val";
            $cc++;

            if ($line =~ /RAW /)
              { $processing_level = 1; }
          }

        # Next line:

        read FIT,$line,80;
        $lc++;
      }

    # Done with the FITS file.

    close(FIT);
    $lc = $lc / 36.0;
    $header_records = ($lc == int($lc))? $lc : (int($lc)+1);
    $lc = ($lines * $samples * 4) / 2800;
    $data_records   = ($lc == int($lc))? $lc : (int($lc)+1);
    $file_records = $header_records + $data_records;
    $start_time = $date . $time;

    # Clean-up on some keywords:

    undef $scale if ($scale == 1.0); 
    undef $offset if ($offset == 0.0);
    if (!$unit && $processing_level ==3)
      { $unit = "MICRO-JY/PIXEL"; }

    # Now we write the PDS label:

    printf LBL "PDS_VERSION_ID = PDS3\n\n";
    printf LBL "RECORD_TYPE = \"FIXED_LENGTH\"\n";
    printf LBL "RECORD_BYTES = 2880\n";
    printf LBL "FILE_RECORDS = $file_records\n\n";
    printf LBL "DATA_SET_ID = \"IHW-C-IRIMAG-3-EDR-HALLEY-V2.0\"\n";
    printf LBL "PRODUCT_ID = \"$name\"\n";
    printf LBL "PRODUCT_NAME = \"IHW IR IMAGE $filenum\"\n";
    printf LBL "PRODUCT_CREATION_TIME = 2006-04-28\n";
    printf LBL "\n";
    printf LBL "INSTRUMENT_HOST_NAME = \"IHW INFRARED STUDIES NETWORK\"\n";
    printf LBL "INSTRUMENT_HOST_ID = \"IRSN\"\n";
    printf LBL "INSTRUMENT_NAME = \"IHW INFRARED IMAGING DATA\"\n";
    printf LBL "INSTRUMENT_ID = \"IRIMAG\"\n";
    printf LBL "TARGET_NAME = \"$target\"\n";
    printf LBL "TARGET_DESC = \"$target_desc\"\n" if ($target_desc);
    printf LBL "START_TIME = $start_time\n";
    printf LBL "STOP_TIME = \"UNK\"\n";
    printf LBL "OBSERVATION_TIME = $start_time\n";
    printf LBL "FILTER_NAME = $filter_name\n";
    printf LBL "PROCESSING_LEVEL_ID = \"$processing_level\"\n";
    printf LBL "OBSERVATION_ID = \"$filenum\"\n";
    printf LBL "OBSERVER_FULL_NAME = \"$observer\"\n";
    printf LBL "\n";
    printf LBL "DESCRIPTION = \"\n";
    printf LBL "System code: $system\n";
    printf LBL "Observatory Info\n";
    printf LBL "            Name: $observatory\n";
    printf LBL "        Location: $location\n";
    printf LBL "  East Longitude: $obs_long\n";
    printf LBL "  North Latitude: $obs_lat\n";
    printf LBL "       Telescope: $telescope\n";
    printf LBL "      Instrument: $instrument\n";
    printf LBL "\n";
    printf LBL "Comments from the FITS header:\n";
    printf LBL "\n";
    for ($i=0; $i<$cc; $i++)
      { printf LBL "$comment[$i]\n"; }
    printf LBL "\"\n";
    printf LBL "\n";
    printf LBL "NOTE = \"\n";
    printf LBL "  The START_TIME listed is actually the OBSERVATION_TIME,\n";
    printf LBL "  i.e., the midpoint of the observation.  Exposure times\n";
    printf LBL "  were not reported, so it was not possible to determine\n";
    printf LBL "  the actual starting time of the observation.  However, \n";
    printf LBL "  START_TIME is a keyword used to search for data across\n";
    printf LBL "  large sections of the PDS archives, so the midpoint \n";
    printf LBL "  time has been repeated as the START_TIME to prevent \n";
    printf LBL "  these data being lost for want of a more accurate\n";
    printf LBL "  value.\n";
    printf LBL "  \"\n";
    printf LBL "\n";
    printf LBL "^FITS_HEADER = (\"$file\",1)\n";
    printf LBL "^IMAGE       = (\"$file\",%d)\n",$header_records+1;
    printf LBL "\n";
    printf LBL "OBJECT = FITS_HEADER\n";
    printf LBL "HEADER_TYPE = \"FITS\"\n";
    printf LBL "RECORDS = %d\n",$header_records;
    printf LBL "BYTES = %d\n", $header_records * 2880;
    printf LBL "DESCRIPTION = \"FITS Standard NOST 100-2.0\"\n";
    printf LBL "END_OBJECT = FITS_HEADER\n";
    printf LBL "\n";
    printf LBL "OBJECT = IMAGE\n";
    printf LBL "LINES = $lines\n";
    printf LBL "LINE_SAMPLES = $samples\n";
    printf LBL "SAMPLE_BITS = 32\n";
    printf LBL "SAMPLE_TYPE = \"MSB_INTEGER\"\n";
    printf LBL "UNIT = \"$unit\"\n" if ($unit);
    printf LBL "PIXEL_ANGULAR_SCALE = $pixel_scale\n";
    printf LBL "AXIS_ORDER_TYPE = \"FIRST_INDEX_FASTEST\"\n";
    printf LBL "LINE_DISPLAY_DIRECTION = \"DOWN\"\n";
    printf LBL "SAMPLE_DISPLAY_DIRECTION = \"RIGHT\"\n";
    printf LBL "DERIVED_MAXIMUM = $maximum\n" if ($maximum);
    printf LBL "DERIVED_MINIMUM = $minimum\n" if ($minimum);
    printf LBL "OFFSET = $offset\n" if ($offset);
    printf LBL "SCALING_FACTOR = $scale\n" if ($scale);
    printf LBL "END_OBJECT = IMAGE\n";
    printf LBL "\n";
    printf LBL "END\n";

    # Done with the label:

    close(LBL);

    # Next file:

  }