def log_invocation(fn='/tmp/reflex_invoc.log'):
    """ log invocation of actor for easy reexecution with:
        eval $(cat /tmp/reflex_invoc.log)
    """
    import sys
    #import os
    #if 'REFLEX_DEBUG' not in os.environ:
    #    return
    try:
        with open(fn, 'w') as f:
            s = " ".join(['"%s"' % x for x in sys.argv])
            f.write('python ' + s + '\n')
    except:
        pass


# import the needed modules
try:
  import numpy
  import pyfits
  import wx
  import matplotlib
  from pipeline_product import *
  matplotlib.use('WXAgg')
  import_sucess = 'true'

#NOTE for developers: 
# -If you want to modify the current script to cope
#  with different parameters, this is the function to modify:
#  setInteractiveParameters()
# -If you want to modify the current script to read different data from
#  the input FITS, this is the function to modify:
#  readFitsData()                  (from class DataPlotterManager) 
# -If you want to modify the current script to modify the plots (using the same
#  data),  this is the function to modify:
#  plotProductsGraphics()          (from class DataPlotterManager)
# -If you want to modify the text that appears in the "Help" button,
#  this is the function to modify:
#  setWindowHelp()
# -If you want to modify the title of the window, modify this function:
#  setWindowTitle()


  #This class deals with the specific details of data reading and final plotting.
  class DataPlotterManager:
    # This function will read all the columns, images and whatever is needed
    # from the products. The variables , self.plot_x, self.plot_y, etc...
    # are used later in function plotProductsGraphics().
    # Add/delete these variables as you need (only that plotProductsGraphics()
    # has to use the same names).
    # You can also create some additional variables (like statistics) after
    # reading the files.
    # If you use a control variable (self.xxx_found), you can modify 
    # later on the layout of the plotting window based on the presence of 
    # given input files. 
    # sof contains all the set of frames
    def readFitsData(self, fitsFiles):
      #Control variable to ced_heck if the interesting files where at the input
      self.red_sci_point_mos_found = False
      self.cubify = False

      #Read all the products
      hdus = dict()
      from collections import defaultdict
      frames = defaultdict(list)

      list_hdus_sci_redl = list()
      list_hdus_sci_redu = list()
      list_hdus_err_sci_redl = list()
      list_hdus_err_sci_redu = list()
      list_sci_redl = list()
      list_sci_redu = list()
      list_err_sci_redl = list()
      list_err_sci_redu = list()

      for frame in fitsFiles:
        if frame == '' :
          continue
        pipe_product = PipelineProduct(frame)
        hdulist = pipe_product.hdulist()
  
        hdus_item = dict()
        #hdulist = frame.hdulist()
        category = frame.category
        frames[category].append(frame)
                    




        print category, frame.name
        if category == "MWXB_SCI_REDL" :
           list_sci_redl.append(frame)
           hdus_item[category]=hdulist
           list_hdus_sci_redl.append(hdus_item[category])

           
           #print category
        elif category == "MWXB_SCI_REDU" :
           list_sci_redu.append(frame)
           hdus_item[category]=hdulist
           list_hdus_sci_redu.append(hdus_item[category])
           #print category


        elif category == "ERR_MWXB_SCI_REDL" :
           list_err_sci_redl.append(frame)
           hdus_item[category]=hdulist
           list_hdus_err_sci_redl.append(hdus_item[category])

           
           #print category
        elif category == "ERR_MWXB_SCI_REDU" :
           list_err_sci_redu.append(frame)
           hdus_item[category]=hdulist
           list_hdus_err_sci_redu.append(hdus_item[category])
           #print category


      naxis=list_hdus_sci_redl[0][0].header['NAXIS']
      if  naxis == 2  :
          nf = list_hdus_sci_redl[0].data.shape[0]
          self.cubify = True
          print "Sci Fibre cube format"
      else :
          nf = len(list_sci_redl)
          print "Sci fibre normal format"
      
      print "nf=", nf , "cubify = ", self.cubify

      #nf=4
      self.nfibres = nf
      self.list_spec_raw = []
      print "nf=",nf
      for i in range(nf):
        self.red_sci_point_mos_found = True
        if self.cubify == True :
           import pdb
           pdb.set_trace()
           spettra_l=list_hdus_sci_redl[0][i].data[:];
           self.list_spec_raw.append(UvesRedSpectrum(list_hdus_sci_redl[0].data[i,:],list_hdus_sci_redu[0].data[i,:],list_hdus_err_sci_redl[0].data[i,:],list_hdus_err_sci_redu[0].data[i,:]))
        else :
           self.list_spec_raw.append(FlamesUvesSpectrum(frames["MWXB_SCI_REDL"],
                                                  frames["MWXB_SCI_REDU"],i,
                                                  frames["ERR_MWXB_SCI_REDL"],
                                                  frames["ERR_MWXB_SCI_REDU"]))

          # self.list_spec_raw.append(UvesRedSpectrum(list_hdus_sci_redl[i],
          #                                        list_hdus_sci_redu[i],
          #                                        list_hdus_err_sci_redl[i],
          #                                        list_hdus_err_sci_redu[i]))
        #print "no of fibres", self.nfibres

    # This function creates all the subplots. It is responsible for the plotting 
    # layouts. 
    # There can different layouts, depending on the availability of data
    # Note that subplot(I,J,K) means the Kth plot in a IxJ grid 
    # Note also that the last one is actually a box with text, no graphs.
    def addSubplots(self, figure):
      if self.red_sci_point_mos_found == True :
        self.list_subplot_spec     = []
        #self.list_subplot_sn       = []
        #self.list_subplot_fwhm     = []
        #self.list_subplot_ripple   = []
        #self.list_subplot_linepos  = []
        nc=1
        nf=self.nfibres
        #print "nf=",nf
        for i in range(nf) :
          self.list_subplot_spec.append(figure.add_subplot(nf,nc,nc*i+1))
          #self.list_subplot_sn.append(figure.add_subplot(nf,nc,nc*i+3))
          #self.list_subplot_fwhm.append(figure.add_subplot(nf,nc,nc*i+4))
          #self.list_subplot_ripple.append(figure.add_subplot(nf,nc,nc*i+5))
          #self.list_subplot_linepos.append(figure.add_subplot(nf,nc,nc*i+6))
      else : 
        self.subtext_nodata     = figure.add_subplot(1,1,1)
          
    # This is the function that makes the plots.
    # Add new plots or delete them using the given scheme.
    # The data has been already stored in self.plot_x, self.plot_xdif, etc ...
    # It is mandatory to add a tooltip variable to each subplot.
    # One might be tempted to merge addSubplots() and plotProductsGraphics().
    # There is a reason not to do it: addSubplots() is called only once at
    # startup, while plotProductsGraphics() is called always there is a resize.
    def plotProductsGraphics(self, figure, canvas):
      if self.red_sci_point_mos_found == True :
        nf=self.nfibres
        for i in range(nf) :
          #print "fill i=",i
          #First subpanel: a spectrum
          if self.red_sci_point_mos_found == True :
            title_spec   = 'Extracted and Merged Spectrum (REDL,REDU) Fib: %d'% (i) 
            tooltip_spec = """Plot of the extracted and merged spectrum of the science object (blue line) as total flux (ADU) versus wavelength (Ang). 
The +-1 sigma uncertainties are plotted as the light blue region encompassing the object spectrum (and bounded by the light grey spectra). 
Note that this spectrum is not flux calibrated."""
            self.list_spec_raw[i].plot(self.list_subplot_spec[i], title_spec, tooltip_spec)

            #Second subpanel: a plot

            #Third subpanel: a plot

            #Fourth subpanel: a plot

            #Fifth subpanel: a plot
            if self.red_sci_point_mos_found == True :
              #self.subplot_linepos.set_ylim(0., self.list_spec_raw[i].qc_ex_ysize_low)
              #print 'nothing to do'
              continue
      else :
        #Data not found info
        self.subtext_nodata.set_axis_off()
        self.text_nodata = """Science object spectra not found in the products:
For Red data:  PRO.CATG=MWXB_SCI_REDL, MWXB_SCI_REDU"""
        self.subtext_nodata.text(0.1, 0.6, self.text_nodata, color='#11557c', fontsize=18,
                                 ha='left', va='center', alpha=1.0)
        self.subtext_nodata.tooltip='Science object spectra not found in the products'

  
    # This function specifies which are the parameters that should be presented
    # in the window to be edited.
    # Note that the parameter has to be also in the in_sop port (otherwise it 
    # won't appear in the window) 
    # The descriptions are used to show a tooltip. They should match one to one
    # with the parameter list 
    # Note also that parameters have to be prefixed by the 'recipe name:'
    def setInteractiveParameters(self):
      paramList = list()
#      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='debug','general','Whether or not to save intermediate results to local directory. [FALSE]'))
#      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='plotter','general',
#      """Any plots produced by the recipe are redirected to the
#         command specified by this parameter. The plotting command must
#         contain the substring 'gnuplot' and must be able to parse
#         gnuplot syntax on its standard input. Valid examples of such
#         a command may include 'gnuplot -persist' and 'cat >
#         mygnuplot$$.gp'. A finer control of the plotting options can
#         be obtained by writing an executable script, e.g. my_gnuplot.pl, that 
#         executes gnuplot after setting the desired gnuplot options
#         (e.g. set terminal pslatex color). To turn off plotting, set
#         this parameter to 'no'. [no]"""))

#      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='process_chip',group='general',"""For
#      RED arm data proces the redl, redu, or both chip(s). <both |
#      redl | redu | REDL | REDU> [both]"""))

      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='ext_method',group='extract',description="""Extraction method. <std | opt | fst | fop> [opt]"""))

#      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='cor_max_fnd',group='extract',description="""Find correlation maximum?. <N | Y> [Y]"""))

      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='cor_max_ rng',group='extract',description="""Correlation range size?. [6.0]"""))

      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='cor_max_ pnt',group='extract',description="""Correlation sampling points?. [25]"""))

      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='cor_def_off',group='extract',description="""Correlation center offset?. [0.0]"""))

      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='corvel_iter',group='extract',description="""Velocity correlation iteration number (SimCal). [1]"""))
      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='bias_method',group='extract',description="""Bias subtraction method. <M | V | N> [M]"""))
      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='bias_value',group='extract',description="""Bias value (only if bias_method = V). [200]"""))
#      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='cubify_sw',group='general',description="""Cubify switch. <Y | N> [N]"""))
      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='filt_sw',group='extract',description="""Filter switch. <none | median> [none]"""))
      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='bkg_max_io_win',group='background',description="""Background window number in each full inter order. [500]"""))
      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='bkg_xy_win_sz_x',group='background',description="""x maximum size of each background window:. [6]"""))
      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='bkg_xy_win_sz_y',group='background',description="""y maximum size of each background window:. [2]"""))
      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='pixel_thresh_max',group='BP',description="""Pixel saturation threshold max. [55000]"""))
      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='pixel_thresh_min',group='BP',description="""Pixel saturation threshold min. [-20]""")) 
#     paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='input_fmt_cube',group='general',description="""Input data format. [TRUE]"""))
#     paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='output_fmt_cube',group='general',description="""Output data format. [FALSE]"""))
      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='drs_k_s_thre',group='general',description="""Kappa sigma threshold. [10.0]"""))
#      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='drs_base_name',group='general',description="""Base name for science products. [fxb]"""))
      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='drs_maxyshift',group='extract',description="""Half width of the interval to scan for correlation, when determining y shift. [3.0]"""))
      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='drs_ext_w_siz',group='extract',description="""Integration window size good: 10 (if fibre deconvolution works fine). [10.0]"""))
      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='rebin.wavestep',group='rebin',description="""The bin size (in w.l.u.) in wavelength space. If negative, a step size of 2/3 * ( average pixel size ) is used. [-1.0]"""))
      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='rebin.scale',group='rebin',
      description="""Whether
      or not to multiply by the factor dx/dlambda (pixels per
      wavelength) during the rebinning. This option is disabled as
      default in concordance with the method used in the MIDAS
      pipeline. This option should be set to true to convert the
      observed flux (in pixel-space) to a flux per wavelength (in 
      wavelength-space). [FALSE]"""))

      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='merge',group='merge',
      description="""Order merging method. If 'optimal', the flux in the
      overlapping region is set to the (optimally computed, using the 
      uncertainties) average of single order spectra. If 'sum', the
      flux in the overlapping region is computed as the sum of the
      single order spectra. If flat-fielding is done, method 'optimal'
      is recommended, otherwise 'sum'. <optimal | sum> [optimal]"""))

      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='merge_delt1',group='merge',
      description="""Order merging left hand (short wavelength) cut. To reduce the
      amount of order overlapping regions we allow to cut short and
      long wavelength ranges. This may reduce the ripple possibly
      introduced by the order merging. Suggested values are: 10 
      (W<=390), 12 (390<W<=437, 520<W<=564), 14 (437<W<=520, 564<W). [0.0]"""))

      paramList.append(RecipeParameter(recipe='flames_obs_scired',displayName='merge_delt2',group='merge',
      description="""Order merging right hand (long wavelength) cut. To reduce the
      amount of order overlapping regions we allow to cut short and
      long wavelength ranges. This may reduce the ripple possibly
      introduced by the order merging. Suggested values is 4. [0.0]"""))


      return paramList

    def setWindowHelp(self):
      help_text = """
In this window, the user should check that the science object extracted spectrum is of a good quality by using the pan and zoom buttons at the top-left of this window. 
Attempt to optimise the S/N of the extracted spectrum as a function of spectral order (the upper plot of the bottom-left plots) by choosing different parameter values and re-running the pipeline recipe."""
      return help_text

    def setWindowTitle(self):
      title = 'Uves Interactive Spectrum Extraction'
      return title

except ImportError:
  import_sucess = 'false'
  print "Error importing modules pyfits, wx, matplotlib, numpy"

#This is the 'main' function
if __name__ == '__main__':
  log_invocation()

  # import reflex modules
  from reflex import *
  from reflex_interactive_app import *
  from pipeline_display import *

  # import UVES reflex modules
  from flames_plot_common import *

  # Create interactive application
  interactive_app = PipelineInteractiveApp()

  #Check if import failed or not
  if import_sucess == 'false' :
    interactive_app.setEnableGUI('false')

  #Open the interactive window if enabled
  if interactive_app.isGUIEnabled() :
    #Get the specific functions for this window
    dataPlotManager = DataPlotterManager()
    interactive_app.setPlotManager(dataPlotManager)
    interactive_app.showGUI()
  else :
    interactive_app.passProductsThrough()

  # print outputs
  interactive_app.print_outputs()

  sys.exit()
