#!/usr/bin/env python

import reflex 
import sys
import os
try: 
    import pyfits
    import math
    import_ok = 1
#except ImportError:
except ImportError:
    import_ok = 0


if __name__ == '__main__':

  parser = reflex.ReflexIOParser()

  #Define inputs
  parser.add_option("-i", "--in_sof", dest="in_sof")
  #Define outputs
  parser.add_output("-o", "--out_sof", dest="out_sof")

  inputs  = parser.get_inputs()
  outputs = parser.get_outputs()

  #Retrieve input
  in_sof = inputs.in_sof

  #Get the input files
  files = in_sof.files

  #Do the stuff
  if import_ok == 0:
      outputs.out_sof = inputs.in_sof
      parser.write_outputs()
      sys.exit()

  for file in files:
    if file.category == 'TRACE_TABLE_06':
      static = pyfits.open(file.name,mode='readonly')
      newdata = static[1].data
      #print file.name
      #raw_input("found trace table 6 in the static calibration:")

  for file in files:
    #if file.category == 'TRACE_TABLE' and file.name == 'TRACE_TABLE-06.fits':
    if os.path.basename(file.name) == 'TRACE_TABLE-06.fits':
      #print file.name
      #raw_input("press a key:")
      # print file.name
      #print "I am going to change file ",file.name
      #raw_input("press a key:")
      hdulist = pyfits.open(file.name,mode='update')
      DataTable = hdulist[1].data
      Width = DataTable.field('Width')
      # newdata = hdulist[0].data / 2
      total = sum(Width)
      #print total
      if math.isnan(total):
        hdulist[1].data = newdata
        hdulist.flush()
        DataTable = hdulist[1].data
        Width = DataTable.field('Width')
        # newdata = hdulist[0].data / 2
        total = sum(Width)
        #print total
     #print "Mapped science mos ",file.name, "has been divided by 2"

  #print total
  #Set the output 
  outputs.out_sof = inputs.in_sof
  parser.write_outputs()

  #raw_input("press a key - almost done:")

  sys.exit()
