pro hxisT_EM, FOV, GAIN, B1, B2, C1, C2, T, EM, EM1, EM2, tclose=TCLOSE

common TEMPOLD,CRPF,CRPC,CRP,FOVOLD,GAINOLD,IU,JU
common hxiscata, catplace

if B1 eq B2 then message, 'Bands have to be different'
if GAIN le 0 then begin  &  TEST = 1  &  GAIN = 1.  &  endif else TEST = 0

if n_elements(CRP) eq 0 then CRP = -1
if CRP(0) eq -1 then begin              ; Define association with CRP files
    openr, /GET_LUN, IU, catplace + 'HXIS_COARSE.RAT'  
    CRPC = assoc(IU,dblarr(7,100))  
    openr, /GET_LUN, JU, catplace + 'HXIS_FINE.RAT'    
    CRPF = assoc(JU,dblarr(7,100))
    FOVOLD = -1  &  GAINOLD = -1
endif

G = fix(100*GAIN-90)-1
if FOV ne FOVOLD or GAIN ne GAINOLD then begin      ; Read new CRP data if necessary
;    if FOV eq 0 then CRP = CRPF(G) else CRP = CRPC(G)  ; Associated read
    if FOV eq 0 then CRP = conv_vax_unix2(CRPF(G)) $
        else CRP = conv_vax_unix2(CRPC(G))  ; Associated read
endif

T_E6 = reform(CRP(0,*))  &  CRP1 = reform(CRP(B1,*))  &  CRP2 = reform(CRP(B2,*))  &  R = CRP2/CRP1

; If the ratio of the CRP count rates for the two bands as a function of temperature has an
; extremum, search only the temperature range below the temperature where the extremum is reached.

A = R(1)-R(0)  &  SIGN = fix(abs(A)/A)  &  S = R-shift(R,1)
S = fix(abs(S)/S)  &  S(0) = S(1)  &  R = R(where(S eq S(0)))  &  NR = n_elements(R)-1

if where(S eq 0) ne -1 then message, 'This is awfully wrong'

RIN = float(C2)/C1  &  A = min(abs(R-RIN),IM)

if S(0)*R(IM) ge S(0)*RIN and IM ne 0 then IM1 = IM-1 else $
if S(0)*R(IM) lt S(0)*RIN and IM ne NR then IM1 = IM+1 else IM1 = IM

if IM1 eq IM then begin  &  T = 0.  &  EM = 0.  &  EM1 = 0.  &  EM2 = 0.  &  endif else begin
    T = T_E6(IM)+(T_E6(IM)-T_E6(IM1))/(R(IM)-R(IM1))*(RIN-R(IM))
    EM1 = CRP1(IM)+(CRP1(IM)-CRP1(IM1))/(R(IM)-R(IM1))*(RIN-R(IM))  &  EM1 = C1/EM1
    EM2 = CRP2(IM)+(CRP2(IM)-CRP2(IM1))/(R(IM)-R(IM1))*(RIN-R(IM))  &  EM2 = C2/EM2
    EM = (EM1+EM2)*0.5
endelse

if TEST then begin
    plot, T_E6(0:NR),R,xtitle=string(RIN)+' --> '+string(T)
    plots, [T_E6(0),T_E6(NR)], [RIN,RIN], /data  &  plots, [T,T], [R(0),R(NR)], /data
endif

FOVOLD = FOV  &  GAINOLD = GAIN

if keyword_set(TCLOSE) then begin
    CRP = -1  &  free_lun, IU  &  free_lun, JU  &  return
endif

return  &  end