#!/usr/bin/python

#File info lister - an argument of '-d' will produce an ISIS dates list format
#(filename, HJD-2450000, seeing), and no flag or a '-i' will produce a full 
#list (filename, object, filter, HJD-2450000, CCDtemp, seeing, sky).
# An arg of -s will produce image statistics, and be much slower
#
#eg:
#  finfo *.fits 
#  finfo -d *.fits > ../register/dates

import os
import sys
import string
import improc
import globals


def help():
  "Usage information."
  print """FITS File header-card information lister - Usage:
    finfo [-d] [filenames]       or
    finfo [-i] [filenames]       or
    finfo [-s] [filenames]       or
    finfo [-o] [filenames]       or
    finfo [-p] [filenames]       or
    finfo [-h]

    -i gives: (filename, object, filter, HJD-2450000, CCDtemp, seeing, sky)
    -d gives ISIS dates file format (filename, HJD-2450000, seeing)
    -s gives filename, mean, sigma, min and max pixel values
    -o gives the same information as -d but for old (PARG camera) images
    -p gives the same information as -i but for old PARG images
    -h prints this usage information.
       """

flag='i'
if len(sys.argv)==1:
  help()
  sys.exit()                  #No arguments supplied, print usage and exit
elif sys.argv[1][0]=='-':
  flag=sys.argv[1][1:]
  args=sys.argv[2:]
else:
  args=sys.argv[1:]           #leave with 'args' a list of files to process

if (not args) or (flag=='h') or (flag=='?'):
  help()
  sys.exit()            #Print usage and exit

                    #Initial assumptions:
dostat=0            #Don't do any image statistics
dofwhmsky=0         #Don't calculate FWHM and Sky
needimage=0         #Don't need to load image data
needheaders=0       #Don't assume any existing header cards
needoldheaders=0    #Don't assume the old PARG CCD header format

if flag=='i':
  fmt="%(filename)-20s %(object)-9s %(filterid)1s %(pjd)8.5f  %(ccdtemp)5.1f  %(fwhm)5.2f %(sky)5d  %(secz)4.2f"
  header="#filename, object, filter, HJD-2450000.0, CCDtemp, FWHM, Sky, SecZ"
  needimage=1
  needheaders=1
  dofwhmsky=1
elif flag=='d':
  fmt="%(filename)-20s %(pjd)9.5f %(fwhm)5.2f"
  header="#filename, HJD-2450000.0, fwhm"
  needimage=1
  needheaders=1
  dofwhmsky=1
elif flag=='s':
  fmt="%(filename)-20s %(mean)7.1f %(noise)8.3f %(min)8.3f %(max)8.3f"
  header="#filename, mean, sigma, min, max"
  needimage=1
  dostat=1
elif flag=='o':
  fmt="%(filename)-20s %(pjd)9.5f %(fwhm)5.2f"
  header="#filename, HJD-2450000.0, fwhm"
  needoldheaders=1
  needimage=1
  dofwhmsky=1
elif flag=='p':
  fmt="%(filename)-20s %(object)-9s %(filterid)1s %(pjd)8.5f  %(fwhm)5.2f %(sky)5d  %(secz)4.2f"
  header="#filename, object, filter, HJD-2450000.0, FWHM, Sky, SecZ"
  needimage=1
  needoldheaders=1
  dofwhmsky=1
else:
  help()
  sys.exit()

#Add extra flags and format strings here for more output variations

print header
for f in args:
  if needimage:
    img=improc.FITS(f,'r')     #Load full image
  else:
    img=improc.FITS(f,'h')     #Load FITS headers only
  gotfwhm = 1
  try:
    if dofwhmsky and (not img.headers.has_key('FWHM')):
      img.fwhmsky()        #If there's no FWHM card, calculate FWHM and sky now
  except:
    gotfwhm = 0

#Calculate or grab any params we might want to print from the image header
  
  filename=os.path.basename(f)
  if needheaders:
    try:
      object=string.strip(img.headers['OBJECT'][1:-1])
    except:
      object=''
    try:
      exptime=float(img.headers['EXPTIME'])
    except:
      try:
        exptime = float(img.headers['PEXP'])
      except:
        exptime = 0.0
    try:
      dateobs=string.strip(img.headers['DATE-OBS'][1:-1])
    except:
      dateobs = ''
    try:
      timeobs=string.strip(img.headers['TIME-OBS'][1:-1])
    except:
      timeobs = ''
    try:
      filterid=string.strip(img.headers['FILTERID'][1:5])
    except:
      filterid = ''
    try:
      secz=float(img.headers['SECZ'])
    except:
      secz = 0.0
    try:
      hjd = float(img.headers['PHJDMID'])
    except:
      try:
        hjd = float(img.headers['HJD'])
      except:
        hjd = 0.0
    if hjd <> 0:
      pjd = hjd - 2450000.0
    else:
      pjd = 0
    try:
      ccdtemp=float(img.headers['CCDTEMP'])
    except:
      ccdtemp = 0.0
  if needoldheaders:
    try:
      object=string.strip(img.headers['OBJECT'][1:-1])
      exptime=float(img.headers['EXPTIME'])
      dateobs=string.strip(img.headers['DATE-OBS'][1:-1])
      timeobs=string.strip(img.headers['TIME-OBS'][1:-1])
      filterid=string.strip(img.headers['FILTER'][1])
      secz=float(img.headers['AIRMASS'])
      hjd=float(img.headers['HJD'])
      pjd=hjd-2450000.0
    except:
      pass     #Assume missing headers aren't needed, or get an error from fmt
  if dostat:
    noise=img.noise()
    mean=img.mean()
    max=img.max()
    min=img.min()
  if dofwhmsky:
#    if not img.headers.has_key('FWHM'):
#      img.fwhmsky()    #If there's no FWHM card, calculate FWHM and sky now
    if gotfwhm and img.headers.has_key('FWHM'):
      fwhm=float(img.headers['FWHM'])
      try:
        sky=float(img.headers['SKY'])
      except:
        sky = 0
    else:
      fwhm = 0
      sky = 0

  
  print fmt % vars()      #Print the data using the format string

