pro sb_icerdiv2,i,d
;+
; $Id$
;
; Project : STEREO SECCHI
;
; Name    : sb_icerdiv2
;
; Purpose : correct for conditional DIV2 by on-board IP prior to ICER.
;           Modified version of scc_icerdiv2 (minimal update of header),
;           but with checks for the SECCHI specific keywords.
;
; Algorithm: - check if datap01 is smaller than 3/4 of biasmean
;            - if so, multiply data by two if both of the following are true:
;              - data was ICER compressed
;              - there was no explicit ICER filter IP just before the ICER IP
;            No ICER filter IP means that either the ICER filter did a DIV2
;            (in that case, the filter IP was replaced by the DIV2 IP),
;            or there was no filter, and ICER may have done an implicit DIV2
;
; Use     : IDL> sb_icerdiv2,index,data
;
; Input/output  :
;    index = header index structure.  Must have at least the following tags:
;         .BIASMEAN
;         .IP_00_19
;         .DATAP01         ; may be updated
;    data  = image data array.  Replaced by corrected data array
;
; Keywords:
;
; Common  : None
;
; Restrictions:
;
; Side effects:
;
; Category    : Pipeline
;
; Prev. Hist. :
;
; Written     : Jean-Pierre Wuelser, LMSAL, 16-Jan-2007
;               modified version of scc_icerdiv2
;               JPW 2-Feb-2007 fixes images that were inadvertently
;                              multiplied by 2 due to a bug in the
;                              pipeline for a few days in late Jan 2007
;
; $Log$
;-

if tag_exist(i,'datap01') and tag_exist(i,'biasmean') then begin
 if i.datap01 lt 0.75*i.biasmean and tag_exist(i,'ip_00_19') then begin
   ip = i.ip_00_19
   if strlen(ip) lt 60 then ip=' '+ip      ; ip should be 3x20 char long
   if strlen(ip) lt 60 then ip=' '+ip      ; but could be as short as 58
   ip = fix(string(reform(byte(ip),3,20)))
   ww = where(ip ne 0,nip)
   ip = ip[ww]
   icer = ip(nip-1) ge 90 and ip(nip-1) le 102       ; last IP was ICER
   not_icfilt = ip(nip-2) lt 106 or ip(nip-2) gt 112 ; prior IP not filter
   if icer and not_icfilt then begin                 ; there was a DIV2
      m2 = d[0,0]
      m2[0] = 2                            ; constant 2 of same type as d
      d = d * m2
      i.datap01 = i.datap01 * 2
   endif
 endif

 ;;; fix images incorrectly multiplied by two in late Jan.2007
 if i.datap01 gt 1.5*i.biasmean and tag_exist(i,'ip_00_19') then begin
   ip = i.ip_00_19
   if strlen(ip) lt 60 then ip=' '+ip      ; ip should be 3x20 char long
   if strlen(ip) lt 60 then ip=' '+ip      ; but could be as short as 58
   ip = fix(string(reform(byte(ip),3,20)))
   ww = where(ip ne 0,nip)
   ip = ip[ww]
   icer = ip(nip-1) ge 90 and ip(nip-1) le 102       ; last IP was ICER
   if icer then begin                      ; was ICER, bug probably in effect
      m2 = d[0,0]
      m2[0] = 2                            ; constant 2 of same type as d
      d = d / m2
      i.datap01 = i.datap01 / 2
   endif
 endif
 ;;;

endif

end
