FUNCTION make_scc_hdr, level, SCIP=scip, FAST=fast, _extra=_extra, spice=spice, IPver=IPver, $
			ENDBADAH=endbadah
;_extra is need for stereo spice to load attitude files from Mission Sim2 not needed after launch

;+
;$Id: make_scc_hdr.pro,v 1.181 2025/06/13 21:42:29 nathan Exp $
; Project     : STEREO - SECCHI
;                   
; Name        : make_scc_hdr
;               
; Purpose     : Return a FITS header with values in the SEB image header 
;   	    	structure. Also fills in the values of a SECCHI header 
;   	    	structure.
;               
; Use         : IDL> fits_hdr = make_scc_hdr(scc_struct)
;
; Inputs      : none
;               
; Outputs     : Returns a fits header (STRARR)
;               
; Opt. Outputs: scc_struct	The image header returned as a
;				SECCHI header structure
;               
; Keywords    : SCIP 	    ='A' or 'B'; overrides observatory designation in 
;   	    	    	    image header
;               _extra      set to indicate pre flight test for SPICE ie sim2='sim2'
;   	    	SPICE       If set add SPICE coordinates to image header
;   	    	IPver	    set Flight software IP version for images v46 = V4.6
;				ENDBADAH=	time to start reloading stereo_spice if att_file='NotFound'
;
; Restrictions: Recquires definition of scc_reduce COMMON block and 
;   	    	populating of SEB base and (if applicable) nominal and extended 
;   	    	headers.
;
; Calls LASCO : utc2yymmdd.pro
; Calls	PT: sccread_ip_dat.pro, $PT/IN/OTHER/cnvrt_ip.dat
; 
;
; Category    : Data_Handling, I_O, pipeline
;               
; Prev. Hist. : None.
;
; Written     : Nathan Rich, NRL, 2004.09.08
;               
; $Log: make_scc_hdr.pro,v $
; Revision 1.181  2025/06/13 21:42:29  nathan
; do not populate temperatures if not near temp in database
;
; Revision 1.180  2024/01/23 15:58:44  secchia
; check update status
;
; Revision 1.179  2022/02/02 11:53:05  secchia
; testing for comiitted version
;
; Revision 1.178  2018/01/30 15:37:21  mcnutt
; added exposure correction for EUVI double exposures
;
; Revision 1.177  2017/01/03 20:31:40  secchia
; removed stereo_spice_conic common block
;
; Revision 1.176  2017/01/03 20:25:21  secchia
; added load_sunspice common block
;
; Revision 1.175  2011/11/23 14:12:32  secchia
; set seb_prog before defining L
;
; Revision 1.174  2011/11/22 16:50:34  nathan
; fix bad filename after last edit
;
; Revision 1.173  2011/11/16 19:08:26  nathan
; move setting scch.filename so can be used in check_encoder message
;
; Revision 1.172  2011/11/14 17:20:49  nathan
; change message for exptime correction
;
; Revision 1.171  2011/11/10 21:18:43  nathan
; implement check_encoder() for euvi qs
;
; Revision 1.170  2011/11/07 20:03:51  nathan
; use expcmd for exptime if actualexpduration is too big
;
; Revision 1.169  2011/10/12 19:06:56  nathan
; modify header comments to remove keywords
;
; Revision 1.168  2011/06/29 19:30:23  nathan
; changed maillist to secchipipeline@cronus
;
; Revision 1.167  2011/02/02 12:53:32  mcnutt
; removed last change
;
; Revision 1.166  2011/02/01 18:28:30  mcnutt
; sets crota value if not EUVI
;
; Revision 1.165  2011/01/18 17:23:23  secchib
; nr - cannot skip tables because RO values must be set for HI
;
; Revision 1.164  2011/01/12 18:34:03  nathan
; enable skiptables; add threshn.img comment
;
; Revision 1.163  2011/01/11 19:43:09  mcnutt
; made correction to critcal event
;
; Revision 1.162  2011/01/07 16:38:51  nathan
; add defn of scch.critevt
;
; Revision 1.161  2011/01/04 18:35:58  mcnutt
;  modified event detect for IP V1.11
;
; Revision 1.160  2010/12/09 20:48:57  nathan
; Moved attmsg.txt email notification from secchi_reduce to make_scc_hdr;
; should only email 1x/day
;
; Revision 1.159  2010/05/27 15:19:10  nathan
; do not convert cdelta to degrees (already done in getsccsecpix)
;
; Revision 1.158  2009/06/10 21:07:29  nathan
; remove common stereo_spice because unused; reduce waits
;
; Revision 1.157  2009/05/06 16:25:00  nathan
; updated DOORSTAT logic and comments to correctly handle EUVI disabled door
;
; Revision 1.156  2009/02/24 11:58:14  secchib
; corrected scch.crln_obs line 726
;
; Revision 1.155  2009/02/23 17:34:39  nathan
; make sure crln_obs is positive
;
; Revision 1.154  2008/12/15 16:56:15  secchib
; changes scch.mask_tbl to none if no mask is applied
;
; Revision 1.153  2008/10/07 16:54:49  nathan
; implement method to key off of imgctr to determine when schedule tables were read
;
; Revision 1.152  2008/07/02 17:33:07  nathan
; use sxdelpar not rem_tag2 to remove TIME_OBS from hdr and remove RAVG also
;
; Revision 1.151  2008/04/03 13:15:43  mcnutt
; reports expsoure corrections in ipmsg.txt
;
; Revision 1.150  2008/02/08 15:29:33  nathan
; improve precision of RSUN to from 3 to 6 figures
;
; Revision 1.149  2007/12/19 18:48:09  mcnutt
; definse expdurcmt2 before if statement to work with HI processing
;
; Revision 1.148  2007/12/18 18:35:49  secchia
; change prevexp array to 5 not 3 to allow for EUVI ap1=4
;
; Revision 1.147  2007/12/18 13:37:19  mcnutt
; corrected expo correction see Nathans notes in bug 267
;
; Revision 1.146  2007/12/17 17:17:48  mcnutt
; Added expsoure correction for Bug 267
;
; Revision 1.145  2007/12/12 23:14:52  nathan
; Correctly compute EXPCMD and EXPTIME for DOUBLE images and add comments (Bug 268)
;
; Revision 1.144  2007/11/27 22:16:03  nathan
; Always get table info, needs getscctableinfo.pro,v 1.10 (Bug 261)
;
; Revision 1.143  2007/11/13 18:35:05  mcnutt
; added CMDOFFSE Bug 256
;
; Revision 1.142  2007/10/26 17:28:55  nathan
; update SPICE comment for HI
;
; Revision 1.141  2007/10/26 16:16:59  mcnutt
; commented out lines to cahnge L to m if its a cor summed image
;
; Revision 1.140  2007/09/06 18:10:25  mcnutt
; Bug 222 sets scch.polar to 1001 for images of type DOUBLE
;
; Revision 1.139  2007/08/22 21:41:17  secchib
; nr - rem_tag time_obs ONLY for fits_hdr (cor1_point requires SECCHI label on scch)
;
; Revision 1.138  2007/08/20 16:25:56  nathan
; if SCI set ap1 and detector from nom_hdr not fileorig
;
; Revision 1.137  2007/08/20 15:08:06  nathan
; handle detector correctly in case of SCI file
;
; Revision 1.136  2007/08/14 19:18:29  nathan
; rem_tag TIME_OBS; exptime type double
;
; Revision 1.135  2007/07/27 21:36:47  nathan
; set SC_[YPR]*A
;
; Revision 1.134  2007/07/10 15:01:49  nathan
; change EVCOUNT values
;
; Revision 1.133  2007/06/20 21:55:28  nathan
; correctly set basename for cadencefile
;
; Revision 1.132  2007/06/20 15:59:37  secchia
; nr - just wait 1 sec if endbadah set
;
; Revision 1.131  2007/06/20 15:56:27  secchia
; nr - compute filename BEFORE WCS stuff
;
; Revision 1.130  2007/06/20 15:08:34  nathan
; Add L EQ m as criteria for using date-end; always call get_stereo_att_file;
; Implement ENDBADAH keyword
;
; Revision 1.129  2007/06/19 16:31:12  nathan
; add comment about time used for pointing info
;
; Revision 1.128  2007/06/19 15:36:56  nathan
; Use DATE-END for ephemeris and attitude for HI, else use DATE-OBS (Bug 178);
; Compute CRVALjA for EUVI (Bug 184)
;
; Revision 1.127  2007/06/13 18:12:38  nathan
; wait 10 sec if att_file not found
;
; Revision 1.126  2007/06/13 14:57:22  mcnutt
; Bug 70 fills CEB_T with 1 hour median temp value
;
; Revision 1.125  2007/06/08 15:53:10  secchia
; nr - do not use m in filename in case of event detect
;
; Revision 1.124  2007/06/05 16:42:05  nathan
; Get CDELT and CRPIX also for EUVI
;
; Revision 1.123  2007/05/23 19:41:53  secchib
; nr - do not reload stereo_spice if not lz
;
; Revision 1.122  2007/05/21 20:43:04  nathan
; add basename to cadence.sav for processing lists
;
; Revision 1.121  2007/05/04 22:07:33  secchia
; nr - syntax error
;
; Revision 1.120  2007/05/04 21:48:03  nathan
; use renamed read_ip_dat; make hpccmnt conditional
;
; Revision 1.119  2007/05/02 15:47:07  secchib
; nr - make sure to /RELOAD load_stereo_spice if att_file=NotFound (Bug 129)
;
; Revision 1.118  2007/04/26 19:06:46  secchib
; nr - do not update _TBL keywords or run cpdb if /NOHBTEMPS
;
; Revision 1.117  2007/04/26 16:13:54  mcnutt
; Fix for Bug 122 images summed onboard except for HI use m in the file name
;
; Revision 1.116  2007/04/24 17:05:12  secchib
; nr - fix printf line 750
;
; Revision 1.115  2007/04/24 14:17:01  nathan
; reload stereo_spice if Att_file not found (Bug 129)
;
; Revision 1.114  2007/04/16 21:47:55  nathan
; Truncate ip_00_19 in case of RELD (Bug 139)
;
; Revision 1.113  2007/04/04 17:05:00  nathan
; check if attitude file found and modify att_file accordingly (Bug 129)
;
; Revision 1.112  2007/03/20 19:27:05  nathan
; Implement euvi_point.pro after secchi_rectify (Bug 115); set ATT_FILE and EPHEMFIL in make_scc_hdr.pro
;
; Revision 1.111  2007/03/13 19:12:04  secchib
; nr - do not wait if /fast
;
; Revision 1.110  2007/03/12 18:12:27  secchib
; nr - substite ops/tables/current/ for readfile source/swire/src/
;
; Revision 1.109  2007/03/06 11:13:20  nathan
; fix incorrect setting of crval(A) based on detector
;
; Revision 1.108  2007/03/01 22:45:18  nathan
; Implement getsccpointing.pro (Bug 27); add SC_[yaw,pitch,roll] (Bug 91)
;
; Revision 1.107  2007/02/26 19:27:54  secchia
; nr - equate readfile dir is/ to ops/tables/current/
;
; Revision 1.106  2007/02/14 20:39:29  secchib
; nr - set default value of hi crs sigma
;
; Revision 1.105  2007/02/13 20:16:27  secchia
; added iphicrs varialb to save cadence file
;
; Revision 1.104  2007/02/12 20:35:24  nathan
; implement dstart/dstop (Bug 93)
;
; Revision 1.103  2007/02/10 00:01:00  nathan
; Add comment to doorstat (Bug 68)
;
; Revision 1.102  2007/02/06 14:17:35  nathan
; change spaceweather SOURCE to SW to match scclister.pro
;
; Revision 1.101  2007/02/01 23:16:06  nathan
; dummy lines for HI CRVAL
;
; Revision 1.100  2007/01/31 21:00:54  nathan
; fix CTYPE*A with *AZP
;
;-            

COMMON scc_reduce ;, ludb, lulog, basehdr, nom_hdr, ext_hdr, scch, leapsecs
common stereo_sunspice, rtnframe, clocks, def_ephem, ephem, attitude, att_sc, $
  att_mjd, att_loaded, mu, maxdate, conic

;common stereo_sunspice; common stereo_spice;, def_ephem, ephem, attitude
;common stereo_spice_conic;, mu, maxdate, conic

; ++++ Initialize admin and common variables

version = '$Id: make_scc_hdr.pro,v 1.181 2025/06/13 21:42:29 nathan Exp $'
len=strlen(version)
version = strmid(version,1,len-2)
; ++++ always initialize scch
scch = def_secchi_hdr()
scch.history[0]=version
if datatype(enums) EQ 'UND' THEN enums = def_scc_enums()
if datatype(ipdat) EQ 'UND' THEN BEGIN
    ssss = scc_read_ip_dat(IPver=IPver)
    ipdat=replicate('ERROR',256)
    for i=0,n_elements(ssss.ip_description)-1 do ipdat[i]=ssss[i].ip_description
ENDIF
IF datatype(aorb) EQ 'UND' THEN aorb=strlowcase(getenv("SCC_PLATFORM"))


; ++++ BEGIN basehdr-only

scch.compfact=0   ; initialize this, is set in secchi_reduce IF nmissing=0

scch.version	=basehdr.version
;scch.simple	=
scch.bitpix	=16
; ??? How do I know if there is an image or not? ???
;gets set to 0 id scch.comprssn eq 5  see header only below
scch.naxis	=2
get_utc,date_mod,/ccsds,/noz
scch.date	=date_mod
scch.fileorig	=string(basehdr.filename)
basename=strmid(scch.fileorig,0,8)
hex2dec,strmid(scch.fileorig,9,2),ap2
scch.apid	=ap2 + 1024
scch.obs_id	=basehdr.osnumber
scch.imgctr	=basehdr.imgctr
scch.TIMGCTR	=basehdr.telescopeImgCnt
scch.imgseq	=basehdr.imgseq
; !!! should be basehdr !!!
;scch.obsrvtry = 'STEREO_'+getenv("SCC_PLATFORM")
scch.obsrvtry = enums.eplatformtypes[nom_hdr.platformid]
date_obs_utc	=tai2utc(basehdr.actualexptime, /nocorrect)
scch.date_obs	=utc2str(date_obs_utc,/noz)
; For combo images, DATE-OBS is over-written later in secchi_reduce.pro

; enums.ehkpinstrument -> tts=['xx','c2','c1','eu','h2','h1']
enum2apid=[-1,1,0,4,3,2]
;TT=tts[nom_hdr.telescopeid]
; ++++ use ApID to determine detector
ap1=strmid(scch.fileorig,10,1)
IF ap1 EQ 'C' THEN ap1=enum2apid[nom_hdr.telescopeid]
tts=['c1','c2','h1','h2','eu']
TT=tts[ap1]
detectors=['COR1','COR2','HI1','HI2','EUVI']
scch.detector=detectors[ap1]

scch.origin	=strupcase(getenv ('SITE'))
scch.bunit	='DN'
scch.blank	=0
scch.obs_prog	=''
scch.encoderp   =basehdr.actualpolarposition
;degr = (scch.encoderp) * 2.5

scch.exptime	=basehdr.actualexpduration*double(4.0e-6)
expdurcomment=' from MEB'
scch.encoderf	=basehdr.actualfilterposition
IF scch.version GT 1 THEN BEGIN
    scch.biasmean   =basehdr.meanbias/1000.
    scch.biassdev   =basehdr.stddevbias/1000.
ENDIF
; ++++ Get Basehdr IP info. ++++
ipf = where(basehdr.ipcmdlog NE 0, nipf)
; ???
;stop
reld=where(basehdr.ipcmdlog EQ 117,nreld)
IF nreld GT 0 THEN preld=reld[0] ELSE preld=0
preld=preld<10
IF basehdr.ipcmdlog[nipf-1] GT 250 THEN $
scch.comprssn 	=basehdr.ipcmdlog[ipf[nipf-2]] ELSE $
scch.comprssn 	=basehdr.ipcmdlog[ipf[nipf-1]]
compr_string	=ipdat[scch.comprssn]
scch.ip_prog0	=basehdr.ipcmdlog[preld+0]
scch.ip_prog1	=basehdr.ipcmdlog[preld+1]
scch.ip_prog2	=basehdr.ipcmdlog[preld+2]
scch.ip_prog3	=basehdr.ipcmdlog[preld+3]
scch.ip_prog4	=basehdr.ipcmdlog[preld+4]
scch.ip_prog5	=basehdr.ipcmdlog[preld+5]
scch.ip_prog6	=basehdr.ipcmdlog[preld+6]
scch.ip_prog7	=basehdr.ipcmdlog[preld+7]
scch.ip_prog8	=basehdr.ipcmdlog[preld+8]
scch.ip_prog9	=basehdr.ipcmdlog[preld+9]
IF scch.version GT 2 THEN BEGIN
    numstring=''
    FOR i=preld,19 DO numstring=numstring+string(basehdr.ipcmdlog[i],format='(i3)')
    IF preld GT 0 THEN FOR i=0,preld-1 DO numstring=numstring+'  0'
	scch.ip_00_19   =numstring
    scch.ipsum=(basehdr.sebxsum + basehdr.sebysum)/2.
ENDIF ELSE BEGIN
    ; +++++ sebx/ysum not getting set correctly in header, use ipcmdlog instead
    junk=where(basehdr.ipcmdlog EQ 3, nipsums)
    scch.ipsum	=((2^nipsums)>1)
ENDELSE

;


scch.ccdsum	=(basehdr.sumrow + basehdr.sumcol)/2.
scch.summed	=scch.ipsum+scch.ccdsum-1
scch.sumrow 	=basehdr.sumrow
scch.sumcol 	=basehdr.sumcol

; readport is right unless EUVI A which is left
scch.readport	='R'
if(scch.detector eq 'EUVI' and  scch.obsrvtry eq 'STEREO_A')then scch.readport	='L'
; ++++ END basehdr-only

; ++++ Compute filename

S=strmid(scch.obsrvtry,7,1)
Ap0=string(basehdr.filename[9])
scch.seb_prog	=enums.eimagetypecodes[nom_hdr.imagetype]
;L=level
case trim(scch.seb_prog) of
  'NORMAL'   : L='n'
  'DARK'     : L='k'
  'DOUBLE'   : L='d'
  'LED'      : L='e'
  'CONTIN'   : L='c'
  'SERIES'   : L='s'
  'NORMAL'   : L='n'
  else       : L='n'
endcase
;change L to m if image was combined onboard
;m_img=[-1]
;if(not keyword_set(IPver))then m_img=[33,34,35,36,37,38,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75]
;if(keyword_set(IPver))then begin
;  if(strlowcase(IPver) eq 'v46')then m_img=[33,34,35,36,37,38,56,57,58,59,60,61,62,63,64,65,66,67]
;endif
;m=where(m_img eq basehdr.ipcmdlog) & if(m(0) gt -1)then L='m'

;never use mper bill 10-26-06
;change L to m if COR image was combined onboard correct for bug 122
;except if used with event detect
;w=where(basehdr.ipcmdlog ge 61 and  basehdr.ipcmdlog le 70,usesaved)
;evtd=where(basehdr.ipcmdlog EQ 4,isevtd)
;if (usesaved) and ~(isevtd) then L='m'
IF scch.vchannel EQ 7 THEN ap0='2'
scch.filename	=utc2yymmdd(date_fname_utc,/yyyy,/hhmmss)+'_'+L+ap0+TT+S+'.fts'

cleardur=0.7  	; assume clear2.tbl if no nom_hdr

; spaceweather ApIDs are x0470 - 0474 = 1136 - 1140
IF (datatype(prevbasename) EQ 'UND') THEN prevbasename='und'
; to handle reduced SW header for IPver 46
prevIP=0
if(keyword_set(IPver))then prevIP =IPver
if(strlowcase(prevIP) eq 'v46') AND (scch.apid LE 1140) AND (scch.apid GE 1136) AND (basename NE prevbasename) THEN $
GOTO, afternom_hdr

; ++++ BEGIN basehdr+nom_hdr

date_cmd_utc    =tai2utc(nom_hdr.cmdexptime, /nocorrect)
;date_fname_utc	=date_cmd_utc
; - is set in secchi_reduce
scch.date_cmd	=utc2str(date_cmd_utc,/noz)

degr            = (nom_hdr.cmdpolarposition) * 2.5

; !!! should be basehdr ???
scch.p1col	=nom_hdr.p1col
scch.p2col	=nom_hdr.p2col
scch.p1row	=nom_hdr.p1row
scch.p2row	=nom_hdr.p2row
;--indicate imaging area
;  naxis1
scch.dstart1	=(51-scch.p1col+1)>1
scch.dstop1	=scch.dstart1-1+((scch.p2col-scch.p1col+1)<2048)
;  naxis2
scch.dstart2	=1
scch.dstop2	=scch.dstart2-1+((scch.p2row-scch.p1row+1)<2048)
; !!!

IF scch.version LE 3 THEN cmdexpdur=basehdr.cmdexpduration ELSE cmdexpdur=nom_hdr.cmdexpduration
IF      (nom_hdr.telescopeid GT 3) THEN $
    scch.expcmd	=cmdexpdur*2.0e-3 $
ELSE IF (scch.seb_prog EQ 'DARK' AND scch.version GT 3) THEN $
    scch.expcmd =cmdexpdur*2.0e-3 ELSE $
    scch.expcmd	=cmdexpdur*1.024e-3
;IF scch.expcmd EQ 0 THEN 	scch.exptime=0 

scch.offset	=nom_hdr.offset
scch.gaincmd	=nom_hdr.gain
gainmodes=['HIGH','LOW']
scch.gainmode	=gainmodes[nom_hdr.gainmode]
scch.clr_tbl	=nom_hdr.clrtableid
IF scch.clr_tbl EQ 1 THEN cleardur=0.7 $ 	; assumes clear2.tbl
	ELSE cleardur=3.5	; assumes clear10.tbl
scch.read_tbl	=nom_hdr.readouttableid

;set fps_on to NA for CORs and hIs 
;scch.fps_on='NA' ; NR, 3/24/06 -- leave blank

fort=make_array(256,value='NaN')
fort[0:1]=['F','T']


IF (scch.detector EQ 'EUVI') THEN BEGIN
; Table from MechParamSummary from LMSAL, SEC01167 Rev C
;									L10-FM Encoder Reading	L20-FM Encoder Reading
;Mirror / Filter Pos	Filter Type	Target CW	Target CCW	CW	CCW		CW	CCW
;175 (III)		Grid		20		23		22	22		21	21
;284 (II) (Reset)	Mesh		14		17		16	16		15	15
;195 (I)		Grid		8		11		10	10		9	9
;304 (IV)		Mesh		2		5		4	4		3	3
	sectors=make_array(256,value=255)
	sectors[0:3]=[304,195,284,171]
	scch.wavelnth=sectors[(ext_hdr.cmdquadposition)/6]
	scch.fps_on=fort[ext_hdr.actualfpsmode]
	scch.fps_cmd=fort[ext_hdr.usefps]
	scch.SCFP_ON=fort[ext_hdr.actualscfinepointmode]  

;moved to include cmd FW position in SPWX image headers
	filters=make_array(256,value='NaN')
	filters[0:3]=['S1','DBL','S2','OPEN']
;	scch.filter	=filters[nom_hdr.cmdfilterposition/45]
;   	    works for filter encoder position +/-3
	scch.filter	=filters[round(basehdr.actualfilterposition/52.)]
    	scch.encoderq   =basehdr.actualpolarposition

	if ( check_encoder(scch.wavelnth,scch.encoderq, nom_hdr.platformid, expe) ) then begin
	    expmsg= scch.filename+' ENCODERQ '+trim(scch.encoderq)+' does not match expected '+trim(expe)+' for '+trim(wavelnth)
	    print,expmsg
	    wait,5
	    printf,lulog,expmsg
	    openw,elun,'ipmsg.txt',/get_lun,/append
	    printf,elun,expmsg
	    printf,elun,''
	    free_lun,elun
	ENDIF

;fps and pzt values from extended header
        scch.FPSNUMS=ext_hdr.fpsdata.numfpssamples	; Number of FPS samples
    	scch.FPSOFFY=ext_hdr.fpsdata.yoffset	    	; Y offset
    	scch.FPSOFFZ=ext_hdr.fpsdata.zoffset	    	; Z offset
    	scch.FPSGTSY=ext_hdr.fpsdata.fpsysum	    	; scch.FPS Y sum
    	scch.FPSGTSZ=ext_hdr.fpsdata.fpszsum	    	; scch.FPS Z sum
    	scch.FPSGTQY=ext_hdr.fpsdata.fpsysquare	    	; scch.FPS Y square
    	scch.FPSGTQZ=ext_hdr.fpsdata.fpszsquare	    	; scch.FPS Z square
    	scch.FPSERS1=ext_hdr.fpsdata.pzterrsum(0)	; PZT Error sum [0]
    	scch.FPSERS2=ext_hdr.fpsdata.pzterrsum(1)	; PZT Error sum [1]
    	scch.FPSERS3=ext_hdr.fpsdata.pzterrsum(2)	; PZT Error sum [2]
    	scch.FPSERQ1=ext_hdr.fpsdata.pzterrsquare(0)	; PZT Error square [0]
    	scch.FPSERQ2=ext_hdr.fpsdata.pzterrsquare(1)	; PZT Error square [1]
    	scch.FPSERQ3=ext_hdr.fpsdata.pzterrsquare(2)	; PZT Error square [2]
    	scch.FPSDAS1=ext_hdr.fpsdata.pztdacsum(0)	; PZT DAC sum [0]
    	scch.FPSDAS2=ext_hdr.fpsdata.pztdacsum(1)	; PZT DAC sum [1]
    	scch.FPSDAS3=ext_hdr.fpsdata.pztdacsum(2)	; PZT DAC sum [2]
    	scch.FPSDAQ1=ext_hdr.fpsdata.pztdacsquare(0)	; PZT DAC square [0]
    	scch.FPSDAQ2=ext_hdr.fpsdata.pztdacsquare(1)	; PZT DAC square [1]
    	scch.FPSDAQ3=ext_hdr.fpsdata.pztdacsquare(2)	; PZT DAC square [2]
        scch.JITRSDEV = sqrt( (scch.FPSERQ1+scch.FPSERQ2+scch.FPSERQ3)/scch.FPSNUMS $
               -(scch.FPSERS1+scch.FPSERS2+scch.FPSERS3)/scch.FPSNUMS ) / 320.0

ENDIF
; !!! need defintion !!!
dirs=make_array(256,value='NaN')
dirs[1:2]=['CW','CCW']
scch.shuttdir	=dirs[nom_hdr.actualshutterdirection]
IF (nom_hdr.actualShutterPosition EQ 0) THEN scch.shuttdir='NONE'
; !!!
scch.ledcolor	=enums.ehkpcalledcolor[nom_hdr.cmdledmode]
scch.ledpulse	=nom_hdr.cmdledpulses
;stop
torf=['T','F','F','T','T']
;IF (nom_hdr.actualdoorposition le 4) THEN $
;    scch.doorclos	= torf[nom_hdr.actualdoorposition] $
;ELSE scch.doorclos = ''
scch.doorstat   =nom_hdr.actualdoorposition
scch.readtime	=nom_hdr.actualreadouttime*1e-6	
; ++++ Get IP info. ++++
scch.ip_time	=(nom_tlr.ipprocessingtime - nom_hdr.ipprocessingtime)	

IF scch.version GT 1 THEN BEGIN
    date_clr_utc    =tai2utc(nom_hdr.ACTUALCCDCLEARSTARTTIME, /nocorrect)
    scch.date_clr   =utc2str(date_clr_utc,/noz)
    date_ro_utc	    =tai2utc(nom_hdr.ACTUALIMAGERETRIEVESTARTTIME, /nocorrect)
    scch.date_ro    =utc2str(date_ro_utc,/noz)
    IF (    nom_hdr.telescopeid GT 3 or $	; HI
    	    scch.seb_prog EQ "DARK" or $
            scch.seb_prog EQ "CONTIN" or $
            (scch.seb_prog EQ "LED" and ( $
		(scch.ledcolor EQ "RED" and scch.detector EQ "EUVI" ) or $
		(scch.detector EQ "COR1") or $
		(scch.ledcolor NE "RED" and scch.detector EQ "COR2")))) THEN BEGIN
    	;scch.exptime=nom_hdr.ACTUALIMAGERETRIEVESTARTTIME - nom_hdr.ACTUALCCDCLEARSTARTTIME - cleardur
	expdurcomment=' computed onboard = ro_start - clr_start - est_clear_duration'
    ENDIF 
ENDIF

whtr=where(basehdr.ipcmdlog eq 68, nwhtr)
; ++++++ header v3 first cut - pcol not getting set correctly if trimmed
wtrm=where(basehdr.ipcmdlog eq 76, nwtrm)
; +++++ Workaround for Bug 42 (FSW) does not compute pcol correct for ccd-summed + TRIM
; +++++ Resolves Bug 41 (result of bug 42)
IF ((nwhtr GT 0) and (scch.version LT 4)) OR $
   ((nwtrm GT 0) and (scch.ccdsum  GT 1)) THEN BEGIN
    scch.p1col	=51
    scch.p2col	=51+2047
ENDIF
anarr=where(nom_hdr.ipcmd EQ 40,isspwx)
IF isspwx GT 0 THEN scch.spwx = 'T' 

scch.obssetid	=nom_hdr.campaignset
scch.ceb_stat   =nom_hdr.cebintfstatus
scch.cam_stat   =nom_hdr.ccdintfstatus
scch.SCSTATUS	=nom_hdr.preexpscstatus	; spacecraft status message before exposure

;	SCANT_ON:str,$	    ; T/F: derived from s/c status before and after
if ((strmid(string(nom_hdr.PREEXPSCSTATUS,'(b16.16)'),8,1) EQ 1) $
    	or (strmid(string(nom_hdr.POSTEXPSCSTATUS,'(b16.16)'),8,1) EQ 1)) $
    	    then scch.SCANT_ON='T' else scch.SCANT_ON='F'

scch.sync	=fort[nom_hdr.sync]
scch.CMDOFFSE   =nom_hdr.lightTravelOffsetTime/1000.

date_end_wexp=tai2utc(basehdr.actualexptime+scch.exptime, /nocorrect)
scch.DATE_END=utc2str(date_end_wexp,/noz)
date_av=tai2utc((basehdr.actualexptime+(scch.exptime/2)), /nocorrect)
scch.DATE_AVG=utc2str(date_av,/noz)

print,'door status is ',enums.edoorstatus[scch.doorstat]
IF (not(keyword_set(FAST))) THEN wait,4

; ++++ END nom_hdr

afternom_hdr:

prevbasename=basename

scch.N_IMAGES=1
; add event info if any 

critevent=string(basehdr.CRITEVENT,'(z4)')
scch.CRITEVT='0x'+strupcase(critevent)

; ++++ WCS/FITS standard definitions

scch.naxis1 	=(scch.p2col - scch.p1col + 1)/(2^(basehdr.sumcol+basehdr.sebxsum-2))
scch.naxis2 	=(scch.p2row - scch.p1row + 1)/(2^(basehdr.sumrow+basehdr.sebysum-2))
IF scch.comprssn EQ 5 THEN BEGIN    ; header only
    scch.naxis=0
    scch.naxis1=0
    scch.naxis2=0
ENDIF

;        COR1     COR2     HI    H2    EUVI
unitv=['arcsec','arcsec','deg','deg','arcsec']
IF strmid(scch.detector,0,2) EQ 'HI' THEN BEGIN
    scch.CTYPE1 ='HPLN-AZP'
    scch.CTYPE2 ='HPLT-AZP'
    scch.CTYPE1A='RA---AZP'
    scch.CTYPE2A='DEC--AZP'
    scch.CUNIT1='deg'
    scch.CUNIT2='deg'
    divisor=1.
ENDIF ELSE BEGIN
    scch.CUNIT1='arcsec'
    scch.CUNIT2='arcsec'
    divisor=3600.   ; for conversion from arcsec to degrees for SCIP RA-DEC values
ENDELSE
IF L EQ 'm' or strmid(scch.detector,0,2) EQ 'HI' THEN BEGIN
	pointingtime=scch.date_end
	hpct=', using DATE END'
ENDIF ELSE BEGIN
	pointingtime=scch.date_obs
	hpct=', using DATE OBS'
ENDELSE
unitAv=['deg','deg','deg','deg','deg']
scch.CUNIT1A=unitAv[ap1]
scch.CUNIT2A=unitAv[ap1]

;print,scch.cdelt1
;print,scch.history
;IF (scch.detector ne 'EUVI') THEN BEGIN
	;--crpix,cdelt for EUVI computed in euvi_point.pro, which is called after secchi_rectify 
	;  in secchi_reduce
	platescl=getsccsecpix(scch,/UPDATE, FAST=fast, _EXTRA=_extra)
	; UPDATE keyword adds HISTORY, CDELT*, PV2_1 to scch
	print,'CDELT: ',platescl
;stop
	crpix=getscccrpix(scch,/UPDATE, FAST=fast, _EXTRA=_extra)
	print,'CRPIX: ',crpix
;ENDIF

;add SPICE 
spicetime=0
hpccmnt='check ATT_FILE for pointing source'
IF	keyword_set(spice) and $
	(basehdr.actualexptime ne 0)  and $	; check for no image taken
	(scch.comprssn NE 5) 	$		; don't compute for header-only 
	then begin
    dopointing:
    print,'Computing ephemeris info from SPICE...'

    adndm=''
	atf=get_stereo_att_file(pointingtime,aorb)
	IF atf EQ '' THEN att_file='NotFound' ELSE att_file=atf
	help,att_file,ephemfil
	print,''
	IF keyword_set(ENDBADAH) THEN endbadaht=utc2str(anytim2utc(endbadah),/noz) ELSE endbadaht='2000/01/01'
    IF att_file EQ 'NotFound' and (islz) and (pointingtime LT endbadaht) THEN wait,1 
    IF att_file EQ 'NotFound' and (islz) and (pointingtime GT endbadaht) THEN BEGIN 
		print,'Waiting 2....'
		wait,2
		load_stereo_spice,/reload,/verbose
		adndm=' STEREO SPICE reloaded'
		atf 	    =get_stereo_spice_kernel(pointingtime,aorb,/ATTITUDE) 
    	    	EPHEMFIL    =get_stereo_spice_kernel(pointingtime,aorb)
		IF atf NE '' THEN att_file=atf ELSE $
		IF ~file_exist('attmsg.txt') THEN BEGIN
		; at start of each day rm attmsg.txt in reduce_main.pro
		    msg=pointingtime+': EPHEMFIL='+ephemfil+', ATT_FILE='+att_file
		    print,'Waiting 10...'
		    print
		    wait,10
		    openw,elun,'attmsg.txt',/get_lun
		    printf,elun,'in secchi_reduce.pro'
		    printf,elun,msg
		    printf,elun,''
		    close,elun
		    free_lun,elun
	    	    IF (islz) and ~keyword_set(TESTLZ) THEN $
		    spawn,'mailx -s ATT_FILE_NotFound secchipipeline@nrl.navy.mil < attmsg.txt',/sh
		ENDIF
    ENDIF 

    time0=systime(1)
    ;print,'Calling get_stereo_lonlat ...'
    hee_d=get_stereo_lonlat(pointingtime,strmid(scch.obsrvtry,7,1), /meters, system='HEE',_extra=_extra)
    ;print,'Calling get_stereo_lonlat ...'
    heeq=get_stereo_lonlat(pointingtime,strmid(scch.obsrvtry,7,1), /degrees, system='HEEQ',_extra=_extra)
    ;print,'Calling get_stereo_coord ...'
    coord=get_stereo_coord(pointingtime,strmid(scch.obsrvtry,7,1) , /meters ,_extra=_extra,ltime=sctime)
    ;print,'Calling get_stereo_coord ...'
    E_coord=get_stereo_coord(pointingtime,'Earth', /meters ,_extra=_extra,ltime=etime)
    ;printf,lulog,'Duration of 6 get_stereo calls ='+string(spicetime)
    scch.RSUN=(6.95508e8 * 648d3 / !dpi ) / hee_d(0)
    scch.HCIX_OBS=coord(0)
    scch.HCIY_OBS=coord(1)
    scch.HCIZ_OBS=coord(2)
    scch.DSUN_OBS=hee_d(0)
    scch.HGLN_OBS=heeq(1)
    scch.HGLT_OBS=heeq(2)
    scch.EAR_TIME=etime-sctime
    scch.SUN_TIME=sctime
    ;print,'Calling get_stereo_hpc_point ...'
    coord=get_stereo_coord(pointingtime,strmid(scch.obsrvtry,7,1) , /meters , system='HAE')
    	scch.HAEX_OBS=coord(0)
    	scch.HAEY_OBS=coord(1)
    	scch.HAEZ_OBS=coord(2)
    ;print,'Calling get_stereo_hpc_point ...'
    coord=get_stereo_coord(pointingtime,strmid(scch.obsrvtry,7,1) , /meters , system='HEE')
    	scch.HEEX_OBS=coord(0)
    	scch.HEEY_OBS=coord(1)
    	scch.HEEZ_OBS=coord(2)
    ;print,'Calling get_stereo_hpc_point ...'
    coord=get_stereo_coord(pointingtime,strmid(scch.obsrvtry,7,1) , /meters , system='HEEQ')
    	scch.HEQX_OBS=coord(0)
    	scch.HEQY_OBS=coord(1)
    	scch.HEQZ_OBS=coord(2)
	scch.EPHEMFIL=ephemfil		; in common scc_reduce


	;--Get pointing in helioprojective cartesian coordinates
	yprhpc=getsccpointing(scch,/updateheader, TOLERANCE=60, YPRSC=scp, FAST=fast, FOUND=ff, _EXTRA=_extra)
	IF (scch.detector EQ 'COR2') THEN $
		hpccmnt='Pointing info from SPICE, 1min. resolution'
	print,'YPR hpc = ',yprhpc
	IF ~keyword_set(FAST) THEN wait,2
	
	IF (scch.detector ne 'EUVI') THEN BEGIN
	    scch.CRVAL1	=yprhpc[0]
	    scch.CRVAL2	=yprhpc[1]
	ENDIF	
	; for EUVI contained in CRPIX and CRVAL=0
	scch.CROTA	=yprhpc[2]
	
	dr=!DPI/180.d
	scch.PC1_1= cos(yprhpc[2]*dr)
	scch.PC1_2=-sin(yprhpc[2]*dr) ;*(scch.CDELT1/scch.CDELT2) ;may be added later
	scch.PC2_1= sin(yprhpc[2]*dr) ;*(scch.CDELT1/scch.CDELT2)
	scch.PC2_2= cos(yprhpc[2]*dr)
	scch.SC_YAW	=scp[0]
	scch.SC_PITCH	=scp[1]
	scch.SC_ROLL	=scp[2]

	;--Get pointing in R.A.-Dec coordinates
	yprrd=getsccpointing(scch,/RADEC, TOLERANCE=60, YPRSC=scpa, FAST=fast, FOUND=ff, _EXTRA=_extra)
	help,ff
	IF ~keyword_set(FAST) THEN wait,2
	scch.ATT_FILE=att_file		; in common scc_reduce
		
	print,'YPR Ra,Dec = ',yprrd
	IF ~keyword_set(FAST) THEN wait,2
	;IF (scch.detector ne 'EUVI') THEN BEGIN
    	scch.CRVAL1A = yprrd[0]
    	scch.CRVAL2A = yprrd[1]
	;ENDIF
	
    ; Does this need a correction for EUVI? 
    ; this is set in getsccsecpix.pro
    ;scch.CDELT1A = -scch.CDELT1/divisor    ;Conversion from arcsec to degrees
    ;scch.CDELT2A =  scch.CDELT2/divisor    ;Conversion from arcsec to degrees
    scch.PC1_1A =  cos(yprrd[2]*dr)
    scch.PC1_2A = -sin(yprrd[2]*dr) * scch.CDELT2A / scch.CDELT1A
    scch.PC2_1A =  sin(yprrd[2]*dr) * scch.CDELT1A / scch.CDELT2A
    scch.PC2_2A =  cos(yprrd[2]*dr)
	scch.SC_YAWA	=scpa[0]
	scch.SC_PITA	=scpa[1]
	scch.SC_ROLLA	=scpa[2]

    carlonlat=get_stereo_lonlat(pointingtime,strmid(scch.obsrvtry,7,1),/au, /degrees, system='Carrington')
    scch.CRLN_OBS=carlonlat(1)
    IF scch.crln_obs LT 0 THEN scch.crln_obs = scch.crln_obs + 360
    scch.CRLT_OBS=carlonlat(2)
    
    spicetime=systime(1)-time0
    help,spicetime
    printf,lulog,'SPICE took'+string(spicetime)+adndm
	
endif

;scch.XCEN=scch.CRVAL1 + scch.CDELT1 * [(scch.NAXIS1+1)/2 - scch.CRPIX1]
;scch.YCEN=scch.CRVAL2 + scch.CDELT2 * [(scch.NAXIS2+1)/2 - scch.CRPIX2]
;i = ((scch.NAXIS1+1)/2 - scch.CRPIX1)
;j = ((scch.NAXIS2+1)/2 - scch.CRPIX2)
;scch.XCEN = scch.CRVAL1 + scch.CDELT1*scch.PC1_1*i + scch.CDELT1*scch.PC1_2*j
;scch.YCEN = scch.CRVAL2 + scch.CDELT2*scch.PC2_1*i + scch.CDELT2*scch.PC2_2*j
;++++ get XCEN and YCEN with spherical corrections 
; moved xcen, ycen to secchi_rectify.pro

sccdest=getenv('SECCHI')
IF (strpos(sccdest,'lz') GT 0)then scch.VCHANNEL=13 	;=7+6
IF (strpos(sccdest,'rt') GT 0)then scch.VCHANNEL=7
IF (strpos(sccdest,'pb') GT 0)then scch.VCHANNEL=6

sourcev=['x','x','RT','SSR1','SSR1','SSR2','x','SW']
scch.DOWNLINK=sourcev(ap0)
polcmt=''
IF scch.detector EQ 'COR2' or scch.detector EQ 'COR1' THEN BEGIN
    IF (scch.detector EQ 'COR1' and s NE 'B') THEN poloffset= -10. $ ; degrees
    ELSE poloffset=0    	    ; assuming position 0 = 0 degrees
    scch.polar      =degr + poloffset
    polcmt=' deg'
ENDIF

;check image exposure times and compare to previous exposure.
expdurcmt2=''
IF (strmid(scch.detector,0,2) ne "HI") THEN BEGIN
  expofile= concat_dir(getenv('SCC_LOG'),'prevexpo.sav')
  expofiletemp=findfile(expofile)
  if (expofiletemp eq '') then BEGIN
        prevexp=dblarr(5)  
  ENDIF else restore,expofile
  expdif=abs(scch.exptime - scch.expcmd)
  camtime=nom_hdr.ACTUALIMAGERETRIEVESTARTTIME - nom_hdr.ACTUALCCDCLEARSTARTTIME - cleardur
  if ( expdif gt scch.expcmd/2) and ( (round(scch.exptime) eq round(prevexp(ap1))) OR $
     ( expdif GT camtime) ) then begin
     expmsg= scch.filename+' correcting exp time from '+trim(scch.exptime)+' to exp cmd '+string(scch.expcmd,'(f7.4)')+', prev '+string(prevexp(ap1),'(f7.4)')
     print,''
     print,'!!!! ',expmsg
     wait,5
     printf,lulog,expmsg
     openw,elun,'ipmsg.txt',/get_lun,/append
     printf,elun,expmsg
     printf,elun,''
     close,elun
     free_lun,elun
     scch.exptime = scch.expcmd
     expdurcomment= ' bad actual exptim, using expcmd'
     expdurcmt2=' exp time corrected'+expdurcmt2
  ENDIF
  if (scch.SEB_PROG eq 'DOUBLE') and (scch.exptime ne scch.expcmd) then begin
     scch.exptime = scch.expcmd
     expdurcomment= ' bad actual exptim, using expcmd'
     expdurcmt2=' exp time corrected'+expdurcmt2
  endif
  prevexp(ap1) = scch.expcmd
  if (scch.SEB_PROG eq 'DOUBLE')then begin
     scchexptime_2=basehdr.ACTUALEXPDURATION_2*double(4.0e-6)   
     scchexpcmd_2=nom_hdr.CMDEXPDURATION_2*1.024e-3
     expdif=scchexptime_2 - scchexpcmd_2
     if (abs(expdif) gt scchexpcmd_2/2) then BEGIN; and (round(scchexptime_2) eq round(prevexp(ap1))) then BEGIN
       expmsg=scch.filename+' correcting exp time_2 from '+trim(scchexptime_2)+' to exp cmd '+string(scchexpcmd_2,'(f7.4)')+', prev '+string(prevexp(ap1),'(f7.4)')
     	print,''
     	print,'!!!! ',expmsg
     	wait,5
       printf,lulog,expmsg
       openw,elun,'ipmsg.txt',/get_lun,/append
       printf,elun,expmsg
       printf,elun,''
       close,elun
       free_lun,elun
       scchexptime_2=scchexpcmd_2
       expdurcomment= ' 2nd bad actual, using expcmd'
       expdurcmt2=' 2nd exp time corrected'+expdurcomment
     ENDIF
     prevexp(ap1) =scchexpcmd_2
  ENDIF
  save,filename=expofile,prevexp
ENDIF      

IF (trim(scch.seb_prog) eq 'DOUBLE') then BEGIN
    IF scch.detector EQ 'COR2' or scch.detector EQ 'COR1' THEN BEGIN
    	degr2 = (nom_hdr.cmdpolarposition_2) * 2.5 + poloffset
    	;degr = (nom_hdr.cmdpolarposition) * 2.5
    	polcmt= ' '+trim(scch.polar)+' deg + '+trim(degr2)+' deg'
    	scch.polar = 1001
    ENDIF
    exp1=scch.exptime
    exp2=scchexptime_2
    print,exp1,exp2
    if exp1+exp2 gt 200 then stop
    IF scch.detector NE 'EUVI' THEN begin
      scch.exptime=(exp1+exp2)/2
      expdurcomment=' avg of 2 exp'+expdurcomment
      scch.expcmd	=(cmdexpdur+nom_hdr.cmdexpduration_2)/2 * 1.024e-3
    ENDIF ELSE BEGIN
      scch.exptime=(exp1+exp2)
      expdurcomment=' total of 2 exp'+expdurcomment
      scch.expcmd	=(cmdexpdur+nom_hdr.cmdexpduration_2) * 1.024e-3
    ENDELSE
ENDIF


; hbtimes is set in secchi_reduce.pro
IF datatype(hbtimes) NE 'UND' THEN BEGIN
    ;put telescope temperatures from database into fits header
    if(scch.detector eq 'EUVI')then tempv=[0,1,2,3,4,5,23]
    if(scch.detector eq 'COR1')then tempv=[6,7,8,8,9,10,24] ;cor1 does not report TEMPMID2
    if(scch.detector eq 'COR2')then tempv=[11,12,13,14,15,16,25] 
    if(scch.detector eq 'HI1' )then tempv=[17,18,19,20,21,22,26]
    if(scch.detector eq 'HI2' )then tempv=[17,18,19,20,21,22,27]

    imtime=find_closest(date_obs_utc.(1),hbtimes.(1)) 

    if(imtime gt -1) and (imtime lt n_elements(hbtimes)-1) then begin
      scch.TEMPAFT1=hbtemps(tempv(0),imtime)
      scch.TEMPAFT2=hbtemps(tempv(1),imtime)
      scch.TEMPMID1=hbtemps(tempv(2),imtime)
     ;scch.TEMPTHRM'
      if(scch.detector ne 'COR1')then scch.TEMPMID2=hbtemps(tempv(3),imtime)
      scch.TEMPFWD1=hbtemps(tempv(4),imtime)
      scch.TEMPFWD2=hbtemps(tempv(5),imtime)
      scch.TEMP_CCD=hbtemps(tempv(6),imtime)
      if(scch.detector ne 'HI1' and scch.detector ne 'HI2') then $
	    scch.TEMP_CEB=hbtemps(28,imtime) else $
  	    scch.TEMP_CEB=hbtemps(29,imtime)
    endif
ENDIF
IF datatype(cebtimes) NE 'UND' THEN BEGIN
    imtimes=where(cebtimes.(1) ge date_obs_utc.(1)-(60*30*1000l) and cebtimes.(1) le  date_obs_utc.(1)+(60*30*1000l))
;    imtime=find_closest(date_obs_utc.(1),cebtimes.(1)) 
    if(imtimes(0) gt -1)then begin
      if(scch.detector ne 'HI1' and scch.detector ne 'HI2') then $
	    scch.CEB_T=median(cebtemps(1,imtimes)) else $
  	    scch.CEB_T=median(cebtemps(0,imtimes))
    endif
ENDIF


; cadence only calculated if not hdr only
if (scch.comprssn NE 5) then begin
  cadencefile= concat_dir(getenv('SCC_LOG'),'cadence.sav')
  cadencetemp=findfile(cadencefile)
    if (cadencetemp eq '') then BEGIN
        cadence=dblarr(3,32767) -1 
        iphicrs=124b     ; default is crs sigma 1 filter 
    ENDIF else restore,cadencefile
  case trim(scch.detector) of
    'HI1'     : cdcol2=0
    'HI2'     : cdcol2=0
    'COR1'    : cdcol2=scch.polar
    'COR2'    : cdcol2=scch.polar
    'EUVI'    : cdcol2=scch.wavelnth
    else      : cdcol2=0
  endcase
  cd1=where(cadence(0,*) eq scch.obs_id) ;find obs_id
  cd2=-1
  if(cd1(0) ne -1)then cd2=where(cadence(1,cd1) eq cdcol2) ;find correct pol or wl
  if(cd2(0) ne -1)then begin
     crow=cd1(cd2(0))
     scch.cadence=basehdr.actualexptime-cadence(2,crow)   
     cadence(2,crow)=basehdr.actualexptime
  endif
  if(cd1(0) eq -1 or cd2(0) eq -1 and strmid(scch.filename,17,1) ne '7')then begin
    nrow=where(cadence(0,*) eq -1) & nrow=nrow(0)
    cadence(0,nrow)=scch.obs_id
    cadence(1,nrow)=cdcol2
    cadence(2,nrow)=basehdr.actualexptime
    scch.cadence=0  
  endif  
  ;save new cadence values if not a SpWx image
  basename=strmid(scch.fileorig,0,8)
  if(strmid(scch.filename,17,1) ne '7')then save,filename=cadencefile,cadence,iphicrs,basename
endif

; ++++ Values from FSW img table files ++++

; first set some date/times which are breakpoints
;date_obs_utc	=tai2utc(basehdr.actualexptime, /nocorrect)
;scch.date_obs	=utc2str(date_obs_utc,/noz)
rotbchangedate='2006-12-08T16:00:01'
IF (aorb EQ 'B') THEN rotbchangedate='2006-12-07T13:30:57'

;tts=['c1','c2','h1','h2','eu']
;TT=tts[ap1]
; [readout,wave]
rowv=[[26,25],[28,27],[32,31],[34,33],[30,29]]
tids=[35,rowv[0,ap1],rowv[1,ap1],36,38,6]
; see $SSW/secchi/idl/database/fswtableids.txt
tbltagnames=['SETUPTBL', 'READFILE', 'WAVEFILE', 'EXPOSTBL', 'IP_TBL', 'MASK_TBL']
tbltagindx=tag_index(scch,tbltagnames)
ntids=n_elements(tids)
IF (resetvars) THEN reset=1 ELSE reset=0

;IF not(islz) or datatype(hbtimes) EQ 'UND' THEN goto, skiptables
; cannot skip tables because RO values must be set for HI

FOR ix=0,ntids-1 DO BEGIN
    tblval=getscctableinfo(aorb,scch.date_obs,tids[ix], RESET=reset, /USE_LOADTIME)
    reset=0
    print,tbltagnames[ix],' = ',tblval
    scch.(tbltagindx[ix])=tblval
ENDFOR
IF not(keyword_set(FAST)) THEN wait,2

break_file,scch.readfile,dlg,dir,fn,ext
if dir EQ 'camera/' THEN dir='ops/tables/current/'
if dir EQ 'is/'     THEN dir='ops/tables/current/'
if dir EQ 'source/swire/src/'     THEN dir='ops/tables/current/'

rotblfile=concat_dir(getenv('SCC_DATA'),dir+fn+".img")
IF (scch.date_obs LT rotbchangedate) THEN $
    rotblfile=concat_dir(getenv('SCC_DATA'), 'ops/tables/default/rotb07comnt.img')

IF (resetvars OR $
    strmid(scch.date_obs,0,10) EQ '2006-12-18' OR $
    strmid(scch.date_obs,0,10) EQ '2006-12-26') THEN spawn,"grep -h ';T'  "+rotblfile,  rotblidlines, /sh  
    ; dates of software patch
    
parts=strsplit(rotblidlines[scch.clr_tbl],',',/extract)
clrtblfile=parts[1]+trim(parts[2])
IF n_elements(parts) GT 11 THEN BEGIN
    scch.cleartim=float(parts[11])/1e6
    scch.line_clr=float(parts[10])/1e6
ENDIF

parts=strsplit(rotblidlines[scch.read_tbl],',',/extract)
readtblfile=parts[1]+trim(parts[2])
IF n_elements(parts) GT 11 THEN BEGIN
    scch.ro_delay=float(parts[11])/1e6
    scch.line_ro= float(parts[10])/1e6
ENDIF

skiptables:

;++++ convert scch structure to fits header ++++
;t0=systime(1)
;scch1 = rem_tag2(scch,'TIME_OBS')
;printf,lulog,'Rem_tag took ',systime(1)-t0,' sec'
fits_hdr = struct2fitshead(scch,/allow_crota,/dateunderscore)
sxdelpar,fits_hdr,['TIME_OBS','RAVG']

; ++++ Fill in comments  ++++
IF (scch.ceb_stat LT 25 and scch.ceb_stat GE 0) THEN $
fxaddpar,fits_hdr,'CEB_STAT',scch.ceb_stat,enums.camera_interface_status[scch.ceb_stat]
IF (scch.cam_stat LT 4 and scch.cam_stat GE 0) THEN $
fxaddpar,fits_hdr,'CAM_STAT',scch.cam_stat,enums.camera_program_state[scch.cam_stat]
doorval=enums.edoorstatus[scch.doorstat]
IF ((scch.doorstat EQ 1) AND ((scch.detector EQ 'HI1') OR  (scch.detector EQ 'HI2'))) $
THEN 	fxaddpar,fits_hdr,'DOORSTAT',scch.doorstat,'(HI door is OPEN; microswitch is inaccurate)' $
ELSE IF scch.doorstat EQ 3 and scch.detector EQ 'EUVI' THEN $
    	fxaddpar,fits_hdr,'DOORSTAT',scch.doorstat,'(EUVI door disabled in OPEN position)' $
ELSE 	fxaddpar,fits_hdr,'DOORSTAT',scch.doorstat,doorval
;fxaddpar,fits_hdr,'HISTORY',version
;fxaddpar,fits_hdr,'DATE-OBS',scch.date_obs
fxaddpar,fits_hdr,'COMPRSSN',scch.comprssn,compr_string
fxaddpar,fits_hdr,'SC_ROLL',scch.sc_roll,'degrees'
fxaddpar,fits_hdr,'SC_PITCH',scch.sc_pitch,'arcsec'
fxaddpar,fits_hdr,'SC_YAW',scch.sc_yaw,'arcsec'
fxaddpar,fits_hdr,'EXPTIME',scch.exptime,expdurcomment
fxaddpar,fits_hdr,'POLAR',scch.polar,polcmt
IF (islz) and datatype(hbtimes) NE 'UND' THEN BEGIN
	; hbtimes is proxy for database availability
	fxaddpar,fits_hdr,'CLR_TBL',scch.clr_tbl,clrtblfile
	fxaddpar,fits_hdr,'READ_TBL',scch.read_tbl,readtblfile
ENDIF
fxaddpar,fits_hdr,'COMMENT','EXP TIME'+expdurcomment
fxaddpar,fits_hdr,'COMMENT','Est. clear duration = '+trim(string(cleardur))+' sec.'
IF (islz) THEN IF L EQ 'd' THEN fxaddpar,fits_hdr,'COMMENT',getscctableinfo(aorb,scch.date_obs,8, RESET=reset, /USE_LOADTIME)
; threshold table used
fxaddpar,fits_hdr,'COMMENT',hpccmnt+hpct
IF expdurcmt2 NE '' THEN fxaddpar,fits_hdr,'COMMENT',expdurcmt2
for i=0,9 do $
	fxaddpar,fits_hdr,'ip_prog'+trim(string(i)), fix(basehdr.ipcmdlog[i]), $
	ipdat[basehdr.ipcmdlog[i]]

;  use NONE for MASK_TBL if no mask applied: functions 25,27,45,46,47
xx=where(basehdr.ipcmdlog EQ 25, nmsk1)
xx=where(basehdr.ipcmdlog EQ 27, nmsko)
xx=where(basehdr.ipcmdlog EQ 45, nmsk2)
xx=where(basehdr.ipcmdlog EQ 46, nmsk3)
xx=where(basehdr.ipcmdlog EQ 47, nmsk4)
IF (nmsk1+nmsko+nmsk2+nmsk3+nmsk4) LE 0 THEN begin 
	fxaddpar,fits_hdr,'MASK_TBL','NONE',scch.mask_tbl 
	scch.mask_tbl='NONE'
  endif ELSE BEGIN
	msg='IP has applied a mask.'
	printf,lulog,msg
	print,msg
	print
	IF not(keyword_set(FAST)) THEN wait,2
  ENDELSE

return, fits_hdr


END
