import reflex
import numpy as np
import sys
try :
    from astropy.io import fits as fits
except:
    import pyfits as fits
import glob

if __name__ == '__main__':

  parser = reflex.ReflexIOParser()

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

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

  # get Kepler parameters:
  parameters= {}
  for p in sys.argv[1:]:
          parameters[p.split("=")[0]]= p.split("=")[1]

  #Define one output file for every input file:
  #outputs.out_sof = inputs.in_sof
  files = inputs.in_sof.files

  
  
  ntotal= 0
  flux_cube= []
  for ifile, file in enumerate(files):
      HDU= pyfits.open(file.name)
      nfiles= HDU[0].header['NFILES']
      ntotal= ntotal + nfiles
      if ifile ==0:
          objects=HDU[1].data.field('OBJECT')
          print(str(len(objects))+" objects in file "+file.name)
          objectdir={}
          for iobj, obj in enumerate(objects):
              if obj== "User_Sky_9":
                 obj= "User_Sky_12"
              objectdir[obj]= iobj
          flux=HDU[0].data * nfiles
      else:
          flux_new=HDU[0].data * nfiles
          objects_new=HDU[1].data.field('OBJECT')
          print(str(len(objects))+" objects in file "+file.name)
          for iobj, obj in enumerate(objects_new):
              if obj in objectdir:
                  old_iobj= objectdir[obj]
                  if old_iobj != iobj:
                      pass
                      #print("mismatch:"+str(iobj) + " " + str(old_iobj))
                  flux[:,old_iobj]= flux[:,old_iobj] + flux_new[:,iobj]
              else:
                      print("object not found"+str(iobj) + " " + obj)
      HDU.close()
  meanflux=flux/ntotal
  outname= parameters["--products-dir"] + "/" + \
                       (files[0].name).replace(".fits", "_onedcombined.fits").split("/")[-1]
  print("writing to file"+outname)
  HDU= pyfits.open(files[0].name)
  #HDU[0].header['nfiles']= ntotal
  HDU[0].header['CMETHOD']= '1DCOMBINE'
  HDU[0].data= meanflux
  HDU.writeto(outname, checksum=True)
  HDU.close()

  # create output SOF:
  outlist= list()
  outlist.append((reflex.FitsFile(outname,files[0].category,None,files[0].purposes)))
  newsof = reflex.SetOfFiles(inputs.in_sof.datasetName,outlist)
  outputs.out_sof = newsof

  
  #send output to EsoReflex:
  parser.write_outputs()

  sys.exit()
