;;	cassimg__dividebyefficiency.pro
;;	Correct image for filter and CCD efficiency
;;
;;	The calibration results files now include a file
;;	 "effic.db" which is a text database containing
;;	 conversion factors for the two instruments and their
;;	 planned and calibrated filter combinations.
;;
;;	Kevin	July 1999
;;	Version Tag: $Id: cassimg__dividebyefficiency.pro,v 1.4 2005/06/23 22:09:05 knowles Exp $

FUNCTION SolarDist, Body, YearFrac
@cisscal_common.pro	; include COMMON definitions

; Solar distances (AU) for Jupiter from 2000.0 to 2009.0 in 0.1 year steps
JupDist = [ 4.96531209, 4.97043011, 4.97626649, 4.98280033, 4.99000701, $
	4.99786044, 5.00633354, 5.01539707, 5.02502008, 5.03516791, $
	5.04580424, 5.05689199, 5.06839399, 5.08027419, 5.09249491, $
	5.10501721, 5.11780008, 5.13080135, 5.14398005, 5.15729571, $
	5.17070957, 5.18418253, 5.19767486, 5.21114744, 5.22456129, $
	5.23788017, 5.25106919, 5.26409409, 5.27692073, 5.28951380, $
	5.30183948, 5.31386544, 5.32556249, 5.33690387, 5.34786300, $
	5.35841424, 5.36853151, 5.37819054, 5.38736950, 5.39604814, $
	5.40420807, 5.41183029, 5.41889668, 5.42539041, 5.43129690, $
	5.43660528, 5.44130573, 5.44538972, 5.44884827, 5.45167242, $
	5.45385526, 5.45539160, 5.45627937, 5.45651748, 5.45610540, $
	5.45504350, 5.45333270, 5.45097724, 5.44798329, 5.44435876, $
	5.44011211, 5.43525080, 5.42978355, 5.42372039, 5.41707466, $
	5.40986241, 5.40210052, 5.39380701, 5.38499927, 5.37569643, $
	5.36591970, 5.35569215, 5.34503893, 5.33398469, 5.32255480, $
	5.31077520, 5.29867384, 5.28628203, 5.27363243, 5.26075930, $
	5.24769611, 5.23447592, 5.22113289, 5.20770216, 5.19422164, $
	5.18072977, 5.16726514, 5.15386612, 5.14057048, 5.12741800, $
	5.11444920 ]

; Solar distances (AU) for Saturn from 2000.0 to 2009.0 in 0.1 year steps
SatDist = [ 9.18396834, 9.1761802, 9.16855017, 9.16108198, 9.15377802, $
	9.14664156, 9.13967734, 9.13289014, 9.12628487, 9.11986437, $
	9.11363161, 9.10759036, 9.10174584, 9.09610518, 9.09067407, $
	9.08545719, 9.08045717, 9.07567627, 9.07111819, 9.06678709, $
	9.06268822, 9.05882520, 9.05520073, 9.05181736, 9.04867769, $
	9.04578622, 9.04314665, 9.04076177, 9.03863244, 9.03675812, $
	9.03513959, 9.03377846, 9.03267826, 9.03184165, 9.03126961, $
	9.03096216, 9.03091817, 9.03113819, 9.03162294, 9.03237298, $
	9.03338774, 9.03466487, 9.03620286, 9.03800070, 9.04005924, $
	9.04237937, 9.04496010, 9.04779927, 9.05089272, 9.05423742, $
	9.05783135, 9.06167325, 9.06576207, 9.07009469, 9.07466794, $
	9.07947815, 9.08452294, 9.08980088, 9.09530916, 9.10104413, $
	9.10699991, 9.11317104, 9.11955355, 9.12614476, 9.13294309, $
	9.13994497, 9.14714590, 9.15454014, 9.16212231, 9.16988869, $
	9.17783513, 9.18595757, 9.19425017, 9.20270675, 9.21132218, $
	9.22009224, 9.22901443, 9.23808479, 9.24729810, 9.25664757, $
	9.26612574, 9.27572722, 9.28544734, 9.29528251, 9.30522803, $
	9.31527787, 9.32542619, 9.33566724, 9.34599727, 9.35641205, $
	9.36690631 ]

IF Body EQ 'JUPITER' THEN BEGIN
  RETURN, INTERPOLATE(JupDist, (YearFrac-2000)*10)
ENDIF ELSE IF Body EQ 'SATURN' THEN BEGIN
  RETURN, INTERPOLATE(SatDist, (YearFrac-2000)*10)
ENDIF ELSE BEGIN
  IF DebugFlag gt 0 THEN CISSCAL_Log, 'Cannot understand I/F target parameter: ', Body
  RETURN, 0
ENDELSE

END



PRO CassImg::DivideByEfficiency

@cisscal_common.pro	; include COMMON definitions

units = '[unknown]'

if (*(*(*CalOptions).flux).ioverf).onoff then begin

; I/F mode ON:

    ; read in spectral file

    specfile = (*(*(*CalOptions).flux).ioverf).specfile

    if specfile eq '' then begin
        specfile = CalibrationBaseDir + 'efficiency/solarflux.tab'
        ang_to_nm = 10.
        pifact = !pi

        ; get distance from sun (AU):

        dfs_val = (*(*(*CalOptions).flux).ioverf).dfs
        
        if dfs_val le 0 then begin
            if dfs_val eq -1 then body = 'SATURN' else $
              if dfs_val eq -2 then body = 'JUPITER' else $
              body = 'UNKNOWN'

;	Get exposure timestamp, extract year and day, 
;        estimate decimal year of exposure
            ImgTime = self->GetLabel('IMAGE_TIME')
            ImgTimeY = STRMID(ImgTime,0,4)
            ImgTimeD = STRMID(ImgTime,5,3)
            ImgTimeYF = ImgTimeY + (ImgTimeD / 365.0)
            
            dfs = SolarDist(body,ImgTimeYF)

            IF DebugFlag gt 0 THEN CISSCAL_Log,'Solar distance is ',$
              strtrim(string(dfs),2),' AU'

        endif else begin
            dfs = dfs_val
        endelse

        if dfs le 0 then RETURN 
        
        units = 'I/F'

    endif else begin         
        ; for user-specified spectrum, lambda should be in nm,
        ; and flux in photons/cm^2/s/nm(/ster if not integrated
        ; over object)

        ang_to_nm = 1.
        dfs = 1.
        pifact = 1.

        units = 'flux normalized to user-input spectrum'

    endelse

    cisscal_readspec, specfile, lambda_f, flux, n_spec

    if n_spec eq 2l then RETURN

    lambda_f = temporary(lambda_f/ang_to_nm)
    flux = temporary(flux*ang_to_nm)

; now read in system transmission (T0*T1*T2*QE)

    transfile = CalibrationBaseDir + 'efficiency/systrans/' + $
                strlowcase(self.Instrument + self.Filter1 + self.Filter2) + $
                '_systrans.tab'

    if file_test(transfile) then begin
        cisscal_readspec, transfile, lambda_t, trans, n_trans
    endif else begin
        IF DebugFlag gt 0 THEN BEGIN
            CISSCAL_Log,'For IBatch = '+strtrim(string(IBatch),2)
            CISSCAL_Log,'  systrans file '+transfile+' not found. Skipping step...'
        ENDIF
        RETURN
    endelse

    if self.Instrument EQ 'ISSNA' then begin
        qecorrfile = CalibrationBaseDir + 'correction/nac_qe_correction.tab'
        cisscal_readspec, qecorrfile, lambda_q, qecorr, n_qecorr
    endif else if self.Instrument EQ 'ISSWA' then begin
        qecorrfile = CalibrationBaseDir + 'correction/wac_qe_correction.tab'
        cisscal_readspec, qecorrfile, lambda_q, qecorr, n_qecorr
;        lambda_q = findgen(901)+200.
;        qecorr = replicate(1.,901)
    endif

; create new wavelength vector

    minlam=ceil(max([min(lambda_t),min(lambda_f),min(lambda_q)]))
    maxlam=floor(min([max(lambda_t),max(lambda_f),max(lambda_q)]))

    lambda = [lambda_f,lambda_t,lambda_q]
    lambda = lambda[where((lambda ge minlam) and (lambda le maxlam))]
    lambda = lambda[uniq(lambda,sort(lambda))]

    newtrans = interpol(trans,lambda_t,lambda)
    newqecorr = interpol(qecorr,lambda_q,lambda)
    newflux = interpol(flux,lambda_f,lambda)/(pifact * dfs^2) ;?

    ;int_tabulated.pro uses the newton-cotes method to integrate:

    EffFact = int_tabulated(lambda,newtrans*newqecorr*newflux)

    IF DebugFlag gt 0 THEN CISSCAL_Log, 'Total efficiency * input flux is ' + $
                 strtrim(string(EffFact),2) + ' electrons/cm^2/sec' ;?

endif else begin

; I/F mode OFF:

  EffFact = ''
  GET_LUN, DBFile
  OPENR, DBFile, CalibrationBaseDir + 'efficiency/effic_db.tab', ERROR=err
  IF ( err NE 0 ) THEN BEGIN
    If DebugFlag gt 0 THEN CISSCAL_Log, 'Efficiencies database not found: unable to search for factor'
    FREE_LUN, DBFile
    RETURN
  ENDIF ELSE BEGIN
    Filter1 = self.Filter1
    Filter2 = self.Filter2

    while not eof(DBFile) do begin
        text=''
        readf, DBFile, text
        if strpos(text, '\begindata') ge 0 then break
    endwhile

    WHILE ( (EffFact EQ '') AND (NOT EOF(DBFile))) DO BEGIN
;	Keep looking...
      LineBuf=''
      READF, DBFile, LineBuf
      LineBuf = STRCOMPRESS(LineBuf)	; collapse whitespace to single spaces
      Fields = STR_SEP(LineBuf, ' ')	; tokenize
      IF Fields[0] NE '' THEN BEGIN	; have tokens OK...
        IF ((Fields[0] EQ self.Instrument) $
          AND ( Fields[1] EQ Filter1 ) $
          AND ( Fields[2] EQ Filter2 ) ) THEN EffFact = Fields[3]
      ENDIF
    ENDWHILE
  ENDELSE
  FREE_LUN, DBFile

  IF EffFact EQ '' THEN BEGIN
;	Couldn't find a match in the database
    If DebugFlag gt 0 THEN CISSCAL_Log, 'Efficiencies database contained no factor for filter combination:', $
			self.Instrument + ':' + Filter1 + ':' + Filter2
    RETURN
  ENDIF ELSE BEGIN
    IF DebugFlag gt 0 THEN CISSCAL_Log, 'Total efficiency is ' + EffFact + ' electrons/photon nm' 
    EffFact = float(EffFact)
  ENDELSE

  units = 'phot/cm^2/s/nm/ster'

endelse

*self.ImageP = *self.ImageP / EffFact
IF DebugFlag eq 2 THEN CISSCAL_Log, 'pixel flux extrema ', self->DNRange()

;	Update calibration history in image label:
;		(added by Ben Knowles, 4/02)
history=self.Labels->Get('PROCESSING_HISTORY_TEXT')
newflag='Divided by Efficiency = '+strtrim(string(EffFact),2)+'; output units are in ' + $
        units + ')'
if (history ne '') then newflag=', '+newflag
newhistory=history+newflag
junk=self.Labels->Set('PROCESSING_HISTORY_TEXT',newhistory,1)

END



