#!/bin/perl 
#+
# deeplog -- generate logsheet data from image headers
#
# Purpose: 
#	Given a list of images, parse the image headers and print
#	out a formatted list of data.  With no arguments, parse all of
#	the images in the current directory.
#
# Usage:
#	deeplog [n | images] [-loop]
# 
# Arguments:
#	n       = number of latest images to parse.
#	images	= names of images to parse.  If no images are listed,
#			then all images in the current directory will be read
#			(EXCEPT for backup.fits).
#       -loop = enables the "looping" mode
# 
# Output:
#	to STDOUT
# 
# Restrictions
#	None
# 
# Note:
#	The output from this program is extra wide.	To print it, use
#	this command:
#		enscript -1r -c -f Courier9 -P lw4s
# 
# Exit values:
#	 0 = normal completion
#	 1 = wrong number of arguments
#
# Example:
#	1) Generate log data for all images in the current directory:
#		deeplog
# 
#	) Generate log data for the last 5 images in the current directory:
#		deeplog 5
# 
#	3) Generate log data for all images in the directory
#	/s/sdata1001/deimos1/2003jan01: 
#		deeplog /s/sdata1001/deimos1/2003jan01/*.fits
#-
# Modification history:
#	2002-Dec-30	GDW	Original version
#	2003-Aug-27	GDW	Changed TTIME to EXPTIME
#	2004-Oct-10	GDW	Added "last n images" option
#       2011-Jul-29     LR      Added the looping option
#-----------------------------------------------------------------------

use File::Basename;

# declarations...
$| = 1;
my( $observers, $date, $directory);
my( @images);
my( $i, $j);
my( $m, $n, $title_format);
my( %HeadValue);
my( $null) = 'INDEF';

# define logsheet fields...
&AddColumn( 'FILENAME',  'Filename', '%-10s ');
&AddColumn( 'TARGNAME', 'Obs Name', '%-14s ');
&AddColumn( 'ROTPOSN',  'PA', '%7.2f ');
&AddColumn( 'LAMPS',    'Lamps', '%-8s ');
&AddColumn( 'SLMSKNAM', 'Slitmsk', '%-7s ');
&AddColumn( 'GRATENAM', 'Grating', '%-7s ');
&AddColumn( 'WAVELEN',  'Waveln', '%7d ');
&AddColumn( 'DWFILNAM', 'Filter', '%-7s ');
&AddColumn( 'DWFOCVAL', 'Focus', '%7d ');
&AddColumn( 'EXPTIME',    'Exp', '%7d ');
&AddColumn( 'AIRMASS',  'Airmass', '%7.2f ');
&AddColumn( 'OBJECT',   'Comments', '%-30s ');

# check args...
die "Usage: $0 [images] [-loop]\n" if ( @ARGV < 0 );

# default mode is no looping
$loop_mode=0;

# build the image list
@images=&BuildImageList;

# parse args...
if (@ARGV) {
if ( @ARGV == 1 and $ARGV[0] =~ /^\d+$/ ) {
  $m = $ARGV[0];
  if ( $m > @images ) { $m = scalar(@images) };
  $m = -$m;
  @images = @images[ $m .. -1 ];	# extract last $m elements of image list
} elsif ( @ARGV ==1 and $ARGV[0] eq "-loop" ) {
    # enable looping
    $loop_mode=1;
}
else {
    # if we specify a list of images, then I assume we don't want to loop
    # even if the use specifies loop mode
  @images=();
  for ( my $i=0; $i<@ARGV; $i++) {
      if ($ARGV[$i] ne "-loop") {
	  push @images,$ARGV[$i];}
   }      
}
}

# verify number of images...
die "ERROR: No images found\n" 
  unless @images;

# get some information from the first DEIMOS image...
for( my $i=0 ; $i < @images ; $i++){
  %HeadValue = &GetFitsHead( $images[$i]);
  last if (defined($HeadValue{'INSTRUME'})
	   and $HeadValue{'INSTRUME'} =~ m/DEIMOS/)
}
die "ERROR: No DEIMOS images found\n" 
  unless $HeadValue{'INSTRUME'} =~ m/DEIMOS/;

# print header...
printf "\n";

printf "%-72s", "Project:";
printf "UT Date: %s", &BlankIfUndef($HeadValue{"DATE-OBS"});
printf "\n";

printf "%-72s", "Observers: " . &BlankIfUndef($HeadValue{"OBSERVER"});
printf "Weather:";
printf "\n";

printf "%-72s", "Data directory: " . &BlankIfUndef($HeadValue{"OUTDIR"});
printf "Seeing:";
printf "\n";

printf "\n";

&PrintHeader;

# loop over images...
for ( $j=0 ; $j<@images ; $j++ ) {
    ProcessImage ($images[$j]);

}

if ($loop_mode) {
# start the waiting loop
my $last_image=$images[@images-1];
my $counter=0;
while (1) {
@images=&BuildImageList;
PrintHeader;
my $current_last_image=$images[@images-1];

    if ($current_last_image ne $last_image) {

	$last_image=$current_last_image;
	$counter = $counter +1;
	if ($counter>20) {&PrintHeader;
			 $counter=0}

	ProcessImage($last_image);
	}
sleep(20);
}
}


#------------------------------------------------------------------
sub PrintHeader {
#------------------------------------------------------------------
$line = '';
for ( $i=0 ; $i<@X::keyword ; $i++ ) {
  $X::format[$i] =~ m/^%-?(\d+)/;
  $n = $1;
  $X::format[$i] =~ m/(\s+)$/;
  $space = $1;
  $buf = sprintf "%-${n}s$space", $X::title[$i];
  print $buf;
  $buf =~ s/./_/g;
  $line .= $buf;
}
printf "\n";
printf "$line\n";
}

#------------------------------------------------------------------
sub BuildImageList {
#------------------------------------------------------------------
# build default image list...
opendir DATADIR, '.';
my @images = sort grep /\.fits/, readdir DATADIR;
#@images =  sort @images ;
closedir DATADIR;

# expunge bad filenames from image list.
# NOTE: that we traverse the list BACKWARDS because we are removing elements from the list as we go...
for ( $i=@images-1 ; $i>=0 ; $i--){
  if( ($images[$i] =~ m/backup.fits/) or	# remove backup files
      ($images[$i] =~ m/^cam/) or		# remove cam files
      not ($images[$i] =~ m/.fits$/ or $images[$i] =~ m/.fits.gz$/)){
    splice( @images, $i, 1) 
    }
}


return @images;
}


#-----------------------------------------------------------------------
sub ProcessImage {
#-----------------------------------------------------------------------
    my $infile = shift;

  # read image header...
  %HeadValue = &GetFitsHead( $infile);

  # skip non-DEIMOS images...
  next unless (defined($HeadValue{'INSTRUME'})
	       and $HeadValue{'INSTRUME'} =~ m/DEIMOS/);

  # build filename field...
  $HeadValue{'FILENAME'} = (fileparse( $infile, '\..*'))[0];

  # fix grating/wavelength fields...
  if ( not defined $HeadValue{'GRATEPOS'}) {
    undef $HeadValue{'WAVELEN'}
  } elsif ($HeadValue{'GRATEPOS'} eq '3' ){
    $HeadValue{'WAVELEN'} = $HeadValue{'G3TLTWAV'}
  } elsif ( $HeadValue{'GRATEPOS'} eq '4' ){
    $HeadValue{'WAVELEN'} = $HeadValue{'G4TLTWAV'}
  } else {
    $HeadValue{'WAVELEN'} = $null;
  }

  # fix lamps...
  if ( defined $HeadValue{'LAMPS'} ){
    $HeadValue{'LAMPS'} =~ s/ //g; # trim blanks from lamps...
    if ( $HeadValue{'LAMPS'} =~ m/^off/i ){$HeadValue{'LAMPS'} = ""}
    if ( defined $HeadValue{'FLIMAGIN'} and 
	 $HeadValue{'FLIMAGIN'} !~ m/^off/i ){
      $HeadValue{'LAMPS'} .= "Dome/Im"
    }
    if ( defined $HeadValue{'FLSPECTR'} and 
	 $HeadValue{'FLSPECTR'} !~ m/^off/i ){
      $HeadValue{'LAMPS'} .= "Dome/Sp"
    }
  }

  # print results...
  for ( $i=0 ; $i<@X::keyword ; $i++ ) {
    if ( defined $HeadValue{$X::keyword[$i]} and 
	 $HeadValue{$X::keyword[$i]} ne $null ){
      $HeadValue{$X::keyword[$i]} =~ s/^\s+//; # remove leading whitespace
      $HeadValue{$X::keyword[$i]} =~ s/\s+$//; # remove trailing whitespace
      printf $X::format[$i], $HeadValue{$X::keyword[$i]}
    } else {
      $X::format[$i] =~ m/^%-?(\d+)/;
      $n = $1;
      if ( not defined $HeadValue{$X::keyword[$i]}){
	$buf = '?'
      } else {
	$buf = ''
      }
      printf "%-${n}s ", $buf;
    }
  }
  printf "\n";
}

#-----------------------------------------------------------------------
sub GetFitsHead {
#-----------------------------------------------------------------------
  
  # get file name to read header from
  my $infile = shift;
  my( $excess, $comment);
  
  # reset output hashes to null
  my %HeadValue = ();
  my %HeadComment = ();
  
  # open the file with a shared lock to prevent it being modified 
  # during reading...
  open TEST, "<$infile";
  flock TEST, 1;
  
  # open input file using appropriate method...
  if ($infile =~ /\.gz$/i) {
    open INFITS, "gunzip --stdout $infile |";
    $| = 1;	# enable autoflush on gunzip output
  } else {
    open INFITS, $infile;
  }  

  # initialize input variable to allow for end-of-header trapping
  $headline = "     ";
  
  # loop thru FITS file 80 bytes at a time until end-of-header mark found
  until (substr($headline,0,3) eq "END") {
    read INFITS, $headline, 80
      or die "unexpected end of file on read";
    chomp($headline);

    # identify keyword name from first 8 bytes
    $name = substr($headline, 0, 8);
    $rest = substr($headline,9);

    # strip extra spaces off of keyword names
    $name =~ s/\s//g;

    # test if value is a string, handle single quotes if it is
    if (substr($rest,0,2) eq " '") {
      $lastquote = index($rest, "'", 2);
      $value = substr($rest,2,$lastquote-2);
      ($excess, $comment) = split (/\//, substr($rest, $lastquote));

    } else {
      # otherwise split value from comment using / separator
      ($value, $comment) = split (/\//, $rest);
      $value =~ s/\s//g;
    }

    # add next value and comment to respective hashes
    unless ($name eq "END" or $name eq "") {
      $HeadValue{$name} = $value;
      $HeadComment{$name} = $comment;
    }
  }
  
  # close input FITS file
  close INFITS;
  close TEST;
  return %HeadValue;
}

#-----------------------------------------------------------------------
sub AddColumn {
#-----------------------------------------------------------------------
  my( $keyword, $title, $format) = @_;
  push( @X::keyword, $keyword);
  push( @X::title, $title);
  push( @X::format, $format);
}

#-----------------------------------------------------------------------
sub BlankIfUndef {
#-----------------------------------------------------------------------
  my( $value) = @_;
  if( defined $value){
    return $value
  } else {
    return ''
  }
}
