;+
; NAME:
;       iris_geocal_run()
;
; PURPOSE:
;       Takes the data produced by iris_geocal_prep (FUV) or
;       iris_sgflat_prep (NUV) and does some minor processing before
;       handing the data off to iris_spec_cal.
;
; CALLING SEQUENCE:
;       result=iris_geocal_run(filename=filename, [/pickfile, datadir=])
;
; INPUTS:
;       filename - an IDL save file with the Level 1.5 data in the form
;                  of index, data
;
; OPTIONAL INPUTS:
;
; KEYWORD PARAMETERS:
;       /pickfile - instead of supplying a filename variable, the user
;                   can pick the file starting from the datadir path
;       datadir - data directory for temporary and permanent storage
;                 of the data.  If nothing is specified then it uses
;                 the current working directory
;
; OUTPUTS:
;       result - filename of the IDL savefile containing the results
;
; OPTIONAL OUTPUTS:
;       None
;
; COMMON BLOCKS:
;       None
;
; PROCEDURES USED:
;       iris_spec_cal
;
; COMMENTS:
;
; EXAMPLES:
;  IDL> result1=iris_geocal_getdata(time_start, time_end, index, data, $
;     >                            datadir=datadir, /nosave)
;     > result2=iris_geocal_prep(index, data, datadir=datadir)
;     > result3=iris_geocal_run(filename=result2, datadir=datadir, /pickfile)
;
; MODIFICATION HISTORY:
;       Started 2014-June-30 by Sarah A. Jaeggli, Montana State University
;-

function iris_geocal_run, filename=filename, datadir=datadir, $
                          restorefile=restorefile, wave=wave, pickfile=pickfile

  if not keyword_set(datadir) then datadir=''

  if keyword_set(pickfile) then $
     filename=dialog_pickfile(path=datadir, filter='*_l1p5.sav', $
                              title='Please select a L1.5 file to process')

  restore, filename

;  img=median(float(data), dimension=3)
  img=mean(float(data), dimension=3, /nan)

  if wave eq 'FUV1' then img=img[0:2071,*]
  if wave eq 'FUV2' then img=img[2072:4143,*]

  ;clean up any stray bad pixels in the FUV
  if wave eq 'FUV1' or wave eq 'FUV2' then $
     img=iris_prep_despike(img, mode='bright', sigmas=3)

  dt=index[0].date_obs
  timestring=strmid(dt, 0,4) + $ ;year
             strmid(dt, 5,2) + $ ;month
             strmid(dt, 8,2) + $ ;day
             '_' + $
             strmid(dt,11,2) + $ ;hour
             strmid(dt,14,2) + $ ;min
             strmid(dt,17,2)     ;sec

  savename=datadir+timestring+'_'+wave+'_spec_cal.sav'

  iris_spec_cal, img, wave=wave, savefile=savename, $
                 restorefile=restorefile

  return, savename

end
