;+
;PROCEDURE:	mvn_sta_prod_cal,all=all,units=units,apids=apids,test=test,gf_nor=gf_nor,return_nrg=return_nrg,nrg_swp
;PURPOSE:	
;	Calibrates STATIC data products generated by mvn_sta_apid_handler.pro
;INPUT:		
;
;KEYWORDS:
;	all		0/1		if not set, then raw tplot structures are deleted
;	units		string		select the units for generated tplot structures
;	apids		strarr		if set, selectes subset of apids to generate tplot structures
;	test		0/1		if set, prints out MLUT check
;	gf_nor		0/1		if set, keyword for testing mechanical attenuator - ignores attM open or closed
;	return_ngr	0/1		if set, returns energy sweep table in "nrg" keyword
;	nrg_swp		fltarr		returned sweep table if return_nrg keyword is set
;
;
;CREATED BY:	J. McFadden	2012/10/04
;VERSION:	1
;LAST MODIFICATION:  2014/03/14
;MOD HISTORY:
;
;NOTES:	 L0 files changed to APID 0x62 (instead of 0x51) 
;
; TBDs to make the code consistent with SIS:
;
;	tbd	modify code to account for non-perfect attenuation of attE and lowest energy sample where attE is activated
;
;	tbd	correct program for leakage by electrostatic attenuator at low energy - 
;			currently these data are flagged with the quality flag
;
;	tbd	current code uses swp2gfan and swp2gfdf to help approximate gf for omni-directional apids - c0,c2,c4,c6
;			need to check whether this properly handles theta and azimuthal angle ranges
;	add	gf_corr[npts,nenergy] to common blocks for apids c0,c2,c4,c6,c8 to account for sensitivity variation with ion flux direction
;
;	tbd	may need to change the code that throws away extra data at end of file
;
;	fix	eff array
;	add	eff_ind coding from time and swp_ind
;	mod	eff dimension
;
;	mod	bkg so it varies with time (it will contain the estimated straggling counts)
;	
;	change	"test" keyword -- may have conflicts
;
;	add	change gf to account for narrow cold beams centered on a sector - no losses from ESA exit posts or TOF posts, see lines 178 and 600
;
;													 
;		quality_flag definition						 determined from
;
;			bit 0	test pulser on					- testpulser header bit set
;			bit 1	diagnostic mode					- diagnostic header bit set
;			bit 2	dead time correction >2 flag			- deadtime correction > 2
;			bit 3	detector droop correction >2 flag 		- mcp droop flagged if correction > 2
;			bit 4	dead time correction not at event time		- missing data quantity for deadtime
;			bit 5	electrostatic attenuator failing at low energy	- attE on and eprom_ver<2
;			bit 6   attenuator change during accumulation		- att 1->2 or 2->1 transition (one measurement)	
;			bit 7	mode change during accumulation			- only needed for packets that average data during mode transition
;			bit 8	lpw sweeps interfering with data 		- lpw mode not dust mode
;			bit 9	high background 		 		- minimum value in DA > 10000 Hz
;			bit 10	no background subtraction array		 	- dat.bkg = 0		- may not be needed
;			bit 11	missing spacecraft potential			- dat.sc_pot = 0	- may not be needed	
;			bit 12	inflight calibration incomplete			- date determined, set to 1 until calibration finalized
;			bit 13	geometric factor problem			- 
;			bit 14	ion suppression problem				- low energy ions <6eV have wrong geometric factor
;			bit 15	not used =0
;
;
;-
pro mvn_sta_prod_cal,all=all,units=units,apids=apids,test=test,gf_nor=gf_nor,ignore=ignore,return_nrg=return_nrg,nrg_swp

; determine the first time in the data, could be used in determining which SLUT/MLUT table was loaded
   if not keyword_set(first_t) then begin				; for testing
	get_data,'mvn_STA_C0_DATA',data=t
	if size(/type,t) eq 8 then begin
		first_t=t.x[0]
	endif else first_t = time_double('2013-12-15/0')		; expected MLUT update time
   endif

; The following gets config4 from housekeeping which is used in conjunction with header mode nibble (md2) to determine sweep values
;	Note: mission was started with config4 set to 0x1111

	get_data,'mvn_STA_2A_hkp_ch69_Config4',data=config4
	if not keyword_set(config4) then begin
		if not keyword_set(return_nrg) then mvn_sta_hkp_cal,def_lim=1
		get_data,'mvn_STA_2A_hkp_ch69_Config4',data=config4
		if not keyword_set(config4) then begin
			config4_def=0
			print,'STATIC ERROR - No Housekeeping Data, setting default value for config4 to: ',config4_def
			config4={x:[time_double('2013-01-01/0'),time_double('2033-01-01/0')],y:[config4_def,config4_def]}
		endif
	endif 
	

; this section does nothing - obsolete - thought to be useful to change tplot units globally
if keyword_set(units) then begin
	un = units
	if units eq 'cnts' then un=0
	if units eq 'eflx' then un=1
endif else un=0

cols=get_colors()

; decompression array 19 bit -> 8 bit

decomp19=dblarr(256)
decomp19[0:127]=$
[0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0,13.0,14.0,15.0,$
16.0,17.0,18.0,19.0,20.0,21.0,22.0,23.0,24.0,25.0,26.0,27.0,28.0,29.0,30.0,31.0,$
32.5,34.5,36.5,38.5,40.5,42.5,44.5,46.5,48.5,50.5,52.5,54.5,56.5,58.5,60.5,62.5,$
65.5,69.5,73.5,77.5,81.5,85.5,89.5,93.5,97.5,101.5,105.5,109.5,113.5,117.5,121.5,125.5,$
131.5,139.5,147.5,155.5,163.5,171.5,179.5,187.5,195.5,203.5,211.5,219.5,227.5,235.5,243.5,251.5,$
263.5,279.5,295.5,311.5,327.5,343.5,359.5,375.5,391.5,407.5,423.5,439.5,455.5,471.5,487.5,503.5,$
527.5,559.5,591.5,623.5,655.5,687.5,719.5,751.5,783.5,815.5,847.5,879.5,911.5,943.5,975.5,1007.5,$
1055.5,1119.5,1183.5,1247.5,1311.5,1375.5,1439.5,1503.5,1567.5,1631.5,1695.5,1759.5,1823.5,1887.5,1951.5,2015.5]

decomp19[128:255]=$
[2111.5,2239.5,2367.5,2495.5,2623.5,2751.5,2879.5,3007.5,3135.5,3263.5,3391.5,3519.5,3647.5,3775.5,3903.5,4031.5,$
4223.5,4479.5,4735.5,4991.5,5247.5,5503.5,5759.5,6015.5,6271.5,6527.5,6783.5,7039.5,7295.5,7551.5,7807.5,8063.5,$
8447.5,8959.5,9471.5,9983.5,10495.5,11007.5,11519.5,12031.5,12543.5,13055.5,13567.5,14079.5,14591.5,15103.5,15615.5,16127.5,$
16895.5,17919.5,18943.5,19967.5,20991.5,22015.5,23039.5,24063.5,25087.5,26111.5,27135.5,28159.5,29183.5,30207.5,31231.5,32255.5,$
33791.5,35839.5,37887.5,39935.5,41983.5,44031.5,46079.5,48127.5,50175.5,52223.5,54271.5,56319.5,58367.5,60415.5,62463.5,64511.5,$
67583.5,71679.5,75775.5,79871.5,83967.5,88063.5,92159.5,96255.5,100351.5,104447.5,108543.5,112639.5,116735.5,120831.5,124927.5,129023.5,$
135167.5,143359.5,151551.5,159743.5,167935.5,176127.5,184319.5,192511.5,200703.5,208895.5,217087.5,225279.5,233471.5,241663.5,249855.5,258047.5,$
270335.5,286719.5,303103.5,319487.5,335871.5,352255.5,368639.5,385023.5,401407.5,417791.5,434175.5,450559.5,466943.5,483327.5,499711.5,516095.5]

; Calibration array naming
;	n_swp - number of energy sweep arrays
;	nenergy - number of energy steps in a 
;	def[n_swp,64,16] - deflection angle (16) as a function of sweep(n_swp) and energy(64)
;	gf[n_swp,
;	def2gf
;	md2swp

; Notes on 7bit ModeID in packet headers  CAAAAAAA = XRRRMMMM  

; 	where RRR  is the data rate  : ATLO RRR=000, x1 RRR=001, x1.5 RRR=010, x2 RRR=011, x3.25 RRR=100, x4.0 RRR = 101, x4.5 RRR = 110
; 	where MMMM is the orbit mode : startup MMMM=0000, ram MMMM=0001, conic MMMM=0010, pickup MMMM=0011, scan MMMM=0100
;		we might have to abandon this coding if we start changing sweep tables, or rely on time to determine which sweep table is valid
;
; Notes on geometric factors and efficiency
;
;	geom_factor is a time independent geometric factor at the start of the mission that include all known mechanical attenuations
;
;	gf[mode,en,def,an,att] is a time independent, energy-deflector-anode-attenuator dependent geometric factor 
;		- inflight calibration concerns this array to get the acual relative attenuation by grids and attenuators
;		- see mvn_sta_calibration_notes.txt
;	the next 16 lines are probably obsolete
;		gf is determined from gf_en[energy[mode]],def_map[apid,mode],agf[time],mec[att],egf[att], - no mass dependence
;			agf is may decrease over time as some foils degrade, but at start of mission assume it is constant 
;  			ecl = 1. 	& ech=30.  	& exit1=   (1.+.121*(1.-(alog(energy/ecl>1.)/alog(ech/ecl)<1.)))	;due to ESA exit grid 
;  			ecl = 10. 	& ech=300. 	& exit2=   (1.+.121*(1.-(alog(energy/ecl>1.)/alog(ech/ecl)<1.)))	;due to ESA exit grid 
;			gf_en = exit1*exit2
;		gf =    gf_en(64)#replicate(1.,16)*gf_df(64,16) # gf_an[att,an] # replicate(1.,64)
;
;	eff[en,an,ma] is the energy-anode-mass dependent efficiency at the start of the mission - assumed constant
;		eff is determined from energy[mode] and eff_en_an_ma[] and an_map[apid,mode] and ma_map[apid,mode] 
;			foils could thin over time and so that high mass efficiencies could increase (look for this)
;
;		((en+15000.)-en15)*(eff20-eff15)/(en20-en15) < max_eff
;		eff2=eff_en_an_ma[1,*,i]-eff_en_an_ma[0,*,i])
;		replicate(1.,64)#reform(eff_en_an_ma[0,*,i]) + ((15000.+energy-delta)/(20000.-delta))^2#reform(eff_en_an_ma[1,*,i]-eff_en_an_ma[0,*,i])
;		replicate(1.,64)#reform(eff_en_an_ma[0,*,i]) + ((15000.+energy)/5000.)^2#replicate(1.,64)
;
; Notes on ordering data in arrays
;	[en,def,an,ma]
;
;

; Calibration values and arrays -- nominal values used as place holders
; 20190419 The calculated geom_factor appears to be ~60% too low based on in-flight calibrations
; geom_factor can be corrected by running mvn_sta_load_gf_update.pro until the l2 files are updated
									; ESA Entrance Aperture Hex Grids: 91.9% transmission
									; ESA Exit Grid pair at spyder plate: 89.2% transmission
									; TOF Start/Stop suppression grids:   83.5% & 82.6% transmission
									; TOF foil frame grids 333 lpi: 65% transmission
	geom = 	0.016/16.						; nominal ESA geometric factor 0.001057* R*R*E (from CODIF simulation), R=3.895 cm (dia = 3.071 inches) for one anode
	geom = geom*(0.919)^3*0.835*0.62				; grid attenuation (3 entrance grids - 91.9%, 1 foil suppresion grid - 83.5%, 1 foil frame grid - 62%)
	geom = geom*(0.7556)*(0.9)					; post attenuation (ESA entrance and exit posts) 

; we need to include an energy dependent transmission -- impact high energy ions, low energy ions see leakage fields
	geom = geom*(0.892)^2						; ESA exit grids are 89.2% transmission -- impact high energy ions, low energy ions see leakage fields
	geom = geom*(0.9)						; TOF ribs attenuate high energy ions (~0.9)
	geom_factor = geom



	nrg_const = 7.8							; simulation energy constant
	def_const = 6.4							; simulation deflector constant (Vdef/Vinner) for 45 deg deflection
	scale = 1.046							; energy correction, produces the proper energy scaling for SLUT tables
	def_scale = 43./45.						; angle correction, produces the proper deflection angle scaling for SLUT tables
;	energy constant = 7.51715 * scale = 7.863			; ground calibration value for energy constant

	dt_cor = 3.89/4.						; scale integ_t to account for settling time
									; p.7 of MAVEN_PF_STATIC_012Q_FPGA_Specification.pdf
									; (62.2 ms - 1.4 ms) x 64 = 3.89 sec


; according to Jasper Halekas, deflection only impacts sensitivity with attenuators out.

; initial approximation of defector collimation attenuation
; old	def2gf = fltarr(46)						; allows calculation of def attenuation for arbitrary center deflection angle
; old	def2gf[0:29]  = 1.						; values of def2gf should be reviewed
; old	def2gf[30:45] = 1. - .45*findgen(16)/15.

; deflector simulation data from Jasper Halekas, theta_zero2 are the peaks, theta_zero is the assumed median deflection which we should use
;	g_th_zero =  [0.120, 0.154, 0.168, 0.177, 0.181, 0.183, 0.183, 0.183, 0.183, 0.183, 0.183, 0.184, 0.184, 0.183, 0.183, 0.183, 0.183, 0.183, 0.181, 0.177, 0.168, 0.152, 0.124, 0.062]
;	theta_zero2 = [-41.7, -37.6, -34.1, -30.9, -27.5, -24.2, -20.5, -16.6, -12.3, -9.1,   -5.5,  -2.2,   1.5,   5.6,   9.5,  13.4,  17.4,  22.0,  26.2,  30.5,  34.7,  38.8,  43.1,  47.0]
;	theta_zero = -43.125 + findgen(24)*3.75
;		the following is an approximation based on Jasper's simulation and may need some adjustment
;		calibrations suggest 45.01 should be 43
;	theta_zero = -45.01 + findgen(24)*90.01/23.		; this was the initial guess for calibrations before Jasper supplied simulation data

	theta_zero = -43.125 + findgen(24)*3.75
	g_th_zero =  [0.120, 0.154, 0.168, 0.177, 0.181, 0.183, 0.183, 0.183, 0.183, 0.183, 0.183, 0.183, 0.183, 0.183, 0.183, 0.183, 0.183, 0.183, 0.181, 0.177, 0.168, 0.152, 0.124, 0.062]

;	def2gf = replicate(1.,46)					; allows calculation of def attenuation for arbitrary center deflection angle
;	for i=23,45 do begin
;		minth=min(abs(theta_zero-i),ind)
;		if i ge theta_zero[ind] then def2gf[i] = (g_th_zero[ind] + (g_th_zero[ind+1]-g_th_zero[ind])*(theta_zero[ind]-i)/(theta_zero[ind]-theta_zero[ind+1]))/.183								
;		if i lt theta_zero[ind] then def2gf[i] = (g_th_zero[ind] + (g_th_zero[ind-1]-g_th_zero[ind])*(theta_zero[ind]-i)/(theta_zero[ind]-theta_zero[ind-1]))/.183								
;	endfor

;  include deflector asymmetry - this may have a sign error
;  Check inflight calibrations, may need to add g_th_zero=reverse(g_th_zero) ?????????????????????

	def2gf = replicate(1.,91)					; allows calculation of def attenuation for arbitrary center deflection angle
	for i=0,90 do begin
		th = -45+i
		minth=min(abs(theta_zero-th),ind)
		if th ge theta_zero[ind] then def2gf[i] = (g_th_zero[ind] + (g_th_zero[ind+1<23]-g_th_zero[ind])*(theta_zero[ind]-th)/(theta_zero[ind]-theta_zero[ind+1<23]))/.183								
		if th lt theta_zero[ind] then def2gf[i] = (g_th_zero[ind] + (g_th_zero[ind-1>0] -g_th_zero[ind])*(theta_zero[ind]-th)/(theta_zero[ind]-theta_zero[ind-1>0] ))/.183								
	endfor

; Include the increased grid losses at large deflections 

	grid_thickness	= 0.003			; mill
	wire_spacing	= 0.0693		; mill
	def2gf1 = ((cos(findgen(46)/!radeg)-(grid_thickness/wire_spacing)*sin(findgen(46)/!radeg))/cos(findgen(46)/!radeg))^3

; electrostatic attenuator

	e_att = 0.0897  						; calculated electrostatic attenuation value - was incorrectly calculated to be 0.09133 prior to 20150202
	e_ano = replicate(1.,16)					; electrostatic grid attenuator variation with anode, assumes no variation 

;	t0    = -2.15							; TOF offset in ns, not used

; TDC peaks in MH hot  +56C:  TDC2 222,466,709	TDC1 228,472,715	; 20121105_011833_fm_tvac_lpt_hot3,  243.5, 24MHz --> 5.844bins/ns , offsets=21.5,15.5
; TDC peaks in MH room +29C:  TDC2 222,465,709	TDC1 228,471,715	; 20121102_021952_fm_tvac_prod4,     243.5, 24MHz --> 5.844bins/ns , offsets=21.5,15.5
; TDC peaks in MH cold -26C:  TDC2 218,457,698	TDC1 224,463,703	; 20121105_064622_fm_tvac_lpt_cold3, 240.0, 24MHz --> 5.760bins/ns , offsets=22.0,16.0
; Based on thermal vac, we might expect TOFs to vary by 1.5% with temperature
; Nominal cruise phase temperature is 8C
; 	b_ns  = 5.760 							; May want to change to this value and redue MLUT3 if STATIC runs cold. 
 	b_ns  = 5.844 							; TOF bins/ns for TOF timing (not sure if this is 5.844 or 5.855 for flight unit) 

	tdc1_offset = 16.
	tdc2_offset = 22.


; From calibrations - Anode Bin Rejecton Boundaries in hex 
; Instrument commands 0x50-5F and 0x60-6F
; FM Anode 		FM tdc3		FM tdc4
;	1		93   8c		93   8c
;	2		81   7a		81   7a
;	3		6e   67		6e   67
;	4		5b   54		5a   53
;	5		49   42		48   41
;	6		38   31		35   2e
;	7		24   1d		22   1b
;	8		12   0b		0f   08
;	9		05   0c		09   10
;	10		1b   23		1b   22
;	11		2b   32		2e   35
;	12		3c   43		41   48
;	13		50   57		54   5b
;	14		62   69		67   6e
;	15		74   7b		79   80
;	16		86   8d		8c   93

; Anode bin boundaries transfered to decimal, note only the highest 8 bits of a 10 bit tdc3 and tdc4 are used

; Note 	- anode bin boundaries were changed on 20160205 when significant anode rejection was discovered
;	- the larger then expected anode boundary drift is probably due to temperature - unexpected based on TOF TDC ground measurements
;	- rejection compared to new tables is roughly as follows on 20160211 - primarily in anodes 0-2,15
;	- [0.397741, 0.330852, 0.667227, 0.927560, 0.936383, 0.891164, 0.971529, 0.979680
;	   0.975024, 0.962121, 0.922044, 0.915169, 0.914899, 0.842561, 0.859615, 0.601016]
;	- anode rejection for O2+ at periapsis is about 30% due to scattering in the stop foils
;
;	new tables uploaded 20160205

;	the following are the anode rejection tables from launch to 20160205
	an_bin_tdc3 = intarr(16,2) 
	an_bin_tdc4 = intarr(16,2) 
	an_bin_tdc3[*,0] = [147,129,110, 91, 73, 56, 36, 18,  5, 27, 43, 60, 80, 98,116,134]
	an_bin_tdc3[*,1] = [140,122,103, 84, 66, 49, 29, 11, 12, 35, 50, 67, 87,105,123,141]
	an_bin_tdc4[*,0] = [147,129,110, 90, 72, 53, 34, 15,  9, 27, 46, 65, 84,103,121,140]
	an_bin_tdc4[*,1] = [140,122,103, 83, 65, 46, 27,  8, 16, 34, 53, 72, 91,110,128,147]

 	p_ns_3  	= (147+140+134+141)/32. 				; 32 ns delay for the entire anode (15+1)*2ns
 	p_ns_4  	= (147+140+140+147)/32. 
	tdc3_offset 	= (18+11-5-12)/4.
	tdc4_offset 	= (15+ 8-9-16)/4.

	mass_bias_offset = intarr(16)						; value at launch
;	mass_bias_offset = [0,0,0,0,0,0,0,0,-3,-3,-3,-3,-3,-3,-3,-3]		; TBD - this should upload at MOI to account for different tdc1 and tdc2 offsets
	evconvlut	 = 255							; nominal value, this should only change if a preamp or tdc dies
	timerst		 = 10							; 0x46 set to 0x0a, command cmd.STA_EVPFMRCTL(TIMERSTDUR=0x0a)

; There are several TOF offset errors between the start and stop due to TDC offsets, test pulser offsets, and differences between start/stop electron TOFs
; The total test pulser and TDC offset is ~22 (243.5-222), but we only care about the TDC offset which is not measured directly
; The electron TOF difference can be estimated from the extra distance of travel for a start electron divided by its average velocity (avg energy ~625 eV)
;	A 625 eV e-, Vel~1.5 cm/ns, and a distance ~3 cm gives an overall travel time of ~2 ns (this can also be simulated)
; The overall offset must be determined from calibration data to make the mass peaks line up
; 15 keV He+ tof=128, 15keV H+ tof=55, assume foil energy loss ~ (500 + m*1000./8.) -- we don't need this assumption
;	offset = (.4934*128 - 55)/(1.-.4934)		where .4934 = (m1/m2)^.5 * ((15000-1000)/(15000-625))^.5
; Note - the tof_offset was determined by comparison of the measured proton peak to simulation.

	tof_offset = 16

mhist_tof = (findgen(1024)+tof_offset)/b_ns				; need to decide if we want that offset in this formula???????????????????????

;	for now just use nominal acc, but if this is changed during mission we will need to
	acc = 15000.							; nominal TOF acceleration voltage, hkp shows 14947 V 

;************************************************************************************************ 
;************************************************************************************************ 
; Dead Time corrections - see MAVEN_PF_STATIC_012Q_FPGA_Specification.pdf
;	EVTOUT in CTM (0x40 command or cmd.STA_EVPCTL) is called Event Timeout (TOINT) in MAVEN_PF_STATIC_012Q_FPGA_Specification.pdf 
;	timing jitter is assumed to be +20 ns since the event could have occurred anywhere in the previous 40ns interval
; 	cmd.STA_EVPCTL(ABINMODE=0, MBINMODE=0, P4SEL=1, STOPFIRSTOK=0, EVTOUT=3, NUMEVENTS=3)  
;	cmd.STA_EVPFMRCTL(TIMERSTDUR=0x0a)  - 
; valid   events 		480 ns + 20 ns = 500 ns dead time, 20 ns jitter		(Conversion Time) + 40ns*(EVTOUT+1) 	+ jitter 	200  + 40*4  + 20	= 380 ns
; invalid events 		720 ns + 20 ns = 740 ns dead time, 20 ns jitter		40ns*(EVTOUT+1) + 40ns*TIMERSTDUR 	+ jitter	40*4 + 40*11 + 20 	= 620 ns
; stop no start events		440 ns + 20 ns = 460 ns dead time, 20 ns jitter		40ns*(TIMERSTDUR+1) 			+ jitter	40*11        + 20	= 440 ns
;
; We also need a correction for qual/total  -- a form of dead time due to start droop
; ??????????????????????????????????????????
;dead1 = 500. 
;dead2 = 740.
dead1 = 420. 		; qualified events
dead2 = 660.		; unqualified events
dead3 = 460.		; stop-no-start and stop-then-start events

;************************************************************************************************ 
;************************************************************************************************ 

; eff_start = qual/C&D ~ 0.65 (EM)
; eff_stop  = qual/A&B ~ 0.47 (EM)
; qual/Trst = (1. + (1.-eff_start)*(1.-eff_stop)) * eff_start * eff_stop

; 0.36 ~ qual/Trst = (1. + (1.-eff_start)*(1.-eff_stop)) * eff_start * eff_stop ~ 0.36
; print,(1. + (1.-.65)*(1.-.47)) * .65 * .47

;************************************************************************************************ 
;************************************************************************************************ 
; Declare time dependent efficiency arrays -- assume 10 changes in these arrays over time????

def_eff = .285		; early mission solar wind proton efficiency, includes ~0.8 anode rejection efficiency

; The below arrays are from ground calibrations with the Colutron gun
; Ground calibration efficiency of foils, ignoring holes in start foils, at 15 keV, 20 keV for H+,H2+,He+,N+,N2+,CO2+
; Note that "measured" start efficiency can be effected by mcp droop  -- ie is smaller with higher count rate -- measure start eff at lower  rates.
; Note that "measured" stop  efficiency can be effected by background -- ie is smaller with lower  count rate -- measure stop  eff at higher rates.
; Efficiency for molecule is 1-(1-eff*open_area)^n , where n is the number of components in the molecule

; there appears to be an energy dependent start efficiency. This may be a biasing of the measurement due to stop eff changes.
; as the energy goes up, more of the stop pulses near the edges of the 22deg window will be lost which biases stop events to the center of the anode
	eff_start_en_an_ma = fltarr(3,16,6)

;	eff_start_en_an_ma[0,*,0]=[.660,.660,.695,.695,.705,.705,.730,.730,.735,.735,.700,.700,.675,.675,.655,.655]			; H+	13 keV
	eff_start_en_an_ma[0,*,0]=[.665,.665,.700,.700,.730,.730,.715,.715,.715,.715,.695,.695,.690,.690,.675,.675]			; H+	17 keV  
	eff_start_en_an_ma[1,*,0]=[.685,.685,.685,.685,.720,.720,.700,.700,.720,.720,.700,.700,.685,.685,.700,.700]			; H+	20 keV
	eff_start_en_an_ma[2,*,0]=[.710,.710,.725,.725,.730,.730,.730,.730,.730,.730,.685,.685,.700,.700,.740,.740]			; H+	25 keV  

	eff_start_en_an_ma[0,*,1]=[.765,.765,.760,.760,.795,.795,.800,.800,.815,.815,.775,.775,.775,.775,.760,.760]			; H2+	17 keV
	eff_start_en_an_ma[1,*,1]=[.780,.780,.800,.800,.800,.800,.800,.800,.800,.800,.780,.780,.800,.800,.780,.780]			; H2+	20 keV
	eff_start_en_an_ma[2,*,1]=[.820,.820,.835,.835,.835,.835,.835,.835,.840,.840,.820,.820,.820,.820,.805,.805]			; H2+	25 keV

	eff_start_en_an_ma[0,*,2]=[.665,.665,.685,.685,.735,.735,.715,.715,.700,.700,.665,.665,.680,.680,.668,.668]			; He+	17 keV
	eff_start_en_an_ma[1,*,2]=[.700,.700,.700,.700,.740,.740,.740,.740,.740,.740,.720,.720,.685,.685,.685,.685]			; He+	20 keV

	eff_start_en_an_ma[0,*,3]=[.758,.758,.751,.751,.786,.786,.779,.779,.801,.801,.758,.758,.765,.765,.725,.725]			; N+	16 keV
	eff_start_en_an_ma[1,*,3]=[.770,.770,.760,.760,.800,.800,.800,.800,.800,.800,.775,.775,.770,.770,.760,.760]			; N+	20 keV
	eff_start_en_an_ma[2,*,3]=[.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7]			; N+	25 keV, count rate too low

	eff_start_en_an_ma[0,*,4]=[.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7]			; N2+	16 keV, beam fluctuations
	eff_start_en_an_ma[1,*,4]=[.845,.845,.823,.823,.861,.861,.861,.861,.885,.885,.853,.853,.861,.861,.845,.845]			; N2+	20 keV

	eff_start_en_an_ma[0,*,5]=[.765,.765,.725,.725,.765,.765,.779,.779,.815,.815,.765,.765,.745,.745,.731,.731]			; CO2+	17 keV
	eff_start_en_an_ma[1,*,5]=[.760,.760,.740,.740,.780,.780,.795,.795,.795,.795,.740,.740,.740,.740,.740,.740]			; CO2+	20 keV


;************************************************************************************************ 


	eff__stop_en_an_ma = fltarr(3,16,6)

	eff__stop_en_an_ma[0,*,0]=[.440,.440,.445,.445,.425,.425,.425,.425,.495,.495,.430,.430,.485,.485,.460,.460]			; H+	17 keV  
	eff__stop_en_an_ma[1,*,0]=[.440,.440,.450,.450,.430,.430,.440,.440,.495,.495,.440,.440,.495,.495,.460,.460]			; H+	20 keV
	eff__stop_en_an_ma[2,*,0]=[.465,.465,.470,.470,.445,.445,.445,.445,.525,.525,.455,.455,.510,.510,.485,.485]			; H+	25 keV  

	eff__stop_en_an_ma[0,*,1]=[.610,.610,.605,.605,.575,.575,.595,.595,.655,.655,.590,.590,.630,.630,.625,.625]			; H2+	17 keV
	eff__stop_en_an_ma[1,*,1]=[.625,.625,.625,.625,.600,.600,.610,.610,.675,.675,.610,.610,.640,.640,.640,.640]			; H2+	20 keV
	eff__stop_en_an_ma[2,*,1]=[.630,.630,.655,.655,.610,.610,.630,.630,.700,.700,.640,.640,.690,.690,.670,.670]			; H2+	25 keV

	eff__stop_en_an_ma[0,*,2]=[.435,.435,.435,.435,.420,.420,.420,.420,.480,.480,.425,.425,.465,.465,.450,.450]			; He+	17 keV
	eff__stop_en_an_ma[1,*,2]=[.440,.440,.450,.450,.450,.450,.430,.430,.495,.495,.440,.440,.485,.485,.460,.460]			; He+	20 keV

	eff__stop_en_an_ma[0,*,3]=[.431,.431,.447,.447,.431,.431,.423,.423,.476,.476,.404,.404,.451,.451,.443,.443]			; N+	16 keV
	eff__stop_en_an_ma[1,*,3]=[.450,.450,.460,.460,.450,.450,.440,.440,.495,.495,.440,.440,.475,.475,.470,.470]			; N+	20 keV
	eff__stop_en_an_ma[2,*,3]=[.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7]			; N+	25 keV, count rate too low

	eff__stop_en_an_ma[0,*,4]=[.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7]			; N2+	16 keV, beam fluctuations
	eff__stop_en_an_ma[1,*,4]=[.494,.494,.507,.507,.498,.498,.517,.517,.546,.546,.380,.380,.517,.517,.526,.526]			; N2+	20 keV

	eff__stop_en_an_ma[0,*,5]=[.274,.274,.317,.317,.317,.317,.353,.353,.334,.334,.155,.155,.305,.305,.322,.322]			; CO2+	17 keV
	eff__stop_en_an_ma[1,*,5]=[.350,.350,.375,.375,.375,.375,.395,.395,.405,.405,.250,.250,.365,.365,.375,.375]			; CO2+	20 keV



;	eff_start_en_an_ma[0,*,4]=[.786,.786,.786,.786,.801,.801,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7]			; N2+	16 keV, beam fluctuations
;	eff__stop_en_an_ma[0,*,4]=[.412,.412,.455,.455,.451,.451,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7]			; N2+	16 keV, beam fluctuations

;	eff_start_en_an_ma[2,*,3]=[.838,.838,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7]			; N+	25 keV, count rate too low
;	eff__stop_en_an_ma[2,*,3]=[.459,.459,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7,.7]			; N+	25 keV, count rate too low


; relative efficiencies for H2+ suggest that the open area of foil grid is ~0.67-0.70, eff for H2+ = 0.55 for each H at 20 keV
;	0.80 = 1 - (1 - .55)^2
;	0.62 = 1 - (1 - .55*.70)^2
;	0.60 = 1 - (1 - .55*.67)^2
;	0.60 = 1 - (1 - .55*.67)^2


	n_eff_cals = 10
	ef_time_boundary=dblarr(n_eff_cals)
	ef_time_boundary(0)   = time_double('2001-01-01')
	ef_time_boundary(1)   = time_double('2013-11-01')
	ef_time_boundary(2:n_eff_cals-1) = time_double('2020-11-01')

	ef1 = fltarr(16,n_eff_cals)						; start tof efficiency versus anode & time, Rate(TimeA and TimeB)/Rate(TimeRST)
	ef2 = fltarr(16,n_eff_cals)						; stop  tof efficiency versus anode & time, Rate(TimeC and TimeD)/Rate(TimeRST)
	ef3 = fltarr(64,n_eff_cals)						; start mass dependent efficiency of foils, assume this is independent of foil  *may not be needed
	ef4 = fltarr(64,n_eff_cals)						; stop  mass dependent efficiency of foils, assume this is independent of foil, *may not be needed
	ef5 = fltarr(64,n_eff_cals)						; start energy dependent efficiency of foils, assume this is independent of foil
	ef6 = fltarr(64,n_eff_cals)						; stop  energy dependent efficiency of foils, assume this is independent of foil

;	for ief1_def = replicate(1.,16

; Independent response arrays

	ano = fltarr(16) & for i=0,15 do ano = (i-7)*22.5		; anode angles

; RateID to rate table map

	rt2rate = [1.,1.,1.5,2.,3.25,4.0,4.5]

; md2swp is obsolete
; ModeID to Sweep table map
;	??? this might need modification because we don't encode sweep waveform directly in headers
;	??? we may need to decode housekeeping config bytes to get this right

	md2swp = intarr(128)
	md2swp[0:4]  =[0,1,2,3,4]					; ATLO      modes
	md2swp[16:20]=[0,5,6,3,4]					; x1    LEO modes
	md2swp[32:36]=[0,5,6,3,4]					; x1.5  LEO modes
	md2swp[48:52]=[0,5,6,3,4]					; x2    LEO modes
	md2swp[64:68]=[0,5,6,3,4]					; x3.25 LEO modes
	md2swp[80:84]=[0,5,6,3,4]					; x4.5  LEO modes

; The following will replace the ModeID to Sweep table map
;    conf2swp[config4,md2], where md2 is the lower nibble of the header mode, and config4 is from housekeeping
	conf2swp = intarr(512,16)							; may need 512 to grow if config4 upper byte is more than 1
	conf2swp[0,0:4]=[0,1,2,3,4]							; predelivery values
	conf2swp[17,0:4]=[0,1,2,3,4]							; LEO to MOI values
	if first_t gt time_double('2014-03-10/0') then conf2swp[17,0:4]=[5,5,6,3,4]	; Cruciform values loaded
	conf2swp[1,0:4]=[5,5,6,7,8]							; MOI      eprom load 1		- 20141006
	conf2swp[2,0:6]=[9,9,10,11,12,13,14]						; Protect  eprom load 2		- 20141127
	conf2swp[3,0:6]=[15,15,16,17,18,19,20]						; Deep dip eprom load 3		- 20150124
	conf2swp[4,0:6]=[21,21,22,23,24,25,26]						; Deep dip eprom load 4		- 20150624
; The following was added for CO2 mode with a SLUT load directly to STATIC, and a Config4 low byte increment to 1 (low and high bytes reversed in housekeeping)
	conf2swp[260,0:7]=[21,21,22,23,24,25,26,27]					; CO2 mode 20180413, config4=260
; The following was added to solidify CO2 mode in eprom load 5
	conf2swp[5,0:7]=[21,21,22,23,24,25,26,27]					; eprom load 5	 20180828

; SLUT parameters for each STATIC energy sweep table
; Note - Slut parameters must be corrected to actual calibration sweep & deflection values with "scale" and "def_scale"
; Note - be sure to put the gridon at an energy step divisible by 4 so that attenuator shifts do not happen within averaged energy steps
; Note - sweep table number is determined from the mode number (ram-1, conic-2, etc) and the config4 byte in the header
; Note - eprom config4 byte is set in RTS_STASTART RTS - cmd.PFP_LOADTABLE(21, 51, 0x03) for config4=3
; Note - adding/changing sweeps should be accompanied a change in the EEPROM config4 byte
; Note - when sweeps are changed/added, "conf2swp,conf2mlut,swp2gfan,swp2gfdf" must be modified in this program
; Note - new MLUT tables might also be needed when sweeps are changed -- determined by "conf2mlut"

	n_swp = 28
	slut = fltarr(n_swp,7)
;	slut[iswp,*]	  Estart,	 Estop,	defmax,	defctr,	gridon,	gridscale,	maxgrid		; mode name
; LEO modes
	slut[0,*] = 	[   50.0,	0.7040,	45.0,	0.,	10.0,	2.0,		25.]		; startup
	slut[1,*] = 	[   50.0,	0.7040,	45.0,	0.,	10.0,	2.0,		25.]		; ram 
	slut[2,*] = 	[  500.0,	1.2340,	45.0,	0.,	 0.0,	2.0,		25.]		; conic 
	slut[3,*] = 	[30000.0,	2.6080,	45.0,	0.,	 0.0,	2.0,		25.]		; pickup 
	slut[4,*] = 	[30000.0,	2.6080,	 0.0,	0.,	 0.0,	2.0,		25.]		; scan
; Cruciform modes 
	slut[5,*] = 	[   50.0,	0.1000,	22.5,	0.,	11.0,	2.0,		25.]		; ram0			loaded before cruciform scan on 2014-03-19
	slut[6,*] = 	[  500.0,	0.1000,	45.0,	0.,	12.0,	2.0,		25.]		; conic0		
; MOI modes loaded 2014-10-06 - gridon minimum is 0V
	slut[7,*] = 	[30000.0,	8.0000,	45.0,	0.,	 0.0,	2.0,		25.]		; pickup1		loaded before Mars Turn-on 2014-10-06
	slut[8,*] = 	[30000.0,	8.0000,	 0.0,	0.,	 0.0,	2.0,		25.]		; scan1			
; Science modes loaded 2014-11-27 - gridon minimum is 2V
	slut[9,*] = 	[   50.0,	0.1000,	22.5,	0.,	24.0,	4.0,		25.]		; ram2			loaded 2014-11-27 - protects static from s/c charging
	slut[10,*] = 	[  500.0,	0.1000,	45.0,	0.,	21.0,	4.0,		25.]		; conic2		
	slut[11,*] = 	[30000.0,	1.0000,	45.0,	0.,	24.0,	4.0,		25.]		; pickup2		
	slut[12,*] = 	[30000.0,	1.0000,	 0.0,	0.,	24.0,	4.0,		25.]		; scan2			
	slut[13,*] = 	[30000.0,	1.0000,	45.0,	0.,	24.0,	4.0,		25.]		; eclip2		
	slut[14,*] = 	[30000.0,	25.000,	45.0,	0.,	 0.0,	2.0,		25.]		; protect2		
; Science modes loaded 2015-01-24 - gridon minimum is 4V
	slut[15,*] = 	[   50.0,	0.1000,	22.5,	0.,	24.0,	4.0,		25.]		; ram3			this should be changed to gridon=11 in the next iteration - better attenuator boundary, protects handles sc charging
	slut[16,*] = 	[  500.0,	0.1000,	45.0,	0.,	21.0,	4.0,		25.]		; conic3		this should be changed to gridon=12 in the next iteration - better attenuator boundary, protects handles sc charging
	slut[17,*] = 	[30000.0,	0.2000,	45.0,	0.,	24.0,	4.0,		25.]		; pickup3		this should be changed to gridon=17 in the next iteration - better attenuator boundary, protects handles sc charging
	slut[18,*] = 	[30000.0,	0.2000,	 0.0,	0.,	24.0,	4.0,		25.]		; scan3			
	slut[19,*] = 	[30000.0,	0.2000,	45.0,	0.,	24.0,	4.0,		25.]		; eclip3		
	slut[20,*] = 	[30000.0,	25.000,	45.0,	0.,	 0.0,	2.0,		25.]		; protect3		
; Science modes - loaded 2015-06-24 - gridon terminated at 12-13 eV
	slut[21,*] = 	[   50.0,	0.1500,	22.5,	0.,	12.5,	5.0,		25.]		; ram4			eprom 4
	slut[22,*] = 	[  500.0,	0.3000,	45.0,	0.,	12.8,	5.0,		25.]		; conic4		grid scale changed to 5 so attE works for deep dips
	slut[23,*] = 	[30000.0,	0.3500,	45.0,	0.,	12.8,	5.0,		25.]		; pickup4		atten disabled, gridon decreased to avoid ionization of neutrals between grids during deep dip
	slut[24,*] = 	[30000.0,	0.3500,	45.0,	0.,	12.8,	5.0,		25.]		; scan4			atten enabled, same as pickup but with high data rate
	slut[25,*] = 	[30000.0,	0.3500,	45.0,	0.,	12.8,	5.0,		25.]		; eclip4		atten enabled, same as pickup otherwise
	slut[26,*] = 	[30000.0,	25.000,	45.0,	0.,	 0.0,	2.0,		25.]		; protect4		
; CO2 mode added 
	slut[27,*] = 	[   10.0,	 1.000,	22.5,	0.,	 12.0,	5.0,		25.]		; protect4		

; iswp to MLUT map	
	swp2mlut = [0,0,0,3,3,1,1,4,4,1,1,5,5,5,6,1,1,7,7,7,6,1,1,8,8,8,6,1]				; MLUT table associated with each SLUT sweep table

; Assumptions about how to deal with mechanical attenuator for data products with no angular info 
; iswp to anode & def range for geometric factor considerations
;    these tables are needed to help approximate gf for omindirectional data - apid c0,c2,c4,c6
;    the assumption is that: ions are in anode 0 in ram mode, ions are in anodes 6-8 in conic mode, ions are uniformly distributed over anodes 0-15 in other modes 
;    these assumptions are adequate to meet required uncertainties of 25% and the code does not require multiple apids for decommutation
;    a more accurate GF estimate could be made by using apid CA to determine the anode distribution of counts -- at some future date if needed
;    a problem with this method is dealing with the non-uniform mechanical attenuator.
;    a better approach might be to have a mechanical attenuator dependence in this table - swp2gfan[nswp,2,4], swp2gfdf[nswp,2,4]
;    right now, the case of mechanical attenuator closed in pickup mode (and protect,eclipse,etc) is handled in the apid sections by a factor of 50 division 

	swp2gfan = intarr(n_swp,2)									; For data averaged over anode, swp2gfan gives the assumed anode range for most counts 
	swp2gfdf = intarr(n_swp,2)									; For data averaged over def step, swp2gfdf gives the assumed def range for most counts 
	swp2gfan[*,0] = [7,7,6, 0, 0,7,6, 0, 0,7,6, 0, 0, 0, 0,7,6, 0, 0, 0, 0,7,6, 0, 0, 0, 0,7]	;   Used for APIDs with anode compressed data
	swp2gfan[*,1] = [7,7,8,15,15,7,8,15,15,7,8,15,15,15,15,7,8,15,15,15,15,7,8,15,15,15,15,7]	;   RAM mode counts assumed to land in anode 7, CONIC mode counts assumed to land in anodes 6 to 8

	swp2gfdf[*,0] = [7,7, 5, 0, 0,7, 5, 0, 0,7, 5, 0, 0, 0, 0,7, 5, 0, 0, 0, 0,7, 5, 0, 0, 0, 0,7]	;   Used for APIDs with deflector compressed data, determines which sweeps should assume inclusion of large def angles where gf response rolls off
	swp2gfdf[*,1] = [8,8,10,15,15,8,10,15,15,8,10,15,15,15,15,8,10,15,15,15,15,8,10,15,15,15,15,8]	;   RAM mode counts assumed to land in def 7-8, CONIC mode counts assumed to land in def 5-10

	def_volt_max = 4000.										; max deflector voltage, high energy steps have limited deflection range

; this is for testing only
if keyword_set(gf_nor) then begin
	swp2gfan[*,0] = 0										;	
	swp2gfan[*,1] = 15								;	
	swp2gfdf[*,0] = 0									;	
	swp2gfdf[*,1] = 15
endif								;	

; MLUT parameters for each STATIC mode
;	mlut = fltarr(n_swp,64,256) 
;	for j=0,n_swp-1 do mlut[j,*,*] = replicate(1.,64)#reform(replicate(1.,4)#findgen(64),256)			; default MLUT
; 
;	need to include the mlut for pickup mode

; Organize calibration arrays as [mode,energy,def,anode,mass,time] - time is needed for time dependent efficiencies

;   The following will require an inflight calibration for tuning to exact values
;	mec = [1.00,1.00,1.00,0.30,.040,.010,.010,.010,.010,.010,.020,0.10,1.00,1.00,1.00,1.00]			; ground calibration approximate value of mec = mgf*bgf
	attM = 0.01												; inflight calibration - first approximation
	attM = 0.013												; inflight calibration - 20160112 based on 20151126

	agf = [1.00,1.00,1.00,1.00,1.00,1.00,1.00,1.00,1.00,1.00,1.00,1.00,1.00,1.00,1.00,1.00]			; anode dependent gf - grid attenuation, active foil area

; ground calibration based on this file
; pathname = '' & append_array, pathname, 'maven/prelaunch/sta/prelaunch/20130717_223852_fm_cal3_15kV_2keV_swp_0yaw_rot_n169to191/commonBlock_20130717_223852_.dat'	
;	agf = [0.71,0.73,0.79,0.77,0.87,0.96,0.90,0.83,0.98,1.00,0.84,0.84,1.08,0.79,0.72,0.71]			; anode dependent gf - grid attenuation, active foil area


	mgf = [1.00,1.00,1.00,0.30,.050,attM,attM,attM,attM,attM,.050,0.30,1.00,1.00,1.00,1.00]			; mech gf attenuator variation with anode
	bgf = [1.00,1.00,1.00,1.00,1.00,1.00,1.00,1.00,1.00,1.00,.775,.325,.775,1.00,1.00,1.00]			; blocked anode 11 response
	egf = [1.00,1.00,1.00,1.00,1.00,1.00,1.00,1.00,1.00,1.00,1.00,1.00,1.00,1.00,1.00,1.00]*e_att		; electrostatic gf attenuation, e_att ~ 0.1

	gf_an_on =  reform(agf#[1,1,1,1] * (bgf#[1,0,1,0]+egf#[0,1,0,1]) * (replicate(1.,16)#[1,1,0,0]+mgf#[0,0,1,1]),16*4)	; electrostatic attenuator on
	gf_an_off = reform(agf#[1,1,1,1] * (bgf#[1,1,1,1])               * (replicate(1.,16)#[1,1,0,0]+mgf#[0,0,1,1]),16*4)	; electrostatic attenuator off

;	this correction factor is used to compensate for attM closed conditions for apid c6,c0,c2,c4,c8 (which have no anode info)  
;		the correction is only applied during pickup/eclipse/protect modes - these modes have swp2gfan[?,0:1]=[0,15] which assumes the flux is isotropic 
;		however, for att=2 or att=3 conditions, we instead assume the flux is attenuated by the mechanical attenuator
;		att_corr reduces the gf in apid c6,c0,c2,c4,c8 when att=2 or att=3 (ie when the mechanical attenuator is engaged)
	att_corr = total(mgf[5:9])/5./(total(mgf)/16.)


; Generate the energy, deflector, attenuation arrays

	nrg   	 = fltarr(n_swp,64)					; energy sweep table, determined from SLUTs
	dnrg 	 = fltarr(n_swp,64)					; denergy sweep table, determined from SLUTs
	def      = fltarr(n_swp,64,16)					; deflector values, determined from SLUTs
	gf_df    = fltarr(n_swp,64,16)					; geometric factor as a function of sweep (n_swp) and energy (64) step and deflection (16) step, calculated from def2gf
	gf_df1   = fltarr(n_swp,64,16)					; geometric factor as a function of sweep (n_swp) and energy (64) step and deflection (16) step, calculated from def2gf
	gf_df2   = fltarr(n_swp,64,16,16,4)				; needed to handle mech attenuator impact on deflector collimation - trajectories don't hit deflectors when mech attenuator is On
	grid_on  = fltarr(n_swp,64,16)					; energy dependent geometric factor correction for grid on, depends on slut and sweep
	grid_off = fltarr(n_swp,64,16)					; energy dependent geometric factor correction for grid off, depends on slut and sweep
	gf_en    = fltarr(n_swp,64,16)					; gf_en contains the energy dependence of gf on leakage fields through ESA exit grids
	gf_an 	 = fltarr(n_swp,64,16,16,4)				; gf with [iswp,energy,def,anode,att] dependence - derived from grid_on, gf_an_on, grid_off, gf_an_off
	gf    	 = fltarr(n_swp,64,16,16,4)				; total mechanical geometric factor depending on [mode,energy,def,anode,att] - derived from gf_en, gf_an

	for iswp=0,n_swp-1 do begin

	   ; energy array
		aa = (slut[iswp,0]/slut[iswp,1])^(1./63) 
		nrg[iswp,*] = scale*slut[iswp,0]/aa^findgen(64) 
		dnrg[iswp,1:62] = (nrg[iswp,0:61]-nrg[iswp,2:63])/2.
		dnrg[iswp,0]=dnrg[iswp,1] & dnrg[iswp,63]=dnrg[iswp,62]

	   ; deflector array  - the negative sign reflects direction of deflection
	   ;			the first term is the scale that reflects limited deflection at high energy
	   ; 			def_scale (43./45.)was determined from ground calibrations.

		def[iswp,*,*] = -1.* reform( (nrg_const*def_volt_max*45./(def_const*nrg[iswp,*]/scale*slut[iswp,2]) < 1.) ,64) # (def_scale*slut[iswp,2]*(findgen(16)-7.5)/7.5)		; this may need a sign change depending upon coordinate transformations

; 	   gf_df is the def-energy dependent attenuation factor 
; old		gf_df[iswp,*,*]  =  def2gf[round(abs(def[iswp,*,*]))<45] * def2gf1[round(abs(def[iswp,*,*]))<45]	; old version assumed symmetric deflection collimation
		gf_df[iswp,*,*]  =  def2gf[0>round(def[iswp,*,*]+45)<90] * def2gf1[round(abs(def[iswp,*,*]))<45]	; new version allows for variation in collimation with deflection direction
		gf_df1[iswp,*,*] =  def2gf1[round(abs(def[iswp,*,*]))<45] 						; gf_df1 is for attenuator closed

	   ; att grid energy dependence
		if slut[iswp,4] eq 0. then begin
			grid_off[iswp,*,*] = 1.
		endif else begin
			minval = min(abs(slut[iswp,4]-nrg[iswp,*]),ind)
			if nrg[iswp,ind] gt slut[iswp,4] then ind=(ind+1)<63
			grid_on[iswp,ind:63,*] = 1.
			if ind ge 1 then grid_off[iswp,0:(ind-1),*] = 1.
		endelse	

	   ; gf_an with [iswp,energy,def,anode,att] dependence	
		gf_an = reform(reform(grid_on,n_swp*64*16)#gf_an_on + reform(grid_off,n_swp*64*16)#gf_an_off,n_swp,64,16,16,4)	

	   ; gf_en contains the energy dependence of gf on leakage fields through ESA exit grids
  		ecl = 1. 	& ech=30.  	& exit1=   (1.+.121*(1.-(alog(nrg[iswp,*]/ecl>1.)/alog(ech/ecl)<1.)))	;due to ESA exit grid, needs tuning 
  		ecl = 10. 	& ech=300. 	& exit2=   (1.+.121*(1.-(alog(nrg[iswp,*]/ecl>1.)/alog(ech/ecl)<1.)))	;due to ESA exit grid, needs tuning
		gf_en[iswp,*,*] = reform(exit1*exit2)#replicate(1.,16)						

	endfor


;   gf_df2 handles modification for mechanical attenuator state
;   gf_df1 is used to remove the collimation caused by deflectors when the attenuator is closed on anodes 5:10
	gf_df2[*,*,*,*,0] =  reform(gf_df, n_swp*64l*16)#replicate(1.,16)
	gf_df2[*,*,*,*,1] =  reform(gf_df, n_swp*64l*16)#replicate(1.,16)
	gf_df2[*,*,*,*,2] =  reform(gf_df, n_swp*64l*16)#replicate(1.,16)
	gf_df2[*,*,*,*,3] =  reform(gf_df, n_swp*64l*16)#replicate(1.,16)
	gf_df2[*,*,*,5:10,2] =  reform(gf_df1, n_swp*64l*16)#replicate(1.,6)
	gf_df2[*,*,*,5:10,3] =  reform(gf_df1, n_swp*64l*16)#replicate(1.,6)


; old	gf_df2 =  reform(reform(gf_df,n_swp*64l*16)#replicate(1.,16*4),n_swp,64l,16,16,4)
; old	gf_df2[*,*,*,*,2:3] = 1.							; no deflector attenuation when the mechanical attenuator is in

;	gf[n_swp,64,16,16,4]
; old	gf =    reform(reform(reform(gf_en*gf_df,n_swp*64l*16)#replicate(1.,16*4),n_swp*64l*16*16*4l) * reform(gf_an,n_swp*64l*16*16*4l),n_swp,64,16,16,4) 
	gf =    reform(reform(reform(gf_en,n_swp*64l*16)#replicate(1.,16*4),n_swp*64l*16*16*4l) * reform(gf_an*gf_df2,n_swp*64l*16*16*4l),n_swp,64,16,16,4) 

if 0 then begin
print,reform(def[3,0,*])								 
print,reform(def[3,20,*])								 
print,reform(def[3,60,*])								 

print,reform(gf_df[3,0,*])								 
print,reform(gf_df[3,20,*])								 
print,reform(gf_df[3,60,*])								 
endif






if 0 then begin
; old dna


;	ggf = fltarr(n_swp,64,16) 				; electrostatic grid gf attenuation vs energy, determined from SLUTs
;	dgf = fltarr(n_swp,16) 					; def gf attenuation vs deflection, determined from SLUTs
;	agf = fltarr(n_swp,64,16,16,64)				; total gf as a function of (energy,def,anode,mass)

;	tof=fltarr(n_swp,64)						; tof in ns for product bins (determined from MLUTs, assumes MLUT accounts for changes in tof due to initial energy)
;	mss=fltarr(n_swp,64)						; mass based on TOF assuming no energy straggling
;	dms=fltarr(n_swp,64)						; accounts for variable TOF mass bin range (determined from MLUTs)
;	ms2=fltarr(n_swp,16,64)					; could be used to account for variations in foil thickness to correct mass

; TOF arrays
; 	15keV H+ takes 11.79 ns for 2 cm
;	TOFs (TDC1,TDC2) are converted from 1024 TOF bins to 256 mass bins with a pseudo log compression - see FPGA spec
;		Formula: 0-255 -> 0-127, 256-511 -> 128-191, 512-1024 -> 192-255  
;		highest resolution mass bins average 2 bins, introduces factor 1/2
; 		Typical product mass compression (256->64) introduces factor 1/4 
	dt = 11.79*b_ns/4./2.						; TOF in bins for 15keV proton					

	tof=fltarr(n_swp,64,64)						; tof
	mas=fltarr(n_swp,64,64)						; mass based on TOF assuming no energy straggling
	dm=fltarr(n_swp,64,64)						; accounts for variable TOF mass bin range 
; 		tof_def:  256 bins summed -> 64 bins
;		tof_def = findgen(64) & tof_def(32:47)=32.+2.*findgen(16) & tof_def(48:63)=64.+4*findgen(16) 
;	tof_def = findgen(64) & tof_def(32:47)=32.+2.*findgen(16) & tof_def(48:63)=64.+4*findgen(16) 

endif


;*************************************************************************************************************
;*************************************************************************************************************
;*************************************************************************************************************
; MLUTs allow energy dependent mapping of TOF to mass product bin so that averaging over energy does not mix masses
; Onboard hardware pseudo-log maps TOF bin (0-1023) to MLUT bin (0-255)- see below: m2tofavg,m2tofmin,m2tofmax 
; MLUT tables produce MLUT bin (0-255) to mass product bin (0-63) compression, at each of 64 energy steps 
; For low energy sweeps, we don't need and energy dependent tables and two 256-byte onboard tables can be stored onboard
;	There were two 256 byte tables created prior to L&EO - MLUT0,MLUT1 - and both were stored onboard
;	MLUT0 is a linear divide by 4 table, 256->64 and was used for RAM/CONIC modes prior to L&EO
;	MLUT1 is identical to the lowest energy row of MLUT2/MLUT3 
;		MLUT1 preserves mass boundaries for products whose mass dimension is reduced by averaging
;	MLUT1 will be used for RAM and CONIC modes assuming their highest energy steps remain below 1 keV
; For energetic sweeps, energy dependent tables are needed (256,64) and two tables can be stored onboard
;	There were two 256x64 byte tables created prior to L&EO - MLUT2,MLUT3 
;	Prior to L&EO, only MLUT2 was stored. Early operations replace MLUT2 with MLUT3. They are almost identical.
;	MLUT3 will be used for PICKUP and SCAN modes which have 2-30000 eV sweeps
;	The extra onboard slot for a 256x64 table will be reserved for any new mode with intermediate sweep.
; Legend
;	m2tof*  	256 -> 1024 mappings
;	mind2tof*	64  -> 1024 mappings, average TOF value
;	mind2twt*	how many TOF(0-1023) bins went into each mass bin - to be used for weighted averaging

; Prior to L&EO there are 4 MLUTs, for MOI there were 5 MLUTs 

	n_mlut = 9							; number of MLUT tables used

; The following replaces the md2mlut map -- assumes we never have more than 255 eprom changes
;    conf2mlut[config4,md2], where md2 is the lower nibble of the header mode, and config4 is from housekeeping
	conf2mlut = intarr(256,16)
	conf2mlut[0,0:4]=[0,0,0,2,2]								; pre-delivery
	conf2mlut[17,0:4]=[0,0,0,2,2]								; LEO
	if first_t gt time_double('2014-03-10/0') then conf2mlut[17,0:4]=[1,1,1,3,3]		; Cruciform
	conf2mlut[1,0:4]=[1,1,1,4,4]								; MOI
	conf2mlut[2,0:6]=[1,1,1,5,5,5,6]							; Protect modes after s/c charging problems
	conf2mlut[3,0:6]=[1,1,1,7,7,7,6]							; Protect modes after s/c charging problems
	conf2mlut[4,0:6]=[1,1,1,7,7,7,6]							; Protect modes after s/c charging problems

; Obsolete: Create ModeID to MLUT table map - this tells what MLUT table is used for each mode
; 	ModeID = 8*rate+mode
;	mode=0to7(STARTUP,RAM,CONIC,PICKUP,SCAN,etc)
;	rate=0to15(ATLO,x1,x1.5,x2.0,x3.25,x4.0,x4.5,etc.)
	md2mlut = indgen(128)
	md2mlut[0:4]  =[0,0,0,2,2]					; ATLO      modes
	md2mlut[16:20]=[1,1,1,3,3]					; x1    LEO modes
	md2mlut[32:36]=[1,1,1,3,3]					; x1.5  LEO modes
	md2mlut[48:52]=[1,1,1,3,3]					; x2    LEO modes
	md2mlut[64:68]=[1,1,1,3,3]					; x3.25 LEO modes
	md2mlut[80:84]=[1,1,1,3,3]					; x4.0  LEO modes
	md2mlut[96:100]=[1,1,1,3,3]					; x4.5  LEO modes


; Read in MLUT tables and calculate m2tof mapping tables 
; Create mapping from MLUT 256 -> TOF 1024 to unmap the onboard hardware compression

	m2tofavg=fltarr(256)
	m2tofavg[0:127]   =      total(reform(findgen(256),2,128),1)/2. 
	m2tofavg[128:191] = 256.+total(reform(findgen(256),4,64),1)/4.  
	m2tofavg[192:255] = 512.+total(reform(findgen(512),8,64),1)/8.  

	m2tofmin=fltarr(256)
	m2tofmin[0:127]   =       2.*findgen(128) 
	m2tofmin[128:191] = 256.+ 4.*findgen(64) 
	m2tofmin[192:255] = 512.+ 8.*findgen(64)  

	m2tofmax=fltarr(256)
	m2tofmax[0:127]   =       2.*findgen(128)+1. 
	m2tofmax[128:191] = 256.+ 4.*findgen(64) +3. 
	m2tofmax[192:255] = 512.+ 8.*findgen(64) +7. 

;*******************************************************************************************
; MLUT table are extracted from /GSEOS/Instruments/STA/Python/scripts/flight-lut	
;*******************************************************************************************

; Get the MLUT path 
;	mluts are stored in /mvn_sta_tables/, a subdirectory of the directory where mvn_sta_prod_cal.pro is stored

	stack = scope_traceback(/structure)
	filename = stack[scope_level()-1].filename
	mlut_path = file_dirname(filename)+'/mvn_sta_tables/'

	print,'Reading MLUTs from path: ',mlut_path

;*******************************************************************************************

;    MLUT0(256,1) - linear divide by map 256->64 eV Sweep

	close,1
	openr,1,mlut_path+'mav_sta_mlut0.lut'
	na=136 & aa=strarr(na)
	readf,1,aa
;	for i=0,na-1 do print,aa[i]
	tmp0 = strmid(aa[na-128:na-1],2,2)
	tmp1 = strmid(aa[na-128:na-1],4,2)
; reverse byte order of the commands
;	mlut=reform(transpose([[tmp0],[tmp1]]),256)
	mlut=reform(transpose([[tmp1],[tmp0]]),256)
	mlut0=intarr(256)
	reads,mlut,mlut0,format='(Z)'
;	print,mlut0
	close,1


	mind2tof0 = fltarr(64)
	mind2twt0=intarr(64)
	for i=0,63 do begin
		ind = where(i eq mlut0,nind)
		if nind ge 1 then begin
			mind2tof0[i] = (m2tofmax[max(ind)] + m2tofmin[min(ind)])/2. 
			mind2twt0[i] = (1 + m2tofmax[max(ind)] - m2tofmin[min(ind)])
			if mind2twt0[i] le 0 then print,'Error in MLUT0',i
		endif else print,'Error in MLUT0'
	endfor

;	print,mind2tof0
;	print,mind2twt0
	mlut0=mlut0#replicate(1.,64)						; (ma,en)
	mind2tof0 = replicate(1.,64)#mind2tof0					; (en,ma)
	mind2twt0 = replicate(1.,64)#mind2twt0					; (en,ma)

;**********************************************
;    MLUT1(256,1) replicate lowest energy row of MLUT2, MLUT2(256,64) 2-30 for slut(3,*) 30000.0-2.6080 eV Sweep

	close,1
	openr,1,mlut_path+'mav_sta_mlut1.lut'
	na=135 & aa=strarr(na)
	readf,1,aa
;	for i=0,na-1 do print,aa[i]
	tmp0 = strmid(aa[na-128:na-1],2,2)
	tmp1 = strmid(aa[na-128:na-1],4,2)
; reverse byte order of the commands
;	mlut=reform(transpose([[tmp0],[tmp1]]),256)
	mlut=reform(transpose([[tmp1],[tmp0]]),256)
	mlut1=intarr(256)
	reads,mlut,mlut1,format='(Z)'
;	print,mlut1
	close,1


	mind2tof1 = fltarr(64)
	mind2twt1=intarr(64)
	for i=0,63 do begin
		ind = where(i eq mlut1,nind)
		if nind ge 1 then begin
			mind2tof1[i] = (m2tofmax[max(ind)] + m2tofmin[min(ind)])/2. 
			mind2twt1[i] = (1 + m2tofmax[max(ind)] - m2tofmin[min(ind)])
			if mind2twt1[i] le 0 then print,'Error in MLUT1',i
		endif else print,'Error in MLUT1'
	endfor

;	print,mind2tof1
;	print,mind2twt1
	mlut1=mlut1#replicate(1.,64)						; (ma,en)
	mind2tof1 = replicate(1.,64)#mind2tof1					; (en,ma)
	mind2twt1 = replicate(1.,64)#mind2twt1					; (en,ma)


;**********************************************
;    MLUT2(256,64) for SLUT2 (see slut(3,*) 30000.0-2.6080 eV Sweep), w/ -22 TDC offset, assumes energy lost in foil is (500.+M*1000./8.)eV (mlutmath.py)

	close,1
	openr,1,mlut_path+'mav_sta_mlut2.lut'
;	na=5+64*128l & aa=strarr(na)						; old file format nna=5
	nna=22									; offset for text at beginning of file
	na=nna+64*128l & aa=strarr(na)
	readf,1,aa
	tmp0 = strmid(aa[nna:na-1],2,2)
	tmp1 = strmid(aa[nna:na-1],4,2)
; reverse byte order of the commands
;	mlut=reform(transpose([[tmp0],[tmp1]]),256*64l)
	mlut=reform(transpose([[tmp1],[tmp0]]),256*64l)
	mlut2=intarr(256*64l)
	reads,mlut,mlut2,format='(Z)'
	mlut2=reform(mlut2,256,64)						; (ma,en)
;	print,mlut2
	close,1


	mind2tof2 = fltarr(64,64)
	mind2twt2=intarr(64,64)
	for j=0,63 do begin
		for i=0,63 do begin
			ind = where(i eq mlut2[*,j],nind)
			if nind ge 1 then begin
				mind2tof2[j,i] = (m2tofmax[max(ind)] + m2tofmin[min(ind)])/2. 		; (en,ma)
				mind2twt2[j,i] = (1 + m2tofmax[max(ind)] - m2tofmin[min(ind)])		; (en,ma)
				if mind2twt2[j,i] le 0 then print,'Error in MLUT2',i
			endif else print,'Error in MLUT2'
		endfor
	endfor

;	print,reform(mind2tof2[0,*])
;	print,reform(mind2tof2[63,*])
;	print,reform(mind2twt2[0,*])
;	print,reform(mind2twt2[63,*])

;**********************************************
;    MLUT3(256,64) for SLUT2 (see slut(3,*) 30000.0-2.6080 eV Sweep), w/ -16 TDC offset, assumes energy lost in foil is (500.+M*1000./8.)eV (mlutmath.py)

	close,1
	openr,1,mlut_path+'mav_sta_mlut3.lut'
;	na=3+64*128l & aa=strarr(na)						; old file format nna=3
	nna=22									; offset for text at beginning of file
	na=nna+64*128l & aa=strarr(na)
	readf,1,aa
	tmp0 = strmid(aa[nna:na-1],2,2)
	tmp1 = strmid(aa[nna:na-1],4,2)
; reverse byte order of the commands
;	mlut=reform(transpose([[tmp0],[tmp1]]),256*64l)
	mlut=reform(transpose([[tmp1],[tmp0]]),256*64l)
	mlut3=intarr(256*64l)
	reads,mlut,mlut3,format='(Z)'
	mlut3=reform(mlut3,256,64)					; (ma,en)
;	print,mlut3
	close,1


	mind2tof3 = fltarr(64,64)
	mind2twt3=intarr(64,64)
	for j=0,63 do begin
		for i=0,63 do begin
			ind = where(i eq mlut3[*,j],nind)
			if nind ge 1 then begin
				mind2tof3[j,i] = (m2tofmax[max(ind)] + m2tofmin[min(ind)])/2. 		; (en,ma)
				mind2twt3[j,i] = (1 + m2tofmax[max(ind)] - m2tofmin[min(ind)])		; (en,ma)
				if mind2twt3[j,i] le 0 then print,'Error in mlut3',i
			endif else print,'Error in mlut3'
		endfor
	endfor

;	print,reform(mind2tof3[0,*])
;	print,reform(mind2tof3[63,*])
;	print,reform(mind2twt3[0,*])
;	print,reform(mind2twt3[63,*])

;**********************************************
;    MLUT4(256,64) for SLUT3 (see slut(7,*) 30000.0-8.0 eV Sweep), w/ -16 TDC offset, assumes energy lost in foil is (500.+M*1000./8.)eV (mlutmath.py)

	close,1
	openr,1,mlut_path+'mav_sta_mlut4_8eV_30keV.lut'
	nna=22									; offset for text at beginning of file
	na=nna+64*128l & aa=strarr(na)
	readf,1,aa
	tmp0 = strmid(aa[nna:na-1],2,2)
	tmp1 = strmid(aa[nna:na-1],4,2)
; reverse byte order of the commands
;	mlut=reform(transpose([[tmp0],[tmp1]]),256*64l)
	mlut=reform(transpose([[tmp1],[tmp0]]),256*64l)
	mlut4=intarr(256*64l)
	reads,mlut,mlut4,format='(Z)'
	mlut4=reform(mlut4,256,64)					; (ma,en)
;	print,mlut4
	close,1


	mind2tof4 = fltarr(64,64)
	mind2twt4=intarr(64,64)
	for j=0,63 do begin
		for i=0,63 do begin
			ind = where(i eq mlut4[*,j],nind)
			if nind ge 1 then begin
				mind2tof4[j,i] = (m2tofmax[max(ind)] + m2tofmin[min(ind)])/2. 		; (en,ma)
				mind2twt4[j,i] = (1 + m2tofmax[max(ind)] - m2tofmin[min(ind)])		; (en,ma)
				if mind2twt4[j,i] le 0 then print,'Error in mlut4',i
			endif else print,'Error in mlut4'
		endfor
	endfor

;	print,reform(mind2tof4[0,*])
;	print,reform(mind2tof4[63,*])
;	print,reform(mind2twt4[0,*])
;	print,reform(mind2twt4[63,*])

;**********************************************
;    MLUT5(256,64) for slut(11,*) 30000.0-1. eV Sweep), w/ -16 TDC offset, assumes energy lost in foil is (500.+M*1000./8.)eV (mlutmath.py)

	close,1
	openr,1,mlut_path+'mav_sta_mlut_1eV_30keV.lut'
	nna=22									; offset for text at beginning of file
	na=nna+64*128l & aa=strarr(na)
	readf,1,aa
	tmp0 = strmid(aa[nna:na-1],2,2)
	tmp1 = strmid(aa[nna:na-1],4,2)
; reverse byte order of the commands
;	mlut=reform(transpose([[tmp0],[tmp1]]),256*64l)
	mlut=reform(transpose([[tmp1],[tmp0]]),256*64l)
	mlut5=intarr(256*64l)
	reads,mlut,mlut5,format='(Z)'
	mlut5=reform(mlut5,256,64)					; (ma,en)
;	print,mlut5
	close,1


	mind2tof5 = fltarr(64,64)
	mind2twt5=intarr(64,64)
	for j=0,63 do begin
		for i=0,63 do begin
			ind = where(i eq mlut5[*,j],nind)
			if nind ge 1 then begin
				mind2tof5[j,i] = (m2tofmax[max(ind)] + m2tofmin[min(ind)])/2. 		; (en,ma)
				mind2twt5[j,i] = (1 + m2tofmax[max(ind)] - m2tofmin[min(ind)])		; (en,ma)
				if mind2twt5[j,i] le 0 then print,'Error in mlut5',i
			endif else print,'Error in mlut5'
		endfor
	endfor

;	print,reform(mind2tof5[0,*])
;	print,reform(mind2tof5[63,*])
;	print,reform(mind2twt5[0,*])
;	print,reform(mind2twt5[63,*])

;**********************************************
;    MLUT6(256,64) for slut(14,*) 30000.0-25 eV Sweep), w/ -16 TDC offset, assumes energy lost in foil is (500.+M*1000./8.)eV (mlutmath.py)

	close,1
	openr,1,mlut_path+'mav_sta_mlut_25eV_30keV.lut'
	nna=22									; offset for text at beginning of file
	na=nna+64*128l & aa=strarr(na)
	readf,1,aa
	tmp0 = strmid(aa[nna:na-1],2,2)
	tmp1 = strmid(aa[nna:na-1],4,2)
; reverse byte order of the commands
;	mlut=reform(transpose([[tmp0],[tmp1]]),256*64l)
	mlut=reform(transpose([[tmp1],[tmp0]]),256*64l)
	mlut6=intarr(256*64l)
	reads,mlut,mlut6,format='(Z)'
	mlut6=reform(mlut6,256,64)					; (ma,en)
;	print,mlut6
	close,1


	mind2tof6 = fltarr(64,64)
	mind2twt6=intarr(64,64)
	for j=0,63 do begin
		for i=0,63 do begin
			ind = where(i eq mlut6[*,j],nind)
			if nind ge 1 then begin
				mind2tof6[j,i] = (m2tofmax[max(ind)] + m2tofmin[min(ind)])/2. 		; (en,ma)
				mind2twt6[j,i] = (1 + m2tofmax[max(ind)] - m2tofmin[min(ind)])		; (en,ma)
				if mind2twt6[j,i] le 0 then print,'Error in mlut6',i
			endif else print,'Error in mlut6'
		endfor
	endfor

;	print,reform(mind2tof6[0,*])
;	print,reform(mind2tof6[63,*])
;	print,reform(mind2twt6[0,*])
;	print,reform(mind2twt6[63,*])

;**********************************************
;    MLUT7(256,64) for slut(17:19,*) 30000.0-0.2 eV Sweep), w/ -16 TDC offset, assumes energy lost in foil is (500.+M*1000./8.)eV (mlutmath.py)

	close,1
	openr,1,mlut_path+'mav_sta_mlut_0p2eV_30keV.lut'			; change name later
	nna=22									; offset for text at beginning of file
	na=nna+64*128l & aa=strarr(na)
	readf,1,aa
	tmp0 = strmid(aa[nna:na-1],2,2)
	tmp1 = strmid(aa[nna:na-1],4,2)
; reverse byte order of the commands
;	mlut=reform(transpose([[tmp0],[tmp1]]),256*64l)
	mlut=reform(transpose([[tmp1],[tmp0]]),256*64l)
	mlut7=intarr(256*64l)
	reads,mlut,mlut7,format='(Z)'
	mlut7=reform(mlut7,256,64)					; (ma,en)
;	print,mlut7
	close,1


	mind2tof7 = fltarr(64,64)
	mind2twt7=intarr(64,64)
	for j=0,63 do begin
		for i=0,63 do begin
			ind = where(i eq mlut7[*,j],nind)
			if nind ge 1 then begin
				mind2tof7[j,i] = (m2tofmax[max(ind)] + m2tofmin[min(ind)])/2. 		; (en,ma)
				mind2twt7[j,i] = (1 + m2tofmax[max(ind)] - m2tofmin[min(ind)])		; (en,ma)
				if mind2twt7[j,i] le 0 then print,'Error in mlut7',i
			endif else print,'Error in mlut7'
		endfor
	endfor

;	print,reform(mind2tof7[0,*])
;	print,reform(mind2tof7[63,*])
;	print,reform(mind2twt7[0,*])
;	print,reform(mind2twt7[63,*])

;**********************************************
;    MLUT8(256,64) for slut(23:25,*) 30000.0-0.35 eV Sweep), w/ -16 TDC offset, assumes energy lost in foil is (500.+M*1000./8.)eV (mlutmath.py)

	close,1
;	openr,1,mlut_path+'mav_sta_mlut_0p2eV_30keV.lut'
	openr,1,mlut_path+'mav_sta_mlut_0p35eV_30keV.lut'			; change name later
	nna=22									; offset for text at beginning of file
	na=nna+64*128l & aa=strarr(na)
	readf,1,aa
	tmp0 = strmid(aa[nna:na-1],2,2)
	tmp1 = strmid(aa[nna:na-1],4,2)
; reverse byte order of the commands
;	mlut=reform(transpose([[tmp0],[tmp1]]),256*64l)
	mlut=reform(transpose([[tmp1],[tmp0]]),256*64l)
	mlut8=intarr(256*64l)
	reads,mlut,mlut8,format='(Z)'
	mlut8=reform(mlut8,256,64)					; (ma,en)
;	print,mlut8
	close,1


	mind2tof8 = fltarr(64,64)
	mind2twt8=intarr(64,64)
	for j=0,63 do begin
		for i=0,63 do begin
			ind = where(i eq mlut8[*,j],nind)
			if nind ge 1 then begin
				mind2tof8[j,i] = (m2tofmax[max(ind)] + m2tofmin[min(ind)])/2. 		; (en,ma)
				mind2twt8[j,i] = (1 + m2tofmax[max(ind)] - m2tofmin[min(ind)])		; (en,ma)
				if mind2twt3[j,i] le 0 then print,'Error in mlut8',i
			endif else print,'Error in mlut8'
		endfor
	endfor

;	print,reform(mind2tof8[0,*])
;	print,reform(mind2tof8[63,*])
;	print,reform(mind2twt8[0,*])
;	print,reform(mind2twt8[63,*])

;**********************************************
; Load tof/mode twt/mode tables

	tof = fltarr(n_mlut,64,64)
	tof[0,*,*] = mind2tof0 	
	tof[1,*,*] = mind2tof1 	
	tof[2,*,*] = mind2tof2 	
	tof[3,*,*] = mind2tof3 	
	tof[4,*,*] = mind2tof4 	
	tof[5,*,*] = mind2tof5 	
	tof[6,*,*] = mind2tof6 	
	tof[7,*,*] = mind2tof7 	
	tof[8,*,*] = mind2tof8 	

	twt = fltarr(n_mlut,64,64)
	twt[0,*,*] = mind2twt0 	
	twt[1,*,*] = mind2twt1 	
	twt[2,*,*] = mind2twt2 	
	twt[3,*,*] = mind2twt3 	
	twt[4,*,*] = mind2twt4 	
	twt[5,*,*] = mind2twt5 	
	twt[6,*,*] = mind2twt6 	
	twt[7,*,*] = mind2twt7 	
	twt[8,*,*] = mind2twt8 	

; Generate tof/mass tables
;    Assume the foil mass loss is (500+M*1000/8) eV = 500+125*M
; Note - the tof_offset was determined by comparison of the measured proton peak to simulation.

	p_vel = 0.0438 					; 1000 eV proton velocity in cm/ns
	const = 2.*1000./(p_vel^2)			; unit conversion  2*energy/(mass-vel^2)
	const2 = (0.0438/1000.^.5)^2
	mas = fltarr(n_swp,64,64)
;	dm  = fltarr(n_swp,64,64)
	nrg2=reform(reform(nrg,(n_swp)*64)#replicate(1.,64),n_swp,64,64)
	for iswp=0,n_swp-1 do begin
;
;		original code
;		mas[iswp,*,*] = (acc+nrg2[iswp,*,*]-500.)/(1000./8.+.5*const*2.^2*b_ns^2/(tof_offset+tof[swp2mlut[iswp],*,*])^2)
;
;		the following explains the equivalent mass calculation based on tof array
;		M = const2 * E/v^2 = const2 * (acc+nrg-loss) / (2cm/(tof))^2  
;		loss = 500+M*125
;		M = const2 * (acc+nrg-500-M*125) / (2cm/(tof_offset+tof_bin)/b_ns)^2 
;		M = (A + B*M) * C --> M = A /(1/C - B)  --> A=(acc+nrg-500), B=-125., C=const2/(2cm/((tof_offset+tof_bin)/b_ns))^2
;		M = (acc+nrg-500.)/(2./(tof_offset+tof_bin)/b_ns)^2/const2 - 125.)
;
;		mas[iswp,*,*] = (acc+nrg2[iswp,*,*]-500.)/((2./((tof_offset+tof[swp2mlut[iswp],*,*])/b_ns))^2./const2 + 125.)
;		mas[iswp,*,*] = (acc+nrg2[iswp,*,*]-0.)/((2./((tof_offset+tof[swp2mlut[iswp],*,*])/b_ns))^2./const2 + 0.)

;		loss = 500 + ((M/16)^.5)*2400. = 500 + 600*M^.5
;		M = const2 * (acc+nrg-loss) / (2cm/(tof_offset+tof_bin)/b_ns)^2 
;		M = const2 * (acc+nrg-500-600*M^.5) / (2cm/(tof_offset+tof_bin)/b_ns)^2 
;		A = acc+nrg-500.
;		B = -600.
;		C = const2/(2cm/((tof_offset+tof_bin)/b_ns))^2
;		M = (A + B*M^.5) * C --> (M-AC)^2 = (BC)^2*M --> 0 = M^2 - (2AC + (BC)^2)M + (AC)^2
;		M = .5 *((2AC + (BC)^2) +/- ((2AC + (BC)^2)^2 - 4*(AC)^2)^.5) 
;		M = .5 *((2*A*C + (B*C)^2) +/- ((2*A*C + (B*C)^2)^2 - 4*(A*C)^2)^.5)

		A = acc+nrg2[iswp,*,*]-500.
		B = -450.
		C = const2/(2./((tof_offset+tof[swp2mlut[iswp],*,*])/b_ns))^2.
;		mas[iswp,*,*] =  .5 *((2*A*C + (B*C)^2) + ((2*A*C + (B*C)^2)^2 - 4*(A*C)^2)^.5)
		mas[iswp,*,*] =  .5 *((2*A*C + (B*C)^2) - ((2*A*C + (B*C)^2)^2 - 4*(A*C)^2)^.5)

	endfor	

;print,minmax(nrg2[3,*,*])
;print,acc
;print,minmax(tof)
;print,b_ns
;print,tof_offset
;print,reform(mas[0,0,*])
;print,reform(mas[1,0,*])
;print,reform(mas[2,0,*])
;print,reform(mas[3,0,*])
;print,reform(mas[3,63,*])
;print,reform(tof[3,0,*])
;print,reform(tof[3,63,*])







;check the bounaries

if keyword_set(test) then begin

print,reform(mas[3,0,*])
print,reform(mas[3,63,*])

window,0
plot,reform(mas[3,63,*]),xlog=1,ylog=1,xrange=[.1,100],yrange=[.1,100],psym=1,xstyle=1,ystyle=1,xtitle='Mass bin',ytitle='Mass, Energy = 0 keV',title='MLUT tables'
; for i=1,63 do oplot,reform(mas[3,i,*])
oplot,[7.5,7.5],[.1,100]
oplot,[15.5,15.5],[.1,100]
oplot,[23.5,23.5],[.1,100]
oplot,[32,32]-.5,[.1,100]
oplot,[40,40]-.5,[.1,100]
oplot,[48,48]-.5,[.1,100]
oplot,[56,56]-.5,[.1,100]
oplot,[.1,100],[1.5,1.5]
oplot,[.1,100],[3.,3.]
oplot,[.1,100],[6.,6.]
oplot,[.1,100],[12.,12.]
oplot,[.1,100],[24.,24.]
oplot,[.1,100],[38.,38.]
makepng,'MLUT_table_plot1'


window,2
plot,reform(tof[3,63,*]),xlog=1,ylog=1,xrange=[.1,100],yrange=[10,1000],psym=1,xstyle=1,ystyle=1,xtitle='Mass bin',ytitle='TOF bin',title='MLUT tables'
; for i=1,63 do oplot,reform(tof[3,i,*])
p_a=72
oplot,[7.5,7.5],[10,1000]
oplot,[15.5,15.5],[10,1000]
oplot,[23.5,23.5],[10,1000]
oplot,[32,32]-.5,[10,1000]
oplot,[40,40]-.5,[10,1000]
oplot,[48,48]-.5,[10,1000]
oplot,[.1,100],[1,1]*(p_a+tof_offset)*2.^0.-tof_offset
oplot,[.1,100],[1,1]*(p_a+tof_offset)*2.^.5-tof_offset
oplot,[.1,100],[1,1]*(p_a+tof_offset)*2.^1.-tof_offset
oplot,[.1,100],[1,1]*(p_a+tof_offset)*2.^1.5-tof_offset
oplot,[.1,100],[1,1]*(p_a+tof_offset)*2.^2.-tof_offset
oplot,[.1,100],[1,1]*(p_a+tof_offset)*2.^2.5-tof_offset
oplot,[.1,100],[1,1]*255,color=cols.red
oplot,[.1,100],[1,1]*375,color=cols.red
oplot,[.1,100],[1,1]*490,color=cols.red
makepng,'MLUT_table_plot2'


window,3 
plot,reform(mas[3,63,*]),xlog=1,ylog=1,xrange=[.1,100],yrange=[.1,100],psym=1,xstyle=1,ystyle=1,xtitle='Mass bin (1',ytitle='Mass, Energy = 0-30 keV',title='MLUT tables'
for i=1,63 do oplot,reform(mas[3,i,*])
oplot,[7.5,7.5],[.1,100]
oplot,[15.5,15.5],[.1,100]
oplot,[23.5,23.5],[.1,100]
oplot,[32,32]-.5,[.1,100]
oplot,[40,40]-.5,[.1,100]
oplot,[48,48]-.5,[.1,100]
oplot,[56,56]-.5,[.1,100]
oplot,[.1,100],[1.5,1.5]
oplot,[.1,100],[3.,3.]
oplot,[.1,100],[6.,6.]
oplot,[.1,100],[12.,12.]
oplot,[.1,100],[24.,24.]
oplot,[.1,100],[38.,38.]

makepng,'MLUT_table_plot3'

print,' '
print,mas[3,0,0],mas[3,0,8],mas[3,0,16],mas[3,0,24],mas[3,0,32],mas[3,0,40],mas[3,0,48],mas[3,0,56],mas[3,0,63]

endif

;*************************************************************************************************************
;*************************************************************************************************************
;*************************************************************************************************************


if keyword_set(return_nrg) then begin
	nrg_swp=nrg
	print, 'made it this far'
	return
endif

 
;***************************************************************************************************************
;***************************************************************************************************************
;***************************************************************************************************************

; make the software version number common block - used for CDF file production

;	common mvn_sta_software_version,ver & ver=0		; software version was "0" prior to 20141219
;	common mvn_sta_software_version,ver & ver=1		; changed 20150118 when all SIS required elements were included in common blocks, some element not filled in
        common mvn_sta_software_version,ver & ver=2             ; changed 20180423 updated dead time corrections and new corrections for blocked bins, jmm, 2018-04-23


;zero all the common block arrays

	common mvn_c0,mvn_c0_ind,mvn_c0_dat & mvn_c0_dat=0 & mvn_c0_ind=-1l
	common mvn_c2,mvn_c2_ind,mvn_c2_dat & mvn_c2_dat=0 & mvn_c2_ind=-1l
	common mvn_c4,mvn_c4_ind,mvn_c4_dat & mvn_c4_dat=0 & mvn_c4_ind=-1l
	common mvn_c6,mvn_c6_ind,mvn_c6_dat & mvn_c6_dat=0 & mvn_c6_ind=-1l
	common mvn_c8,mvn_c8_ind,mvn_c8_dat & mvn_c8_dat=0 & mvn_c8_ind=-1l
	common mvn_ca,mvn_ca_ind,mvn_ca_dat & mvn_ca_dat=0 & mvn_ca_ind=-1l
	common mvn_cc,mvn_cc_ind,mvn_cc_dat & mvn_cc_dat=0 & mvn_cc_ind=-1l
	common mvn_cd,mvn_cd_ind,mvn_cd_dat & mvn_cd_dat=0 & mvn_cd_ind=-1l
	common mvn_ce,mvn_ce_ind,mvn_ce_dat & mvn_ce_dat=0 & mvn_ce_ind=-1l
	common mvn_cf,mvn_cf_ind,mvn_cf_dat & mvn_cf_dat=0 & mvn_cf_ind=-1l
	common mvn_d0,mvn_d0_ind,mvn_d0_dat & mvn_d0_dat=0 & mvn_d0_ind=-1l
	common mvn_d1,mvn_d1_ind,mvn_d1_dat & mvn_d1_dat=0 & mvn_d1_ind=-1l
	common mvn_d2,mvn_d2_ind,mvn_d2_dat & mvn_d2_dat=0 & mvn_d2_ind=-1l
	common mvn_d3,mvn_d3_ind,mvn_d3_dat & mvn_d3_dat=0 & mvn_d3_ind=-1l
	common mvn_d4,mvn_d4_ind,mvn_d4_dat & mvn_d4_dat=0 & mvn_d4_ind=-1l
	common mvn_d6,mvn_d6_ind,mvn_d6_dat & mvn_d6_dat=0 & mvn_d6_ind=-1l
	common mvn_d7,mvn_d7_ind,mvn_d7_dat & mvn_d7_dat=0 & mvn_d7_ind=-1l
	common mvn_d8,mvn_d8_ind,mvn_d8_dat & mvn_d8_dat=0 & mvn_d8_ind=-1l
	common mvn_d9,mvn_d9_ind,mvn_d9_dat & mvn_d9_dat=0 & mvn_d9_ind=-1l
	common mvn_da,mvn_da_ind,mvn_da_dat & mvn_da_dat=0 & mvn_da_ind=-1l
	common mvn_db,mvn_db_ind,mvn_db_dat & mvn_db_dat=0 & mvn_db_ind=-1l

; zero the time jitter check

	c0_cnt8=0	&	c0_jitter_flag = 0
	c2_cnt8=0	&	c2_jitter_flag = 0
	c4_cnt8=0	&	c4_jitter_flag = 0
	c6_cnt8=0	&	c6_jitter_flag = 0
	c8_cnt8=0	&	c8_jitter_flag = 0
	ca_cnt8=0	&	ca_jitter_flag = 0
	cc_cnt8=0	&	cc_jitter_flag = 0
	cd_cnt8=0	&	cd_jitter_flag = 0
	ce_cnt8=0	&	ce_jitter_flag = 0
	cf_cnt8=0	&	cf_jitter_flag = 0
	d0_cnt8=0	&	d0_jitter_flag = 0
	d1_cnt8=0	&	d1_jitter_flag = 0
	d2_cnt8=0	&	d2_jitter_flag = 0
	d3_cnt8=0	&	d3_jitter_flag = 0
	d4_cnt8=0	&	d4_jitter_flag = 0
	d8_cnt8=0	&	d8_jitter_flag = 0
	da_cnt8=0	&	da_jitter_flag = 0

;***************************************************************************************************************
; C6 is completed first since its can reflect mode transitions at RAM-CONIC boundaries correctly and can 
;	subsequently be used to correct the mode transition times in C0 packets. Note that C0 can correct its
;	mode transitions at PICKUP-CONIC boundaries by matching times.

;***************************************************************************************************************
; APID C6


if keyword_set(apids) then test = fix((total(apids eq 'c6') + total(apids eq 'C6')) < 1) else test=0
if not keyword_set(apids) or test then begin
print,'Processing apid c6'

	ndis=0
	get_data,'mvn_STA_C6_DATA',data=t
	if size(/type,t) eq 8 then begin
		npts=2048									; 32Ex1Dx1Ax64M
		np = 2										; np is number of packets per measurement
		ind1 = where(t.x gt 0, nn)
		tt=t.x[0:nn-1] 
		dd=t.y[0:nn-1,*] 

; the following "if" makes sure there are at least two measurements so the out-of-order time correction works
	if nn ge 2*np then begin

		get_data,'mvn_STA_C6_DIAG',data=diag
;		en = (diag.y[0:nn-1] AND 15)
		en = (diag.y[0:nn-1] AND 1) 
		dt=0.1
			store_data,'mvn_sta_C6_DIAG_EN',data={x:tt+en*dt,y:en}
			get_data,'mvn_STA_C6_SEQ_CNTR',data=tmp2
			store_data,'mvn_sta_C6_SEQ_CNTR_EN',data={x:tt+en*dt,y:tmp2.y[0:nn-1]} 
			store_data,'mvn_sta_C6_DATA_EN',data={x:tt+en*dt,y:total(t.y[0:nn-1,*],2)} 

		ind = where(en eq 0 and shift(en,-1) eq 1,ndis)					; ndis is number of complete distributions

		if ndis ge 1 then begin

			dat = bytarr(np,ndis,npts/np)
			dat[0,*,*] = dd[ind,*]
			dat[1,*,*] = dd[ind+1,*]
			tdis = tt[ind]

;		correct half second jitter in header times, assumes times always delayed
			time = tdis
			dt = time[1:ndis-1]-time[0:ndis-2]-4.
			ind8 = where( .4 lt dt and dt lt .6,cnt8)
				c6_cnt8=cnt8
			for i=0,cnt8-1 do time[ind8[i]+1] = time[ind8[i]+1] - .5d
			dt = time[1:ndis-1]-time[0:ndis-2]-4.
			ind9 = where( -.6 lt dt and dt lt -.4,cnt9)
				c6_cnt9=cnt9
			for i=0,cnt9-1 do time[ind9[i]] = time[ind9[i]] - .5d
			ind9 = where((.4 lt dt and dt lt .6) or (-.6 lt dt and dt lt -.4),cnt10)
				c6_cnt10=cnt10
			if cnt10 gt 0 then c6_jitter_flag=1
			tdis = time

			get_data,'mvn_STA_C6_MODE',data=md
				md1 = md.y[ind[0:ndis-1]] and 127
				md2 = md.y[ind[0:ndis-1]]and 15
				rt2 = (md.y[ind[0:ndis-1]] and 112)/16

			get_data,'mvn_STA_C6_AVG',data=cavg
				avg = 2^(cavg.y[ind[0:ndis-1]] and 7)
				sum = (cavg.y[ind[0:ndis-1]] and 8)/8

				avg2 = sum*avg > 1

; the following seems to be working to handle headers out of phase with the data

			ind3 = where(md2[0:ndis-2] ne md2[1:ndis-1],nch)
			dd2 = decomp19[reform(transpose(reform(dat,np,ndis,64,16),[1,3,0,2]),ndis,32*64)]	
			if nch gt 0 then begin							; this is required because config headers are out of phase w/ data
				for ii=0,nch-1 do begin	
					for jj=1,3/avg[ind3[ii]] do begin			; 1/avg is generally not needed, but might need adjusting if we ever average C6 packets in time
						if ind3[ii] gt 2 and (ind3[ii]+jj) lt ndis then begin
							avg2[ind3[ii]+jj]=avg2[ind3[ii]]
							md2[ind3[ii]+jj]=md2[ind3[ii]]
							rt2[ind3[ii]+jj]=rt2[ind3[ii]]
							md1[ind3[ii]+jj]=md1[ind3[ii]]
						endif
					endfor
			; the following accounts for unpredictable 1 packet jitter in headers at mode changes
					if (ind3[ii]+jj+1) lt ndis then begin
					if total(abs(dd2[ind3[ii]+jj,*]-dd2[ind3[ii]+jj-1,*])) lt total(abs(dd2[ind3[ii]+jj,*]-dd2[ind3[ii]+jj+1,*])) then begin
						if (ind3[ii]+jj) lt ndis then begin
							avg2[ind3[ii]+jj]=avg2[ind3[ii]]
							md2[ind3[ii]+jj]=md2[ind3[ii]]
							rt2[ind3[ii]+jj]=rt2[ind3[ii]]
							md1[ind3[ii]+jj]=md1[ind3[ii]]
						endif
					endif
					endif	
				endfor
			endif

			tt1 = tdis - 2.*avg2 							; corrected timing for averaging, kluge for header mismatch
			tt2 = tdis + 2.*avg2 

			get_data,'mvn_STA_C6_ATTEN',data=catt						; attenuator state
			att0 = (catt.y[ind[0:ndis-1]] and replicate(192,ndis))/64
			if ndis ge 2 then ind0 = where(att0[0:ndis-2] ne att0[1:ndis-1],cnt0) else cnt0=0
			if cnt0 ne 0 then begin
				for i=0,cnt0-1 do begin
					inds = ind0[i]
					idelay = fix(3/avg2[inds])
; the following should make the attenuator timing a bit better at attM transitions
;					if att0[inds] eq 1 and att0[inds+1] eq 2 then idelay = fix(2/avg2[inds])
;					if att0[inds] eq 2 and att0[inds+1] eq 1 then idelay = fix(2/avg2[inds])
					if idelay gt 0 then att0[inds+1:(inds+idelay)<(ndis-1)] = att0[inds]
				endfor
			endif

			header = 256l^3*md.y[ind[0:ndis-1]] + 256l^2*cavg.y[ind[0:ndis-1]] + 256l*catt.y[ind[0:ndis-1]] + diag.y[ind[0:ndis-1]]

			store_data,'mvn_sta_C6_mode',data={x:tdis,y:md2}
				ylim,'mvn_sta_C6_mode',-1,7,0
			store_data,'mvn_sta_C6_rate',data={x:tdis,y:rt2}					; corrected modes
				ylim,'mvn_sta_C6_rate',-1,8,0
			store_data,'mvn_sta_C6_data_rate',data={x:tdis,y:rt2rate[rt2]}					; corrected modes
				ylim,'mvn_sta_C6_data_rate',0,5,0
				options,'mvn_sta_C6_data_rate',ytitle='sta!Cdata!Crate'
			store_data,'mvn_sta_C6_att',data={x:tdis,y:att0}
				ylim,'mvn_sta_C6_att',-1,4,0

;			swp_ind = md2swp[md1]									; old version
;			swp_ind = conf2swp[fix(interp((config4.y and 255)*1.,config4.x,tdis)+.5),md2]	
			swp_ind = conf2swp[fix(interp((config4.y and 511)*1.,config4.x,tdis)+.5),md2]	
			eprom_ver = fix(interp((config4.y and 255)*1.,config4.x,tdis)+.5)
			if tdis[0] lt time_double('2014-10-1/0') then eprom_ver[*]=0
			store_data,'mvn_sta_C6_eprom_ver',data={x:tdis,y:eprom_ver}
				ylim,'mvn_sta_C6_eprom_ver',min(eprom_ver)-1,max(eprom_ver)+1,0				

			energy=nrg[swp_ind,*]
			energy=total(reform(energy,ndis,2,32),2)/2.
			mass=mas[swp_ind,0,*]
			mass=reform(mass,ndis,64)								

			tmp=decomp19[reform(transpose(reform(dat,np,ndis,64,16),[1,3,0,2]),ndis,32,64)]		; [time,en,def,ma]

			store_data,'mvn_sta_C6_P1D_E',data={x:tdis,y:total(tmp,3),v:energy}
			store_data,'mvn_sta_C6_P1D_M',data={x:tdis,y:total(tmp,2),v:mass}
			store_data,'mvn_sta_C6_P1D_tot',data={x:tdis,y:total(total(tmp,3),2)}
			store_data,'mvn_sta_C6_P1D_all',data={x:tdis,y:reform(tmp,ndis,npts),v:indgen(npts)}

			ylim,'mvn_sta_C6_P1D_tot',0,0,1
			ylim,'mvn_sta_C6_P1D_E',.1,40000.,1
			ylim,'mvn_sta_C6_P1D_M',.5,100.,1

			zlim,'mvn_sta_C6_P1D_E',1,1.e3,1
			zlim,'mvn_sta_C6_P1D_M',1,1.e3,1

			options,'mvn_sta_C6_P1D_E',datagap=512.
			options,'mvn_sta_C6_P1D_M',datagap=512.
			options,'mvn_sta_C6_P1D_tot',datagap=512.

			options,'mvn_sta_C6_P1D_E','spec',1
			options,'mvn_sta_C6_P1D_M','spec',1

			options,'mvn_sta_C6_P1D_E',ytitle='sta!CP1D-C6!C!CEnergy!CeV'
			options,'mvn_sta_C6_P1D_M',ytitle='sta!CP1D-C6!C!CMass!Camu'
		endif
	endif
	endif

; Make C6 common block

   if size(/type,t) eq 8 and ndis ge 2 then begin

	nenergy = 32
	avg_nrg = 64/nenergy
	ndef = 1
	avg_def=16/ndef
	nanode = 1
	avg_an = 16/nanode
	nbins = ndef*nanode
	nmass = 64

	magf = replicate(0.,ndis)#[0.,0.,0.]
	quat_sc  = replicate(0.,ndis)#[0.,0.,0.,0.]
	quat_mso = replicate(0.,ndis)#[0.,0.,0.,0.]
	bins_sc = fix(replicate(1,ndis)#replicate(1,nbins))
	quality_flag = intarr(ndis)
	pos_sc_mso = replicate(0.,ndis)#[0.,0.,0.]
	bkg   = fltarr(ndis,nenergy,nmass)
	dead   = fltarr(ndis,nenergy,nmass) & dead[*]=1.

	energy2  = reform(reform(total(reform(nrg,n_swp,avg_nrg,nenergy),2)/avg_nrg,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)
	denergy2 = reform(reform(total(reform(dnrg,n_swp,avg_nrg,nenergy),2)       ,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)

;	gf[n_swp,64,16,16,4]
	gf2 = fltarr(n_swp,nenergy,4)
;	gf1 = total(reform(gf,n_swp,avg_nrg,nenergy,16,16,4),2)/avg_nrg
;	for i=0,n_swp-1 do gf2[i,*,*] = total(total(gf1[i,*,swp2gfdf[i,0]:swp2gfdf[i,1],swp2gfan[i,0]:swp2gfan[i,1],*],3),3)/avg_def
; correction 10-21-2014
	gf1 = total(reform(gf,n_swp,avg_nrg,nenergy,16,16,4),2)/avg_nrg
	for i=0,n_swp-1 do gf2[i,*,*] = avg_an*total(total(gf1[i,*,swp2gfdf[i,0]:swp2gfdf[i,1],swp2gfan[i,0]:swp2gfan[i,1],*],3),3)/(swp2gfdf[i,1]-swp2gfdf[i,0]+1.)/(swp2gfan[i,1]-swp2gfan[i,0]+1)

; kluge for pre-MOI solar wind -- assume all counts are through mech attenuator when activated
;	factor of 50 is because mech attenuator is factor of 100, but only covers half the FOV
	if first_t lt time_double('2014-09-01/0') then begin
		if keyword_set(gf_nor) then begin
			for i=0,n_swp-1 do gf2[i,*,2]=gf2[i,*,2]/50.
			for i=0,n_swp-1 do gf2[i,*,3]=gf2[i,*,3]/50.
		endif else begin
			gf2[3:4,*,2]=gf2[3:4,*,2]/50.
			gf2[3:4,*,3]=gf2[3:4,*,3]/50.
			gf2[7:8,*,2]=gf2[7:8,*,2]/50.
			gf2[7:8,*,3]=gf2[7:8,*,3]/50.
		endelse
	endif
; the following assumes that if the mechanical attenuator is closed, then the particles are attenuated in all modes 
;	compensates for swp2gfan[*,0:1]=[0,15] in pickup,eclipse,scan,protect modes. - see definintion of att_corr 
	if first_t ge time_double('2014-09-01/0') then begin
			gf2[3:4,*,2]=gf2[3:4,*,2]*att_corr
			gf2[3:4,*,3]=gf2[3:4,*,3]*att_corr
			gf2[7:8,*,2]=gf2[7:8,*,2]*att_corr
			gf2[7:8,*,3]=gf2[7:8,*,3]*att_corr
			gf2[11:14,*,2]=gf2[11:14,*,2]*att_corr
			gf2[11:14,*,3]=gf2[11:14,*,3]*att_corr
			gf2[17:20,*,2]=gf2[17:20,*,2]*att_corr
			gf2[17:20,*,3]=gf2[17:20,*,3]*att_corr
			gf2[23:26,*,2]=gf2[23:26,*,2]*att_corr
			gf2[23:26,*,3]=gf2[23:26,*,3]*att_corr
	endif

; ??????? i think the above line should sum over anodes and average over deflections so that the integ_t can reflect the dead time correctly
; ??????? for ram mode, gf could be constructed to only have GF in the ram direction

; the following line assumes a constant efficiency as a default until other calibration code can be developed
;    a proper efficiency calibration is handled mvn_sta_dead_load.pro

	eff2 = fltarr(128,nenergy,nmass) & eff2[*]=def_eff  & eff_ind=intarr(ndis)

;	mlut = md2mlut(md1)
	mlut = swp2mlut(swp_ind)
	mass_arr=total(total(reform(mas,n_swp,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	tof_arr=total(total(reform(tof,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	twt_arr=total(total(reform(twt,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/avg_nrg

	theta = fltarr(n_swp,nenergy,nmass) & theta[*]=0.
	dtheta = reform(reform(total(reform(abs(def(*,*,15)-def(*,*,0)),n_swp,avg_nrg,nenergy),2),n_swp*nenergy)#replicate(1.,nmass),n_swp,nenergy,nmass)/avg_nrg
	phi = fltarr(n_swp,nenergy,nmass) & phi[*]=0.
	dphi = fltarr(n_swp,nenergy,nmass) & dphi(*)=360.
	domega = dphi*dtheta/!radeg^2

	c6_dat= {project_name:		'MAVEN',				$
		spacecraft:		'0', 					$
		data_name:		'c6 32e64m', 				$
		apid:			'c6',					$
		units_name: 		'counts', 				$
		units_procedure: 	'mvn_sta_convert_units', 		$
		valid: 			replicate(1,ndis), 			$
		quality_flag: 		quality_flag, 				$

		time:			tt1,					$
		end_time:		tt2,					$
		delta_t:		tt2-tt1,				$
		integ_t: 		(tt2-tt1)/(nenergy*ndef)*dt_cor,	$	

		eprom_ver:		eprom_ver,				$
		header:			header,					$
		mode:			md2,					$
		rate:			rt2,					$
		swp_ind:		swp_ind,				$
		mlut_ind:		mlut,					$
		eff_ind:		eff_ind,				$
		att_ind:		att0,					$

		nenergy: 		nenergy,				$
		energy: 		energy2, 				$
		denergy: 		denergy2, 				$

		nbins: 			nbins, 					$
		bins: 			replicate(1,nbins), 			$
		ndef:			ndef,					$
		nanode:			nanode,					$

		theta: 			theta,  				$
		dtheta: 		dtheta,  				$
		phi: 			phi,  					$
		dphi: 			dphi, 					$
		domega: 		domega,  				$

		gf: 			gf2, 					$
		eff: 			eff2,	 				$

		geom_factor: 		geom_factor,				$
		dead1: 			dead1,					$
		dead2: 			dead2,					$
		dead3: 			dead3,					$

		nmass:			nmass,					$
		mass: 			1.0438871e-02, 				$
		mass_arr:		mass_arr,				$
		tof_arr:		tof_arr,				$
		twt_arr:		twt_arr,				$

		charge: 		1., 					$
		sc_pot: 		replicate(0.,ndis),			$
		magf:	 		magf, 					$
		quat_sc:	 	quat_sc, 				$
		quat_mso:	 	quat_mso, 				$
		bins_sc:		bins_sc,				$
		pos_sc_mso:		pos_sc_mso,				$

		bkg:	 		bkg,		 			$
		dead:	 		dead,		 			$

		data:			tmp}

		common mvn_c6,mvn_c6_ind,mvn_c6_dat & mvn_c6_dat=c6_dat & mvn_c6_ind=0l

   endif
endif


;***************************************************************************************************************
; APID C0

if keyword_set(apids) then test = fix((total(apids eq 'c0') + total(apids eq 'C0')) < 1) else test=0
if not keyword_set(apids) or test then begin
print,'Processing apid c0'

	nn=0
	get_data,'mvn_STA_C0_DATA',data=t
	if size(/type,t) eq 8 then begin
		npts=128									; 64Ex1Dx1Ax2M
		ind1 = where(t.x gt 0, nn)
		tt=t.x[0:nn-1]
	if nn ge 2 then begin

		get_data,'mvn_STA_C0_DIAG',data=diag

;		correct half second jitter in header times, assumes times always delayed by .5, assumes C0 has 4 sec cadence
			time = tt
			dt = time[1:nn-1]-time[0:nn-2]-4.
			ind8 = where( .4 lt dt and dt lt .6,cnt8)
				c0_cnt8=cnt8
			for i=0,cnt8-1 do for j=0,7 do time[ind8[i]+j+1] = time[ind8[i]+j+1] - .5d
			dt = time[1:nn-1]-time[0:nn-2]-4.
			ind9 = where( -.6 lt dt and dt lt -.4,cnt9)
				c0_cnt9=cnt9
			for i=0,cnt9-1 do for j=0,7 do time[ind9[i]-j] = time[ind9[i]-j] - .5d
			ind10 = where((.4 lt dt and dt lt .6) or (-.6 lt dt and dt lt -.4),cnt10)
				c0_cnt10=cnt10
			if cnt10 gt 0 then c0_jitter_flag=1
			tt = time

		get_data,'mvn_STA_C0_MODE',data=md
			md1 = md.y[0:nn-1] and 127 
			md2 = md.y[0:nn-1] and 15 
			rt2 = (md.y[0:nn-1] and 112)/16 

		get_data,'mvn_STA_C0_AVG',data=cavg							; average state
		avg = 2^(cavg.y and replicate(7,nn))
		sum = (cavg.y and replicate(8,nn))/8
			avg2 = sum*avg > 1

; the following is used to correct mode changes in packets when accompanied by changes in averaging time - no longer needed if C6 packets present 
		comp = (cavg.y and replicate(192,nn))/128
		ind = where(avg[0:nn-2] ne avg[1:nn-1],count)					; corrected timing for averaging
		if count ne 0 then begin
			for i=0,count-1 do begin
				a0 = avg[ind[i]]
				a1 = avg[ind[i]+1]
				dt = a1*4.
				nf = abs(round( ( (tt[ind[i]+1]-tt[ind[i]])/4. -(a0+a1)/2. ) /(a1-a0) ))
				if nf gt 7 then nf=0
				for j=ind[i]-nf+1,ind[i] do begin
					tt[j]=tt[ind[i]+1]-dt*(ind[i]+1-j)
					avg2[j]=avg2[ind[i]+1]
					md2[j]=md2[ind[i]+1]
					rt2[j]=rt2[ind[i]+1]
					md1[j]=md1[ind[i]+1]
				endfor
			endfor
		endif

;	correct C0 mode transitions using C6 data if it is available

		get_data,'mvn_sta_C6_mode',data=md6
		if size(/type,md6) eq 8 then begin
			get_data,'mvn_sta_C6_rate',data=rt6
			md2 = fix(round(interp(md6.y,md6.x,tt)))
			rt2 = fix(round(interp(rt6.y,rt6.x,tt)))
		endif
		md1 = rt2*16+md2	 

			tt1 = tt - 2.*avg2 								; corrected timing for averaging, kluge for header mismatch
			tt2 = tt + 2.*avg2 
			if nn gt 2 then begin
				tt2[0:nn-2] = tt2[0:nn-2] < tt1[1:nn-1]
				tt3 = (tt1 + tt2)/2.
;				print,'C0 correction for averaging error: tt3-tt = ',tt3-tt
				tt = tt3
			endif



		get_data,'mvn_STA_C0_ATTEN',data=catt						; attenuator state
		att1 = (catt.y[0:nn-1] and replicate(192,nn))/64
		att0 = att1
		store_data,'mvn_STA_C0_att_s',data={x:tt,y:att1}
		att2 = (catt.y[0:nn-1] and replicate(48,nn))/16
		store_data,'mvn_STA_C0_att_e',data={x:tt,y:att2}
		att3 = (catt.y[0:nn-1] and replicate(15,nn))
		store_data,'mvn_STA_C0_att_w',data={x:tt,y:att3}
		ind0 = where(att1[0:nn-2] ne att1[1:nn-1],cnt0)					; find att transitions
		if cnt0 ne 0 then begin
			nmax = 1024/npts
			for i=0,cnt0-1 do begin
				inds = ind0[i]
				if att3[inds] ge nmax then print,'APID C0 packet header error: WWWW too large, wwww=',att3[inds]
;				idelay = fix(2/avg[inds])					; observed internal delays of 2 x 4sec, hence the "2"
				idelay = fix(2/avg2[inds])					; observed internal delays of 2 x 4sec, hence the "2"
				iww = att3[inds] - 1
				if iww lt 0 then iww = nmax-1
				att0[inds-nmax+1:inds] = att1[inds+1] 				; replace transition att w/ next value
				att0[inds-nmax+1:inds-nmax+1+iww+idelay] = att1[inds]		; use ww and interal delays to correct att at previous value
			endfor
		endif

;	correct C0 attenuator transitions using C6 data if it is available
		get_data,'mvn_sta_C6_att',data=att6
		if size(/type,att6) eq 8 then att0 = fix(round(interp(att6.y,att6.x,tt)))<3

		header = 256l^3*md.y[0:nn-1] + 256l^2*cavg.y[0:nn-1] + 256l*catt.y[0:nn-1] + diag.y[0:nn-1]

		store_data,'mvn_sta_C0_mode',data={x:tt,y:md2}					; corrected modes
			ylim,'mvn_sta_C0_mode',-1,7,0
		store_data,'mvn_sta_C0_rate',data={x:tt,y:rt2}					; corrected modes
			ylim,'mvn_sta_C0_rate',-1,8,0
		store_data,'mvn_sta_C0_att',data={x:tt,y:att0}
			ylim,'mvn_sta_C0_att',-1,4,0

;		swp_ind = md2swp[md1]									; old version
;		swp_ind = conf2swp[fix(interp((config4.y and 255)*1.,config4.x,tt)+.5),md2]					
		swp_ind = conf2swp[fix(interp((config4.y and 511)*1.,config4.x,tt)+.5),md2]					
			eprom_ver = fix(interp((config4.y and 255)*1.,config4.x,tt)+.5)
			if tt[0] lt time_double('2014-10-1/0') then eprom_ver[*]=0

		energy=nrg[swp_ind,*]
		mass=mas[swp_ind,0,*]
		mass=total(reform(mass,nn,32,2),2)/32.						; because there are only 2 masses

		tmp=decomp19[transpose(reform(t.y[0:nn-1,*],nn,2,64),[0,2,1])]			; [time,en,ma]

		store_data,'mvn_sta_C0_P1A_E',data={x:tt,y:reform(total(tmp,3),nn,64),v:energy}
		store_data,'mvn_sta_C0_P1A_M',data={x:tt,y:reform(total(tmp,2),nn,2),v:mass}
		store_data,'mvn_sta_C0_P1A_E_M0',data={x:tt,y:reform(tmp[*,*,0],nn,64),v:energy}
		store_data,'mvn_sta_C0_P1A_E_M1',data={x:tt,y:reform(tmp[*,*,1],nn,64),v:energy}
		store_data,'mvn_sta_C0_P1A_tot',data={x:tt,y:total(total(tmp,2),2)}
		store_data,'mvn_sta_C0_P1A_all',data={x:tt,y:reform(tmp,nn,npts),v:findgen(npts)}


;		store_data,'mvn_sta_C0_E_eflx',data={x:tt,y:reform(total(tmp,3),nn,64),v:energy}

		ylim,'mvn_sta_C0_P1A_tot',0,0,1
		ylim,'mvn_sta_C0_P1A_E',.1,40000.,1
		ylim,'mvn_sta_C0_P1A_M',.5,100,1
		ylim,'mvn_sta_C0_P1A_E_M0',.4,40000.,1
		ylim,'mvn_sta_C0_P1A_E_M1',.4,40000.,1
		zlim,'mvn_sta_C0_P1A_E',1,1.e3,1
		zlim,'mvn_sta_C0_P1A_M',1,1.e3,1
		zlim,'mvn_sta_C0_P1A_E_M0',1,1.e3,1
		zlim,'mvn_sta_C0_P1A_E_M1',1,1.e3,1
		datagap=64.
		options,'mvn_sta_C0_P1A_E',datagap=datagap
		options,'mvn_sta_C0_P1A_M',datagap=datagap
		options,'mvn_sta_C0_P1A_E_M0',datagap=datagap
		options,'mvn_sta_C0_P1A_E_M1',datagap=datagap
		options,'mvn_sta_C0_P1A_tot',datagap=datagap
		options,'mvn_sta_C0_att',datagap=datagap
		options,'mvn_sta_C0_mode',datagap=datagap

		options,'mvn_sta_C0_P1A_E','spec',1
		options,'mvn_sta_C0_P1A_M','spec',1
		options,'mvn_sta_C0_P1A_E_M0','spec',1
		options,'mvn_sta_C0_P1A_E_M1','spec',1
		options,'mvn_sta_C0_P1A_E',ytitle='sta!CP1A-C0!C!CEnergy!CeV'
		options,'mvn_sta_C0_P1A_M',ytitle='sta!CP1A-C0!C!CMass!Camu'
		options,'mvn_sta_C0_P1A_E_M0',ytitle='sta!CP1A-C0!CH+He+!C!CEnergy!CeV'
		options,'mvn_sta_C0_P1A_E_M1',ytitle='sta!CP1A-C0!CO+O2+!C!CEnergy!CeV'
	endif
	endif

; Make C0 common block

   if size(/type,t) eq 8 and nn ge 2 then begin

	nenergy = 64
	avg_nrg = 64/nenergy
	ndef = 1
	avg_def=16/ndef
	nanode = 1
	avg_an = 16/nanode
	nbins = ndef*nanode
	nmass = 2

	magf = replicate(0.,nn)#[0.,0.,0.]
	quat_sc  = replicate(0.,nn)#[0.,0.,0.,0.]
	quat_mso = replicate(0.,nn)#[0.,0.,0.,0.]
	bins_sc = fix(replicate(1,nn)#replicate(1,nbins))
	quality_flag = intarr(nn)
	pos_sc_mso = replicate(0.,nn)#[0.,0.,0.]
	bkg   = fltarr(nn,nenergy,nmass)
	dead   = fltarr(nn,nenergy,nmass) & dead[*]=1.

	energy2  = reform(reform(total(reform(nrg,n_swp,avg_nrg,nenergy),2)/avg_nrg,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)
	denergy2 = reform(reform(total(reform(dnrg,n_swp,avg_nrg,nenergy),2)       ,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)

;	gf[n_swp,64,16,16,4]
	gf2 = fltarr(n_swp,nenergy,4)
	gf1 = total(reform(gf,n_swp,avg_nrg,nenergy,16,16,4),2)/avg_nrg
	for i=0,n_swp-1 do gf2[i,*,*] = avg_an*total(total(gf1[i,*,swp2gfdf[i,0]:swp2gfdf[i,1],swp2gfan[i,0]:swp2gfan[i,1],*],3),3)/(swp2gfdf[i,1]-swp2gfdf[i,0]+1.)/(swp2gfan[i,1]-swp2gfan[i,0]+1)


; kluge for pre-MOI solar wind -- assume all counts are through mech attenuator when activated
;	factor of 50 is because mech attenuator is factor of 100, but only covers half the FOV
	if first_t lt time_double('2014-09-01/0') then begin
		if keyword_set(gf_nor) then begin
			for i=0,n_swp-1 do gf2[i,*,2]=gf2[i,*,2]/50.
			for i=0,n_swp-1 do gf2[i,*,3]=gf2[i,*,3]/50.
		endif else begin
			gf2[3:4,*,2]=gf2[3:4,*,2]/50.
			gf2[3:4,*,3]=gf2[3:4,*,3]/50.
			gf2[7:8,*,2]=gf2[7:8,*,2]/50.
			gf2[7:8,*,3]=gf2[7:8,*,3]/50.
		endelse
	endif
; the following assumes that if the mechanical attenuator is closed, then the particles are attenuated in all modes 
;	compensates for swp2gfan[*,0:1]=[0,15] in pickup,eclipse,scan,protect modes. - see definintion of att_corr 
	if first_t ge time_double('2014-09-01/0') then begin
			gf2[3:4,*,2]=gf2[3:4,*,2]*att_corr
			gf2[3:4,*,3]=gf2[3:4,*,3]*att_corr
			gf2[7:8,*,2]=gf2[7:8,*,2]*att_corr
			gf2[7:8,*,3]=gf2[7:8,*,3]*att_corr
			gf2[11:14,*,2]=gf2[11:14,*,2]*att_corr
			gf2[11:14,*,3]=gf2[11:14,*,3]*att_corr
			gf2[17:20,*,2]=gf2[17:20,*,2]*att_corr
			gf2[17:20,*,3]=gf2[17:20,*,3]*att_corr
			gf2[23:26,*,2]=gf2[23:26,*,2]*att_corr
			gf2[23:26,*,3]=gf2[23:26,*,3]*att_corr
	endif

; the following line assumes a constant efficiency as a default until other calibration code can be developed
;    a proper efficiency calibration is handled mvn_sta_dead_load.pro

	eff2 = fltarr(128,nenergy,nmass) & eff2[*]=def_eff  & eff_ind=intarr(nn)

;	mlut = md2mlut(md1)
	mlut = swp2mlut(swp_ind)
	mass_arr=total(total(reform(mas,n_swp,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	tof_arr=total(total(reform(tof,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	twt_arr=total(total(reform(twt,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/avg_nrg

	theta = fltarr(n_swp,nenergy,nmass) & theta[*]=0.
	dtheta = reform(reform(total(reform(abs(def(*,*,15)-def(*,*,0)),n_swp,avg_nrg,nenergy),2),n_swp*nenergy)#replicate(1.,nmass),n_swp,nenergy,nmass)/avg_nrg
	phi = fltarr(n_swp,nenergy,nmass) & phi[*]=0.
	dphi = fltarr(n_swp,nenergy,nmass) & dphi(*)=360.
	domega = dphi*dtheta/!radeg^2

	c0_dat= {project_name:		'MAVEN',				$
		spacecraft:		'0', 					$
		data_name:		'c0 64e2m', 				$
		apid:			'c0',					$
		units_name: 		'counts', 				$
		units_procedure: 	'mvn_sta_convert_units', 		$
		valid: 			replicate(1,nn), 			$
		quality_flag: 		quality_flag, 				$

		time:			tt1,					$
		end_time:		tt2,					$
		delta_t:		tt2-tt1,				$
		integ_t: 		(tt2-tt1)/(nenergy*ndef)*dt_cor,	$	

		eprom_ver:		eprom_ver,				$
		header:			header,					$
		mode:			md2,					$
		rate:			rt2,					$
		swp_ind:		swp_ind,				$
		mlut_ind:		mlut,					$
		eff_ind:		eff_ind,				$
		att_ind:		att0,					$

		nenergy: 		nenergy,				$
		energy: 		energy2, 				$
		denergy: 		denergy2, 				$

		nbins: 			nbins, 					$
		bins: 			replicate(1,nbins), 			$
		ndef:			ndef,					$
		nanode:			nanode,					$

		theta: 			theta,  				$
		dtheta: 		dtheta,  				$
		phi: 			phi,  					$
		dphi: 			dphi, 					$
		domega: 		domega,  				$

		gf: 			gf2, 					$
		eff: 			eff2,	 				$

		geom_factor: 		geom_factor,				$
		dead1: 			dead1,					$
		dead2: 			dead2,					$
		dead3: 			dead3,					$

		nmass:			nmass,					$
		mass: 			1.0438871e-02, 				$
		mass_arr:		mass_arr,				$
		tof_arr:		tof_arr,				$
		twt_arr:		twt_arr,				$

		charge: 		1., 					$
		sc_pot: 		replicate(0.,nn),			$
		magf:	 		magf, 					$
		quat_sc:	 	quat_sc, 				$
		quat_mso:	 	quat_mso, 				$
		bins_sc:		bins_sc,				$
		pos_sc_mso:		pos_sc_mso,				$

		bkg:	 		bkg,		 			$
		dead:	 		dead,		 			$

		data:			tmp}

		common mvn_c0,mvn_c0_ind,mvn_c0_dat & mvn_c0_dat=c0_dat & mvn_c0_ind=0l

   endif
endif


;***************************************************************************************************************
; APID C2

if keyword_set(apids) then test = fix((total(apids eq 'c2') + total(apids eq 'C2')) < 1) else test=0
if not keyword_set(apids) or test then begin
print,'Processing apid c2'

	nn=0
	get_data,'mvn_STA_C2_DATA',data=t
	if size(/type,t) eq 8 then begin
		npts=1024									; 32Ex1Dx1Ax32M
		ind1 = where(t.x gt 0, nn)
		tt=t.x[0:nn-1]
	if nn ge 2 then begin

		get_data,'mvn_STA_C2_DIAG',data=diag

		get_data,'mvn_STA_C2_MODE',data=md
			md1 = md.y[0:nn-1] and 127
			md2 = md.y[0:nn-1] and 15
			rt2 = (md.y[0:nn-1] and 112)/16

;	Correct tt for mode change boundaries, may want to add similar feature to other packets
;	assume start time in packet is correct and end time reflects incorrect CCxxSNNN bits
;	correct center time by using the start time of next packet

		get_data,'mvn_STA_C2_AVG',data=cavg						; average state
			avg = 2^(cavg.y[0:nn-1] and 7)
			sum = (cavg.y[0:nn-1] and 8)/8
			avg2 = sum*avg > 1

; the following needs to be checked to handle headers out of phase with the data  

			ind = where(md2[0:nn-2] ne md2[1:nn-1],nch)	
			if nch gt 0 then begin							; this is required because config headers are out of phase w/ data
				for ii=0,nch-1 do begin	
					for jj=1,3/avg[ind[ii]] do begin			; 1/avg is generally not needed, but might need adjusting if we ever average C6 packets in time
						if ind[ii]+jj le nn-1 then begin
							avg2[ind[ii]+jj]=avg2[ind[ii]]
							md2[ind[ii]+jj]=md2[ind[ii]]
							rt2[ind[ii]+jj]=rt2[ind[ii]]
							md1[ind[ii]+jj]=md1[ind[ii]]
						endif
					endfor
				endfor
			endif

;	correct C2 mode transitions using C6 data if it is available

		get_data,'mvn_sta_C6_mode',data=md6
		if size(/type,md6) eq 8 then begin
			get_data,'mvn_sta_C6_rate',data=rt6
			ind0 = where (md2[0:nn-2] ne md2[1:nn-1],count) 
			if count gt 0 then begin
				for i=0,count-1 do begin
					j0=0>(ind0[i]-8)
					j1=(nn-1)<(ind0[i]+8)
					for j=j0,j1 do begin
						tmpmin = min(abs(md6.x - tt[j]),ind6)
						if tmpmin lt 1. and md6.y[ind6] ne md2[j] then begin
							md2[j]=md6.y[ind6]
							rt2[j]=rt6.y[ind6]
						endif 
					endfor
				endfor
			endif
		endif
		md1 = rt2*16+md2	 

		tt1 = tt - 2.*avg2 								; corrected timing for averaging, kluge for header mismatch
		tt2 = tt + 2.*avg2 
		if nn gt 2 then begin
			tt2[0:nn-2] = tt2[0:nn-2] < tt1[1:nn-1]
			tt3 = (tt1 + tt2)/2.
;			print,tt3-tt
			tt = tt3
		endif

		get_data,'mvn_STA_C2_ATTEN',data=catt						; attenuator state
		att0 = (catt.y[0:nn-1] and replicate(192,nn))/64
		if nn gt 2 then begin
			ind0 = where(att0[0:nn-2] ne att0[1:nn-1],cnt0)
			if cnt0 ne 0 then begin
				for i=0,cnt0-1 do begin
					inds = ind0[i]
					idelay = fix(2/avg2[inds])
					if idelay gt 0 then att0[inds+1:(inds+idelay)<(nn-1)] = att0[inds]
				endfor
			endif
		endif

		header = 256l^3*md.y[0:nn-1] + 256l^2*cavg.y[0:nn-1] + 256l*catt.y[0:nn-1] + diag.y[0:nn-1]

		store_data,'mvn_sta_C2_mode',data={x:tt,y:md2}					; corrected modes
			ylim,'mvn_sta_C2_mode',-1,7,0
		store_data,'mvn_sta_C2_rate',data={x:tt,y:rt2}					; corrected modes
			ylim,'mvn_sta_C2_rate',-1,8,0
		store_data,'mvn_sta_C2_att',data={x:tt,y:att0}
			ylim,'mvn_sta_C2_att',-1,4,0

		get_data,'mvn_STA_C2_SEQ_CNTR',data=tmp7
		store_data,'mvn_sta_C2_SEQ_CNTR2',data={x:tt,y:tmp7.y[0:nn-1]}

;		swp_ind = md2swp[md1]								; old version
;		swp_ind = conf2swp[fix(interp((config4.y and 255)*1.,config4.x,tt)+.5),md2]					
		swp_ind = conf2swp[fix(interp((config4.y and 511)*1.,config4.x,tt)+.5),md2]					
			eprom_ver = fix(interp((config4.y and 255)*1.,config4.x,tt)+.5)
			if tt[0] lt time_double('2014-10-1/0') then eprom_ver[*]=0

		energy=nrg[swp_ind,*]
		energy=total(reform(energy,nn,2,32),2)/2.					; because there are only 32 energies
		mass=mas[swp_ind,0,*]
		mass=total(reform(mass,nn,2,32),2)/2.						; because there are only 32 masses

		tmp=decomp19[transpose(reform(t.y[0:nn-1,*],nn,32,32),[0,2,1])]			; [time,en,ma]

		store_data,'mvn_sta_C2_P1B_E',data={x:tt,y:total(tmp,3),v:energy}
		store_data,'mvn_sta_C2_P1B_M',data={x:tt,y:total(tmp,2),v:mass}
		store_data,'mvn_sta_C2_P1B_tot',data={x:tt,y:total(total(tmp,2),2)}
		store_data,'mvn_sta_C2_P1B_all',data={x:tt,y:reform(tmp,nn,npts),v:findgen(npts)}

		ylim,'mvn_sta_C2_P1B_tot',0,0,1
		ylim,'mvn_sta_C2_P1B_E',.4,40000.,1
		ylim,'mvn_sta_C2_P1B_M',.5,100,1
		zlim,'mvn_sta_C2_P1B_E',1,1.e3,1
		zlim,'mvn_sta_C2_P1B_M',1,1.e3,1
		datagap=256.
		options,'mvn_sta_C2_P1B_E',datagap=datagap
		options,'mvn_sta_C2_P1B_M',datagap=datagap
		options,'mvn_sta_C2_P1B_tot',datagap=datagap
		options,'mvn_sta_C2_att',datagap=datagap
		options,'mvn_STA_C2_MODE',datagap=datagap


		options,'mvn_sta_C2_P1B_E','spec',1
		options,'mvn_sta_C2_P1B_M','spec',1
		options,'mvn_sta_C2_P1B_E',ytitle='sta!CP1B-C2!C!CEnergy!CeV'
		options,'mvn_sta_C2_P1B_M',ytitle='sta!CP1B-C2!C!CMass!Camu'
	endif
	endif

; Make C2 common block

   if size(/type,t) eq 8 and nn ge 2 then begin

	nenergy = 32
	avg_nrg = 64/nenergy
	ndef = 1
	avg_def=16/ndef
	nanode = 1
	avg_an = 16/nanode
	nbins = ndef*nanode
	nmass = 32

	magf = replicate(0.,nn)#[0.,0.,0.]
	quat_sc  = replicate(0.,nn)#[0.,0.,0.,0.]
	quat_mso = replicate(0.,nn)#[0.,0.,0.,0.]
	bins_sc = fix(replicate(1,nn)#replicate(1,nbins))
	quality_flag = intarr(nn)
	pos_sc_mso = replicate(0.,nn)#[0.,0.,0.]
	bkg   = fltarr(nn,nenergy,nmass)
	dead   = fltarr(nn,nenergy,nmass) & dead[*]=1.

	energy2  = reform(reform(total(reform(nrg,n_swp,avg_nrg,nenergy),2)/avg_nrg,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)
	denergy2 = reform(reform(total(reform(dnrg,n_swp,avg_nrg,nenergy),2)       ,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)

;	gf[n_swp,64,16,16,4]
	gf2 = fltarr(n_swp,nenergy,4)
	gf1 = total(reform(gf,n_swp,avg_nrg,nenergy,16,16,4),2)/avg_nrg
	for i=0,n_swp-1 do gf2[i,*,*] = avg_an*total(total(gf1[i,*,swp2gfdf[i,0]:swp2gfdf[i,1],swp2gfan[i,0]:swp2gfan[i,1],*],3),3)/(swp2gfdf[i,1]-swp2gfdf[i,0]+1.)/(swp2gfan[i,1]-swp2gfan[i,0]+1)


; kluge for pre-MOI solar wind -- assume all counts are through mech attenuator when activated
;	factor of 50 is because mech attenuator is factor of 100, but only covers half the FOV
	if first_t lt time_double('2014-09-01/0') then begin
		if keyword_set(gf_nor) then begin
			for i=0,n_swp-1 do gf2[i,*,2]=gf2[i,*,2]/50.
			for i=0,n_swp-1 do gf2[i,*,3]=gf2[i,*,3]/50.
		endif else begin
			gf2[3:4,*,2]=gf2[3:4,*,2]/50.
			gf2[3:4,*,3]=gf2[3:4,*,3]/50.
			gf2[7:8,*,2]=gf2[7:8,*,2]/50.
			gf2[7:8,*,3]=gf2[7:8,*,3]/50.
		endelse
	endif
; the following assumes that if the mechanical attenuator is closed, then the particles are attenuated in all modes 
;	compensates for swp2gfan[*,0:1]=[0,15] in pickup,eclipse,scan,protect modes. - see definintion of att_corr 
	if first_t ge time_double('2014-09-01/0') then begin
			gf2[3:4,*,2]=gf2[3:4,*,2]*att_corr
			gf2[3:4,*,3]=gf2[3:4,*,3]*att_corr
			gf2[7:8,*,2]=gf2[7:8,*,2]*att_corr
			gf2[7:8,*,3]=gf2[7:8,*,3]*att_corr
			gf2[11:14,*,2]=gf2[11:14,*,2]*att_corr
			gf2[11:14,*,3]=gf2[11:14,*,3]*att_corr
			gf2[17:20,*,2]=gf2[17:20,*,2]*att_corr
			gf2[17:20,*,3]=gf2[17:20,*,3]*att_corr
			gf2[23:26,*,2]=gf2[23:26,*,2]*att_corr
			gf2[23:26,*,3]=gf2[23:26,*,3]*att_corr
	endif

; the following line assumes a constant efficiency as a default until other calibration code can be developed
;    a proper efficiency calibration is handled mvn_sta_dead_load.pro

	eff2 = fltarr(128,nenergy,nmass) & eff2[*]=def_eff  & eff_ind=intarr(nn)

;	mlut = md2mlut(md1)
	mlut = swp2mlut(swp_ind)
	mass_arr=total(total(reform(mas,n_swp,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	tof_arr=total(total(reform(tof,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	twt_arr=total(total(reform(twt,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/avg_nrg

	theta = fltarr(n_swp,nenergy,nmass) & theta[*]=0.
	dtheta = reform(reform(total(reform(abs(def(*,*,15)-def(*,*,0)),n_swp,avg_nrg,nenergy),2),n_swp*nenergy)#replicate(1.,nmass),n_swp,nenergy,nmass)/avg_nrg
	phi = fltarr(n_swp,nenergy,nmass) & phi[*]=0.
	dphi = fltarr(n_swp,nenergy,nmass) & dphi(*)=360.
	domega = dphi*dtheta/!radeg^2

	c2_dat= {project_name:		'MAVEN',				$
		spacecraft:		'0', 					$
;		data_name:		'C2 Energy-Mass', 			$
;		apid:			'C2',					$
		data_name:		'c2 32e32m', 				$
		apid:			'c2',					$
		units_name: 		'counts', 				$
		units_procedure: 	'mvn_sta_convert_units', 		$
		valid: 			replicate(1,nn), 			$
		quality_flag: 		quality_flag, 				$

		time:			tt1,					$
		end_time:		tt2,					$
		delta_t:		tt2-tt1,				$
		integ_t: 		(tt2-tt1)/(nenergy*ndef)*dt_cor,	$	

		eprom_ver:		eprom_ver,				$
		header:			header,					$
		mode:			md2,					$
		rate:			rt2,					$
		swp_ind:		swp_ind,				$
		mlut_ind:		mlut,					$
		eff_ind:		eff_ind,				$
		att_ind:		att0,					$

		nenergy: 		nenergy,				$
		energy: 		energy2, 				$
		denergy: 		denergy2, 				$

		nbins: 			nbins, 					$
		bins: 			replicate(1,nbins), 			$
		ndef:			ndef,					$
		nanode:			nanode,					$

		theta: 			theta,  				$
		dtheta: 		dtheta,  				$
		phi: 			phi,  					$
		dphi: 			dphi, 					$
		domega: 		domega,  				$

		gf: 			gf2, 					$
		eff: 			eff2,	 				$

		geom_factor: 		geom_factor,				$
		dead1: 			dead1,					$
		dead2: 			dead2,					$
		dead3: 			dead3,					$

		nmass:			nmass,					$
		mass: 			1.0438871e-02, 				$
		mass_arr:		mass_arr,				$
		tof_arr:		tof_arr,				$
		twt_arr:		twt_arr,				$

		charge: 		1., 					$
		sc_pot: 		replicate(0.,nn),			$
		magf:	 		magf, 					$
		quat_sc:	 	quat_sc, 				$
		quat_mso:	 	quat_mso, 				$
		bins_sc:		bins_sc,				$
		pos_sc_mso:		pos_sc_mso,				$

		bkg:	 		bkg,		 			$
		dead:	 		dead,		 			$

		data:			tmp}

		common mvn_c2,mvn_c2_ind,mvn_c2_dat & mvn_c2_dat=c2_dat & mvn_c2_ind=0l

   endif 
endif

;***************************************************************************************************************
; APID C4


if keyword_set(apids) then test = fix((total(apids eq 'c4') + total(apids eq 'C4')) < 1) else test=0
if not keyword_set(apids) or test then begin
print,'Processing apid c4'

	nn=0
	get_data,'mvn_STA_C4_DATA',data=t
	if size(/type,t) eq 8 then begin
		npts=256									; 4Ex1Dx1Ax64M
		ind1 = where(t.x gt 0, nn)
		tt=t.x[0:nn-1]
	if nn ge 2 then begin

		get_data,'mvn_STA_C4_DIAG',data=diag

		get_data,'mvn_STA_C4_MODE',data=md
			md1 = md.y[0:nn-1] and 127
			md2 = md.y[0:nn-1] and 15
			rt2 = (md.y[0:nn-1] and 112)/16

		get_data,'mvn_STA_C4_AVG',data=cavg							; set avg state
		avg = 2^(cavg.y and replicate(7,nn))
		sum = (cavg.y and replicate(8,nn))/8
			avg2 = sum*avg > 1

		comp = (cavg.y and replicate(192,nn))/128

; the following may be obsolete if C6 packet header phase correction are possible

		ind = where(avg[0:nn-2] ne avg[1:nn-1],count)
		if count ne 0 then begin
			for i=0,count-1 do begin
				a0 = avg[ind[i]]
				a1 = avg[ind[i]+1]
				dt = a1*4.
				nf = abs(round( ( (tt[ind[i]+1]-tt[ind[i]])/4. -(a0+a1)/2. ) /(a1-a0) ))
				if nf gt 15 then nf=0
				for j=ind[i]-nf+1,ind[i] do begin
					tt[j]=tt[ind[i]+1]-dt*(ind[i]+1-j)
					avg2[j]=avg2[ind[i]+1]
					md2[j]=md2[ind[i]+1]
					rt2[j]=rt2[ind[i]+1]
					md1[j]=md1[ind[i]+1]
				endfor
			endfor
		endif

;	correct C4 mode transitions using C6 data if it is available (very unlikely)

		get_data,'mvn_sta_C6_mode',data=md6
		if size(/type,md6) eq 8 then begin
			get_data,'mvn_sta_C6_rate',data=rt6
			ind0 = where (md2[0:nn-2] ne md2[1:nn-1],count) 
			if count gt 0 then begin
				for i=0,count-1 do begin
					j0=0>(ind0[i]-8)
					j1=(nn-1)<(ind0[i]+8)
					for j=j0,j1 do begin
						tmpmin = min(abs(md6.x - tt[j]),ind6)
						if tmpmin lt 1. and md6.y[ind6] ne md2[j] then begin
							md2[j]=md6.y[ind6]
							rt2[j]=rt6.y[ind6]
						endif 
					endfor
				endfor
			endif
		endif
		md1 = rt2*16+md2	 

			tt1 = tt - 2.*avg2 								; corrected timing for averaging, kluge for header mismatch
			tt2 = tt + 2.*avg2 
			if nn gt 2 then begin
				tt2[0:nn-2] = tt2[0:nn-2] < tt1[1:nn-1]
				tt3 = (tt1 + tt2)/2.
;				print,'C0 correction for averaging error: tt3-tt = ',tt3-tt
				tt = tt3
			endif


		get_data,'mvn_STA_C4_ATTEN',data=catt						; set attenuator state
		att1 = (catt.y[0:nn-1] and replicate(192,nn))/64
		att0 = att1
		store_data,'mvn_STA_C4_att_s',data={x:tt,y:att1}
		att2 = (catt.y[0:nn-1] and replicate(48,nn))/16
		store_data,'mvn_STA_C4_att_e',data={x:tt,y:att2}
		att3 = (catt.y[0:nn-1] and replicate(15,nn))
		store_data,'mvn_STA_C4_att_w',data={x:tt,y:att3}
		ind0 = where(att1[0:nn-2] ne att1[1:nn-1],cnt0)					; find att transitions
		if cnt0 ne 0 then begin
			nmax = 1024/npts
			for i=0,cnt0-1 do begin
				inds = ind0[i]
				if att3[inds] ge nmax then print,'APID C4 packet header error: WWWW too large, wwww=',att3[inds]
;				idelay = fix(2/avg[inds])					; observed internal delays of 2 x 4sec, hence the "2"
				idelay = fix(2/avg2[inds])					; observed internal delays of 2 x 4sec, hence the "2"
				iww = att3[inds] - 1
				if iww lt 0 then iww = nmax-1
				att0[inds-nmax+1:inds] = att1[inds+1] 				; replace transition att w/ next value
				att0[inds-nmax+1:inds-nmax+1+iww+idelay] = att1[inds]		; use ww and interal delays to correct att at previous value
			endfor
		endif

		header = 256l^3*md.y[0:nn-1] + 256l^2*cavg.y[0:nn-1] + 256l*catt.y[0:nn-1] + diag.y[0:nn-1]

		store_data,'mvn_sta_C4_mode',data={x:tt,y:md2}
			ylim,'mvn_sta_C4_mode',-1,7,0
		store_data,'mvn_sta_C4_rate',data={x:tt,y:rt2}					; corrected modes
			ylim,'mvn_sta_C4_rate',-1,8,0
		store_data,'mvn_sta_C4_att',data={x:tt,y:att0}
			ylim,'mvn_sta_C4_att',-1,4,0

;		swp_ind = md2swp[md1]									; old version
;		swp_ind = conf2swp[fix(interp((config4.y and 255)*1.,config4.x,tt)+.5),md2]					
		swp_ind = conf2swp[fix(interp((config4.y and 511)*1.,config4.x,tt)+.5),md2]					
			eprom_ver = fix(interp((config4.y and 255)*1.,config4.x,tt)+.5)
			if tt[0] lt time_double('2014-10-1/0') then eprom_ver[*]=0

		energy=nrg[swp_ind,*]
		energy=total(reform(energy,nn,16,4),2)/16.
		mass=mas[swp_ind,0,*]
		mass=reform(mass,nn,64)								; because there are only 32 masses

		tmp=decomp19[transpose(reform(t.y[0:nn-1,*],nn,64,4),[0,2,1])]			; [time,en,ma]

		store_data,'mvn_sta_C4_P1C_E',data={x:tt,y:total(tmp,3),v:energy}
		store_data,'mvn_sta_C4_P1C_M',data={x:tt,y:total(tmp,2),v:mass}
		store_data,'mvn_sta_C4_P1C_tot',data={x:tt,y:total(total(tmp,2),2)}
		store_data,'mvn_sta_C4_P1C_all',data={x:tt,y:reform(tmp,nn,npts),v:findgen(npts)}

		ylim,'mvn_sta_C4_P1C_tot',0,0,1
		ylim,'mvn_sta_C4_P1C_E',.4,40000.,1
		ylim,'mvn_sta_C4_P1C_M',.5,100,1
		zlim,'mvn_sta_C4_P1C_E',1,1000,1
		zlim,'mvn_sta_C4_P1C_M',1,1000,1
		datagap=64.
		options,'mvn_sta_C4_P1C_E',datagap=datagap
		options,'mvn_sta_C4_P1C_M',datagap=datagap
		options,'mvn_sta_C4_P1C_tot',datagap=datagap
		options,'mvn_sta_C4_att',datagap=datagap
		options,'mvn_sta_C4_mode',datagap=datagap

		options,'mvn_sta_C4_P1C_E','spec',1
		options,'mvn_sta_C4_P1C_M','spec',1
		options,'mvn_sta_C4_P1C_E',ytitle='sta!CP1C-C4!C!CEnergy!CeV'
		options,'mvn_sta_C4_P1C_M',ytitle='sta!CP1C-C4!C!CMass!Camu'
	endif
	endif

; Make C4 common block

   if size(/type,t) eq 8 and nn ge 2 then begin

	nenergy = 4
	avg_nrg = 64/nenergy
	ndef = 1
	avg_def=16/ndef
	nanode = 1
	avg_an = 16/nanode
	nbins = ndef*nanode
	nmass = 64

	magf = replicate(0.,nn)#[0.,0.,0.]
	quat_sc  = replicate(0.,nn)#[0.,0.,0.,0.]
	quat_mso = replicate(0.,nn)#[0.,0.,0.,0.]
	bins_sc = fix(replicate(1,nn)#replicate(1,nbins))
	quality_flag = intarr(nn)
	pos_sc_mso = replicate(0.,nn)#[0.,0.,0.]
	bkg   = fltarr(nn,nenergy,nmass)
	dead   = fltarr(nn,nenergy,nmass) & dead[*]=1.

	energy2  = reform(reform(total(reform(nrg,n_swp,avg_nrg,nenergy),2)/avg_nrg,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)
	denergy2 = reform(reform(total(reform(dnrg,n_swp,avg_nrg,nenergy),2)       ,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)

;	gf[n_swp,64,16,16,4]
	gf2 = fltarr(n_swp,nenergy,4)
	gf1 = total(reform(gf,n_swp,avg_nrg,nenergy,16,16,4),2)/avg_nrg
	for i=0,n_swp-1 do gf2[i,*,*] = avg_an*total(total(gf1[i,*,swp2gfdf[i,0]:swp2gfdf[i,1],swp2gfan[i,0]:swp2gfan[i,1],*],3),3)/(swp2gfdf[i,1]-swp2gfdf[i,0]+1.)/(swp2gfan[i,1]-swp2gfan[i,0]+1)

; kluge for pre-MOI solar wind -- assume all counts are through mech attenuator when activated
;	factor of 50 is because mech attenuator is factor of 100, but only covers half the FOV
	if first_t lt time_double('2014-09-01/0') then begin
		if keyword_set(gf_nor) then begin
			for i=0,n_swp-1 do gf2[i,*,2]=gf2[i,*,2]/50.
			for i=0,n_swp-1 do gf2[i,*,3]=gf2[i,*,3]/50.
		endif else begin
			gf2[3:4,*,2]=gf2[3:4,*,2]/50.
			gf2[3:4,*,3]=gf2[3:4,*,3]/50.
			gf2[7:8,*,2]=gf2[7:8,*,2]/50.
			gf2[7:8,*,3]=gf2[7:8,*,3]/50.
		endelse
	endif
; the following assumes that if the mechanical attenuator is closed, then the particles are attenuated in all modes 
;	compensates for swp2gfan[*,0:1]=[0,15] in pickup,eclipse,scan,protect modes. - see definintion of att_corr 
	if first_t ge time_double('2014-09-01/0') then begin
			gf2[3:4,*,2]=gf2[3:4,*,2]*att_corr
			gf2[3:4,*,3]=gf2[3:4,*,3]*att_corr
			gf2[7:8,*,2]=gf2[7:8,*,2]*att_corr
			gf2[7:8,*,3]=gf2[7:8,*,3]*att_corr
			gf2[11:14,*,2]=gf2[11:14,*,2]*att_corr
			gf2[11:14,*,3]=gf2[11:14,*,3]*att_corr
			gf2[17:20,*,2]=gf2[17:20,*,2]*att_corr
			gf2[17:20,*,3]=gf2[17:20,*,3]*att_corr
			gf2[23:26,*,2]=gf2[23:26,*,2]*att_corr
			gf2[23:26,*,3]=gf2[23:26,*,3]*att_corr
	endif

; the following line assumes a constant efficiency as a default until other calibration code can be developed
;    a proper efficiency calibration is handled mvn_sta_dead_load.pro

	eff2 = fltarr(128,nenergy,nmass) & eff2[*]=def_eff  & eff_ind=intarr(nn)

;	mlut = md2mlut(md1)
	mlut = swp2mlut(swp_ind)
	mass_arr=total(total(reform(mas,n_swp,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	tof_arr=total(total(reform(tof,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	twt_arr=total(total(reform(twt,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/avg_nrg

	theta = fltarr(n_swp,nenergy,nmass) & theta[*]=0.
	dtheta = reform(reform(total(reform(abs(def(*,*,15)-def(*,*,0)),n_swp,avg_nrg,nenergy),2),n_swp*nenergy)#replicate(1.,nmass),n_swp,nenergy,nmass)/avg_nrg
	phi = fltarr(n_swp,nenergy,nmass) & phi[*]=0.
	dphi = fltarr(n_swp,nenergy,nmass) & dphi(*)=360.
	domega = dphi*dtheta/!radeg^2

	c4_dat= {project_name:		'MAVEN',				$
		spacecraft:		'0', 					$
;		data_name:		'C4 Energy-Mass', 			$
;		apid:			'C4',					$
		data_name:		'c4 4e64m', 				$
		apid:			'c4',					$
		units_name: 		'counts', 				$
		units_procedure: 	'mvn_sta_convert_units', 		$
		valid: 			replicate(1,nn), 			$
		quality_flag: 		quality_flag, 				$

		time:			tt1,					$
		end_time:		tt2,					$
		delta_t:		tt2-tt1,				$
		integ_t: 		(tt2-tt1)/(nenergy*ndef)*dt_cor,	$	

		eprom_ver:		eprom_ver,				$
		header:			header,					$
		mode:			md2,					$
		rate:			rt2,					$
		swp_ind:		swp_ind,				$
		mlut_ind:		mlut,					$
		eff_ind:		eff_ind,				$
		att_ind:		att0,					$

		nenergy: 		nenergy,				$
		energy: 		energy2, 				$
		denergy: 		denergy2, 				$

		nbins: 			nbins, 					$
		bins: 			replicate(1,nbins), 			$
		ndef:			ndef,					$
		nanode:			nanode,					$

		theta: 			theta,  				$
		dtheta: 		dtheta,  				$
		phi: 			phi,  					$
		dphi: 			dphi, 					$
		domega: 		domega,  				$

		gf: 			gf2, 					$
		eff: 			eff2,	 				$

		geom_factor: 		geom_factor,				$
		dead1: 			dead1,					$
		dead2: 			dead2,					$
		dead3: 			dead3,					$

		nmass:			nmass,					$
		mass: 			1.0438871e-02, 				$
		mass_arr:		mass_arr,				$
		tof_arr:		tof_arr,				$
		twt_arr:		twt_arr,				$

		charge: 		1., 					$
		sc_pot: 		replicate(0.,nn),			$
		magf:	 		magf, 					$
		quat_sc:	 	quat_sc, 				$
		quat_mso:	 	quat_mso, 				$
		bins_sc:		bins_sc,				$
		pos_sc_mso:		pos_sc_mso,				$

		bkg:	 		bkg,		 			$
		dead:	 		dead,		 			$

		data:			tmp}

		common mvn_c4,mvn_c4_ind,mvn_c4_dat & mvn_c4_dat=c4_dat & mvn_c4_ind=0l

   endif
endif


;***************************************************************************************************************
; APID C8

if keyword_set(apids) then test = fix((total(apids eq 'c8') + total(apids eq 'C8')) < 1) else test=0
if not keyword_set(apids) or test then begin
print,'Processing apid c8'

	nn=0
	get_data,'mvn_STA_C8_DATA',data=t
	if size(/type,t) eq 8 then begin
		npts=512									; 32Ex16Dx1Ax1M
		ind1 = where(t.x gt 0, nn)
		tt=t.x[0:nn-1]
	if nn ge 2 then begin

		get_data,'mvn_STA_C8_DIAG',data=diag

;		correct half second jitter in header times, assumes times always delayed by .5, assumes C0 has 4 sec cadence
			time = tt
			dt = time[1:nn-1]-time[0:nn-2]-4.
			ind8 = where( .4 lt dt and dt lt .6,cnt8)
				c8_cnt8=cnt8
			for i=0,cnt8-1 do for j=0,1 do time[ind8[i]+j+1] = time[ind8[i]+j+1] - .5d
			dt = time[1:nn-1]-time[0:nn-2]-4.
			ind9 = where( -.6 lt dt and dt lt -.4,cnt9)
				c8_cnt9=cnt9
			for i=0,cnt9-1 do for j=0,1 do time[ind9[i]-j] = time[ind9[i]-j] - .5d
			ind10 = where((.4 lt dt and dt lt .6) or (-.6 lt dt and dt lt -.4),cnt10)
				c8_cnt10=cnt10
			if cnt10 gt 0 then c8_jitter_flag=1
			tt = time

		get_data,'mvn_STA_C8_MODE',data=md
			md1 = md.y[0:nn-1] and 127
			md2 = md.y[0:nn-1] and 15
			rt2 = (md.y[0:nn-1] and 112)/16

		get_data,'mvn_STA_C8_AVG',data=cavg
		avg = 2^(cavg.y and replicate(7,nn))
		sum = (cavg.y and replicate(8,nn))/8
			avg2 = sum*avg > 1

		comp = (cavg.y and replicate(192,nn))/128
		ind = where(avg[0:nn-2] ne avg[1:nn-1],count)
		if count ne 0 then begin
			for i=0,count-1 do begin
				a0 = avg[ind[i]]
				a1 = avg[ind[i]+1]
				dt = a1*4.
				nf = abs(round( ( (tt[ind[i]+1]-tt[ind[i]])/4. -(a0+a1)/2. ) /(a1-a0) ))
				if nf gt 1 then nf=0
				for j=ind[i]-nf+1,ind[i] do begin
					tt[j]=tt[ind[i]+1]-dt*(ind[i]+1-j)
					avg2[j]=avg2[ind[i]+1]
					md2[j]=md2[ind[i]+1]
					rt2[j]=rt2[ind[i]+1]
					md1[j]=md1[ind[i]+1]
				endfor
			endfor
		endif

;	correct C8 mode transitions using C6 data if it is available
		get_data,'mvn_sta_C6_mode',data=md6
		if size(/type,md6) eq 8 then begin
			get_data,'mvn_sta_C6_rate',data=rt6
			md2 = fix(round(interp(md6.y,md6.x,tt)))
			rt2 = fix(round(interp(rt6.y,rt6.x,tt)))
		endif
		md1 = rt2*16+md2	 

			tt1 = tt - 2.*avg2 								; corrected timing for averaging, kluge for header mismatch
			tt2 = tt + 2.*avg2 
			if nn gt 2 then begin
				tt2[0:nn-2] = tt2[0:nn-2] < tt1[1:nn-1]
				tt3 = (tt1 + tt2)/2.
;				print,'C0 correction for averaging error: tt3-tt = ',tt3-tt
				tt = tt3
			endif


		get_data,'mvn_STA_C8_ATTEN',data=catt						; set attenuator state
		att1 = (catt.y[0:nn-1] and replicate(192,nn))/64
		att0 = att1
		store_data,'mvn_STA_C8_att_s',data={x:tt,y:att1}
		att2 = (catt.y[0:nn-1] and replicate(48,nn))/16
		store_data,'mvn_STA_C8_att_e',data={x:tt,y:att2}
		att3 = (catt.y[0:nn-1] and replicate(15,nn))
		store_data,'mvn_STA_C8_att_w',data={x:tt,y:att3}
		ind0 = where(att1[0:nn-2] ne att1[1:nn-1],cnt0)					; find att transitions
		if cnt0 ne 0 then begin
			nmax = 1024/npts
			for i=0,cnt0-1 do begin
				inds = ind0[i]
				if att3[inds] ge nmax then print,'APID C8 packet header error: WWWW too large, wwww=',att3[inds]
;				idelay = fix(2/avg[inds])					; observed internal delays of 2 x 4sec, hence the "2"
				idelay = fix(2/avg2[inds])					; observed internal delays of 2 x 4sec, hence the "2"
				iww = att3[inds] - 1
				if iww lt 0 then iww = nmax-1
				att0[inds-nmax+1:inds] = att1[inds+1] 				; replace transition att w/ next value
				att0[inds-nmax+1:inds-nmax+1+iww+idelay] = att1[inds]		; use ww and interal delays to correct att at previous value
			endfor
		endif

;	correct C8 attenuator transitions using C6 data if it is available
		get_data,'mvn_sta_C6_att',data=att6
		if size(/type,att6) eq 8 then att0 = fix(round(interp(att6.y,att6.x,tt)))<3

		header = 256l^3*md.y[0:nn-1] + 256l^2*cavg.y[0:nn-1] + 256l*catt.y[0:nn-1] + diag.y[0:nn-1]

		store_data,'mvn_sta_C8_mode',data={x:tt,y:md2}
			ylim,'mvn_sta_C8_mode',-1,7,0
		store_data,'mvn_sta_C8_rate',data={x:tt,y:rt2}					; corrected modes
			ylim,'mvn_sta_C8_rate',-1,8,0
		store_data,'mvn_sta_C8_att',data={x:tt,y:att0}
			ylim,'mvn_sta_C8_att',-1,4,0

;		swp_ind = md2swp[md1]									; old version
;		swp_ind = conf2swp[fix(interp((config4.y and 255)*1.,config4.x,tt)+.5),md2]					
		swp_ind = conf2swp[fix(interp((config4.y and 511)*1.,config4.x,tt)+.5),md2]					
			eprom_ver = fix(interp((config4.y and 255)*1.,config4.x,tt)+.5)
			if tt[0] lt time_double('2014-10-1/0') then eprom_ver[*]=0

		energy=nrg[swp_ind,*]
		energy=total(reform(energy,nn,2,32),2)/2.
		deflection = reform(def[swp_ind,62,*],nn,16)

		tmp=decomp19[transpose(reform(t.y[0:nn-1,*],nn,16,32),[0,2,1])]			; [time,en,def]

		store_data,'mvn_sta_C8_P2_E',data={x:tt,y:total(tmp,3),v:energy}
		store_data,'mvn_sta_C8_P2_D',data={x:tt,y:total(tmp,2),v:deflection}
		store_data,'mvn_sta_C8_P2_tot',data={x:tt,y:total(total(tmp,2),2)}
		store_data,'mvn_sta_C8_P2_all',data={x:tt,y:reform(tmp,nn,npts),v:findgen(npts)}

		ylim,'mvn_sta_C8_P2_tot',0,0,1
		ylim,'mvn_sta_C8_P2_E',.4,40000.,1
		ylim,'mvn_sta_C8_P2_D',-45,45,0
		zlim,'mvn_sta_C8_P2_E',1,1.e4,1
		zlim,'mvn_sta_C8_P2_D',1,1.e4,1
		options,'mvn_sta_C8_P2_E',datagap=64.
		options,'mvn_sta_C8_P2_D',datagap=64.
		options,'mvn_sta_C8_P2_tot',datagap=64.
		options,'mvn_sta_C8_P2_E','spec',1
		options,'mvn_sta_C8_P2_D','spec',1
		options,'mvn_sta_C8_P2_E',ytitle='sta!CP2-C8!C!CEnergy!CeV'
		options,'mvn_sta_C8_P2_D',ytitle='sta!CP2-C8!C!CDef!Ctheta'
	endif
	endif

; Make C8 common block

   if size(/type,t) eq 8 and nn ge 2 then begin

	nenergy = 32
	avg_nrg = 64/nenergy
	ndef = 16
	avg_def=16/ndef
	nanode = 1
	avg_an = 16/nanode
	nbins = ndef*nanode
	nmass = 1

	magf = replicate(0.,nn)#[0.,0.,0.]
	quat_sc  = replicate(0.,nn)#[0.,0.,0.,0.]
	quat_mso = replicate(0.,nn)#[0.,0.,0.,0.]
	bins_sc = fix(replicate(1,nn)#replicate(1,nbins))
	quality_flag = intarr(nn)
	pos_sc_mso = replicate(0.,nn)#[0.,0.,0.]
	bkg   = fltarr(nn,nenergy,nbins,nmass)
	dead   = fltarr(nn,nenergy,nbins,nmass) & dead[*]=1.

;	energy2  = reform(reform(total(reform(nrg,n_swp,avg_nrg,nenergy),2)/avg_nrg,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)
;	denergy2 = reform(reform(total(reform(dnrg,n_swp,avg_nrg,nenergy),2)       ,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)

	an_ma = replicate(1.,nbins*nmass) 
	energy2  = reform(reform(total(reform(nrg,n_swp,avg_nrg,nenergy),2)/avg_nrg,n_swp*nenergy) # an_ma,n_swp,nenergy,nbins,nmass)
	denergy2 = reform(reform(total(reform(dnrg,n_swp,avg_nrg,nenergy),2)       ,n_swp*nenergy) # an_ma,n_swp,nenergy,nbins,nmass)

;	gf[n_swp,64,16,16,4]	sum geometric factor over energy, deflection and anode, why is there a normalization???????				; gf[iswp,en,def,an,att]
;	gf2 = reform(total(total(reform(gf,n_swp,avg_nrg,nenergy,avg_def,ndef,16,4),4),2),n_swp,nenergy,nbins,4)/avg_nrg/avg_def			;

;	gf2 = avg_an*reform(total(total(reform(gf,n_swp,avg_nrg,nenergy,ndef,16,4),5),2),n_swp,nenergy,nbins,4)/avg_nrg			;

	gf2 = fltarr(n_swp,nenergy,ndef,4)
	gf1 = total(reform(gf,n_swp,avg_nrg,nenergy,16,16,4),2)/avg_nrg
	for i=0,n_swp-1 do gf2[i,*,*,*] = avg_an*total(gf1[i,*,*,swp2gfan[i,0]:swp2gfan[i,1],*],4)/(swp2gfan[i,1]-swp2gfan[i,0]+1)

; kluge for pre-MOI solar wind -- assume all counts are through mech attenuator when activated
;	factor of 50 is because mech attenuator is factor of 100, but only covers half the FOV
	if first_t lt time_double('2014-09-01/0') then begin
		if keyword_set(gf_nor) then begin
			for i=0,n_swp-1 do gf2[i,*,*,2]=gf2[i,*,2]/50.
			for i=0,n_swp-1 do gf2[i,*,*,3]=gf2[i,*,3]/50.
		endif else begin
			gf2[3:4,*,*,2]=gf2[3:4,*,*,2]/50.
			gf2[3:4,*,*,3]=gf2[3:4,*,*,3]/50.
			gf2[7:8,*,*,2]=gf2[7:8,*,*,2]/50.
			gf2[7:8,*,*,3]=gf2[7:8,*,*,3]/50.
		endelse
	endif
; the following assumes that if the mechanical attenuator is closed, then the particles are attenuated except for pickup, eclipse and protect modes 
;     note that scan mode (iswp=24) is used near planet when ram ions are in mech attenuator direction and therefore should not have this correction 
	if first_t ge time_double('2014-09-01/0') then begin
			gf2[3:4  ,*,*,2]=gf2[3:4  ,*,*,2]*att_corr
			gf2[3:4  ,*,*,3]=gf2[3:4  ,*,*,3]*att_corr
			gf2[7:8  ,*,*,2]=gf2[7:8  ,*,*,2]*att_corr
			gf2[7:8  ,*,*,3]=gf2[7:8  ,*,*,3]*att_corr
			gf2[11:14,*,*,2]=gf2[11:14,*,*,2]*att_corr
			gf2[11:14,*,*,3]=gf2[11:14,*,*,3]*att_corr
			gf2[17:20,*,*,2]=gf2[17:20,*,*,2]*att_corr
			gf2[17:20,*,*,3]=gf2[17:20,*,*,3]*att_corr
			gf2[23:26,*,*,2]=gf2[23:26,*,*,2]*att_corr
			gf2[23:26,*,*,3]=gf2[23:26,*,*,3]*att_corr
	endif


; the following line assumes a constant efficiency as a default until other calibration code can be developed
;    a proper efficiency calibration is handled mvn_sta_dead_load.pro

	eff2 = fltarr(128,nenergy,nbins,nmass) & eff2=reform(eff2,128,nenergy,nbins,nmass) & eff2[*]=def_eff  & eff_ind=intarr(nn)

;	mlut = md2mlut(md1)
	mlut = swp2mlut(swp_ind)
	mass_arr=total(total(reform(mas,n_swp,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	tof_arr=total(total(reform(tof,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	twt_arr=total(total(reform(twt,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/avg_nrg

	mass_arr=transpose(reform(reform(mass_arr,n_swp*nenergy*nmass)#replicate(1.,nbins),n_swp,nenergy,nmass,nbins),[0,1,3,2])
	tof_arr=transpose(reform(reform(tof_arr,n_mlut*nenergy*nmass)#replicate(1.,nbins),n_mlut,nenergy,nmass,nbins),[0,1,3,2])
	twt_arr=transpose(reform(reform(twt_arr,n_mlut*nenergy*nmass)#replicate(1.,nbins),n_mlut,nenergy,nmass,nbins),[0,1,3,2])
; TBD ?????????????? - eventually assume energy dependent mass based on ram velocity
	mass_arr[*] = 32.	; for now assume a default mass is O2+, ignore tof_arr and twt_arr.

; the following uses def(n_swp,64,16) to generate theta and phi arrays that depend on iswp(md1)

;theta and phi are screwed up????????????????????
	theta = reform(reform(total(total(reform(def,n_swp,avg_nrg,nenergy,avg_def,ndef),4),2),n_swp*nenergy*ndef)#replicate(1.,nanode*nmass),n_swp,nenergy,nbins,nmass)/avg_nrg/avg_def
	dtheta = reform(reform(total(reform(abs(def(*,*,15)-def(*,*,0))/(15.),n_swp,avg_nrg,nenergy),2),n_swp*nenergy)#replicate(1.,nbins*nmass),n_swp,nenergy,nbins,nmass)/avg_nrg*avg_def
;	phi = 0.
;	dphi = 360.
	phi = fltarr(n_swp,nenergy,nbins,nmass) & phi[*]=0.
	dphi = fltarr(n_swp,nenergy,nbins,nmass) & dphi(*)=360.
	domega = dphi*dtheta/!radeg^2 


;	print,n_swp,nenergy,nbins,nmass
; don't know why this line won't work
;	reform(domega,n_swp,nenergy,nbins,nmass)


	c8_dat= {project_name:		'MAVEN',				$
		spacecraft:		'0', 					$
;		data_name:		'C8 Energy-Angle-Mass', 		$
;		apid:			'C8',					$
		data_name:		'c8 32e16d', 				$
		apid:			'c8',					$
		units_name: 		'counts', 				$
		units_procedure: 	'mvn_sta_convert_units', 		$
		valid: 			replicate(1,nn), 			$
		quality_flag: 		quality_flag, 				$

		time:			tt1,					$
		end_time:		tt2,					$
		delta_t:		tt2-tt1,				$
		integ_t: 		(tt2-tt1)/(nenergy*ndef)*dt_cor,	$	

		eprom_ver:		eprom_ver,				$
		header:			header,					$
		mode:			md2,					$
		rate:			rt2,					$
		swp_ind:		swp_ind,				$
		mlut_ind:		mlut,					$
		eff_ind:		eff_ind,				$
		att_ind:		att0,					$

		nenergy: 		nenergy,				$
		energy: 		energy2, 				$
		denergy: 		denergy2, 				$

		nbins: 			nbins, 					$
		bins: 			replicate(1,nbins), 			$
		ndef:			ndef,					$
		nanode:			nanode,					$

		theta: 			theta,  				$
		dtheta: 		dtheta,  				$
		phi: 			phi,  					$
		dphi: 			dphi, 					$
		domega: 		domega,  				$

		gf: 			gf2, 					$
		eff: 			eff2,	 				$

		geom_factor: 		geom_factor,				$
		dead1: 			dead1,					$
		dead2: 			dead2,					$
		dead3: 			dead3,					$

		nmass:			nmass,					$
		mass: 			1.0438871e-02, 				$
		mass_arr:		mass_arr,				$
		tof_arr:		tof_arr,				$
		twt_arr:		twt_arr,				$

		charge: 		1., 					$
		sc_pot: 		replicate(0.,nn),			$
		magf:	 		magf, 					$
		quat_sc:	 	quat_sc, 				$
		quat_mso:	 	quat_mso, 				$
		bins_sc:		bins_sc,				$
		pos_sc_mso:		pos_sc_mso,				$

		bkg:	 		bkg,		 			$
		dead:	 		dead,		 			$

		data:			reform(tmp,nn,nenergy,nbins,nmass)}

		common mvn_c8,mvn_c8_ind,mvn_c8_dat & mvn_c8_dat=c8_dat & mvn_c8_ind=0l

   endif
endif


;***************************************************************************************************************
; APID CA


if keyword_set(apids) then test = fix((total(apids eq 'ca') + total(apids eq 'CA')) < 1) else test=0
if not keyword_set(apids) or test then begin
print,'Processing apid ca'

	nn=0
	get_data,'mvn_STA_CA_DATA',data=t
	if size(/type,t) eq 8 then begin
		npts=1024									; 16Ex4Dx16Ax1M
		ind1 = where(t.x gt 0, nn)
		tt=t.x[0:nn-1]
	if nn ge 2 then begin

		get_data,'mvn_STA_CA_DIAG',data=diag

;		correct half second jitter in header times, assumes times always delayed by .5, assumes CA has 4 sec cadence
			time = tt
			dt = time[1:nn-1]-time[0:nn-2]-4.
			ind8 = where( .4 lt dt and dt lt .6,cnt8)
				ca_cnt8=cnt8
			for i=0,cnt8-1 do time[ind8[i]+1] = time[ind8[i]+1] - .5d
			dt = time[1:nn-1]-time[0:nn-2]-4.
			ind9 = where( -.6 lt dt and dt lt -.4,cnt9)
				ca_cnt9=cnt9
			for i=0,cnt9-1 do time[ind9[i]] = time[ind9[i]] - .5d
			ind10 = where((.4 lt dt and dt lt .6) or (-.6 lt dt and dt lt -.4),cnt10)
				ca_cnt10=cnt10
			if cnt10 gt 0 then ca_jitter_flag=1
			tt = time

		get_data,'mvn_STA_CA_MODE',data=md
			md1 = md.y[0:nn-1] and 127
			md2 = md.y[0:nn-1] and 15
			rt2 = (md.y[0:nn-1] and 112)/16

		get_data,'mvn_STA_CA_AVG',data=cavg							; average state
			avg = 2^(cavg.y[0:nn-1] and 7)
			sum = (cavg.y[0:nn-1] and 8)/8

			avg2 = sum*avg > 1

; the following seems to be working to handle headers out of phase with the data

			ind = where(md2[0:nn-2] ne md2[1:nn-1],nch)	
			if nch gt 0 then begin							; this is required because config headers are out of phase w/ data
				for ii=0,nch-1 do begin	
					for jj=1,3/avg[ind[ii]] do begin			; 1/avg is generally not needed, but might need adjusting if we ever average C6 packets in time
						if ind[ii]+jj le nn-1 then begin
							avg2[ind[ii]+jj]=avg2[ind[ii]]
							md2[ind[ii]+jj]=md2[ind[ii]]
							rt2[ind[ii]+jj]=rt2[ind[ii]]
							md1[ind[ii]+jj]=md1[ind[ii]]
						endif
					endfor
				endfor
			endif

;	correct CA mode transitions using C6 data if it is available

		get_data,'mvn_sta_C6_mode',data=md6
		if size(/type,md6) eq 8 then begin
			get_data,'mvn_sta_C6_rate',data=rt6
			md2 = fix(round(interp(md6.y,md6.x,tt)))
			rt2 = fix(round(interp(rt6.y,rt6.x,tt)))
		endif
		md1 = rt2*16+md2	 

		tt1 = tt - 2.*avg2								; corrected timing for averaging
		tt2 = tt + 2.*avg2
		if nn gt 2 then begin
			tt2[0:nn-2] = tt2[0:nn-2] < tt1[1:nn-1]
			tt3 = (tt1 + tt2)/2.
			tt = tt3
		endif


		get_data,'mvn_STA_CA_ATTEN',data=catt						; attenuator state
		att0 = (catt.y[0:nn-1] and replicate(192,nn))/64
		ind0 = where(att0[0:nn-2] ne att0[1:nn-1],cnt0)
		if cnt0 ne 0 then begin
			for i=0,cnt0-1 do begin
				inds = ind0[i]
				idelay = fix(2/avg2[inds])					; observed internal delays of 2 x 4sec, hence the "2"
				if idelay gt 0 then att0[inds+1:(inds+idelay)<(nn-1)] = att0[inds]
			endfor
		endif

;	correct CA attenuator transitions using C6 data if it is available
		get_data,'mvn_sta_C6_att',data=att6
		if size(/type,att6) eq 8 then att0 = fix(round(interp(att6.y,att6.x,tt)))<3

		header = 256l^3*md.y[0:nn-1] + 256l^2*cavg.y[0:nn-1] + 256l*catt.y[0:nn-1] + diag.y[0:nn-1]

		store_data,'mvn_sta_CA_mode',data={x:tt,y:md2}
			ylim,'mvn_sta_CA_mode',-1,7,0
		store_data,'mvn_sta_CA_rate',data={x:tt,y:rt2}					; corrected modes
			ylim,'mvn_sta_CA_rate',-1,8,0
		store_data,'mvn_sta_CA_att',data={x:tt,y:att0}
			ylim,'mvn_sta_CA_att',-1,4,0

;		swp_ind = md2swp[md1]									; old version
;		swp_ind = conf2swp[fix(interp((config4.y and 255)*1.,config4.x,tt)+.5),md2]					
		swp_ind = conf2swp[fix(interp((config4.y and 511)*1.,config4.x,tt)+.5),md2]					
			eprom_ver = fix(interp((config4.y and 255)*1.,config4.x,tt)+.5)
			if tt[0] lt time_double('2014-10-1/0') then eprom_ver[*]=0

		energy=nrg[swp_ind,*]
		energy=total(reform(energy,nn,4,16),2)/4.
		deflection = total(reform(def[swp_ind,62,*],nn,4,4),2)/4.

		tmp=decomp19[transpose(reform(t.y[0:nn-1,*],nn,16,4,16),[0,3,2,1])]		; [time,en,def,an]

		store_data,'mvn_sta_CA_P3_E',data={x:tt,y:total(total(tmp,4),3),v:energy}
		store_data,'mvn_sta_CA_P3_D',data={x:tt,y:total(total(tmp,4),2),v:deflection}
		store_data,'mvn_sta_CA_P3_A',data={x:tt,y:total(total(tmp,3),2),v:22.5*(findgen(16)-7.)}
		store_data,'mvn_sta_CA_P3_tot',data={x:tt,y:total(total(total(tmp,2),2),2)}
		store_data,'mvn_sta_CA_P3_all',data={x:tt,y:reform(tmp,nn,npts),v:findgen(npts)}

		ylim,'mvn_sta_CA_P3_tot',0,0,1
		ylim,'mvn_sta_CA_P3_E',.4,40000.,1
		ylim,'mvn_sta_CA_P3_D',-45,45,0
		ylim,'mvn_sta_CA_P3_A',-180,200,0
		zlim,'mvn_sta_CA_P3_E',1,1.e4,1
		zlim,'mvn_sta_CA_P3_D',1,1.e4,1
		zlim,'mvn_sta_CA_P3_A',1,1.e4,1
		options,'mvn_sta_CA_P3_E',datagap=64.
		options,'mvn_sta_CA_P3_D',datagap=64.
		options,'mvn_sta_CA_P3_A',datagap=64.
		options,'mvn_sta_CA_P3_tot',datagap=64.
		options,'mvn_sta_CA_P3_E','spec',1
		options,'mvn_sta_CA_P3_D','spec',1
		options,'mvn_sta_CA_P3_A','spec',1
		options,'mvn_sta_CA_P3_E',ytitle='sta!CP3-CA!C!CEnergy!CeV'
		options,'mvn_sta_CA_P3_D',ytitle='sta!CP3-CA!C!CDef!Ctheta'
		options,'mvn_sta_CA_P3_A',ytitle='sta!CP3-CA!C!CAnode!Cphi'
	endif
	endif


; Make CA common block

   if size(/type,t) eq 8 and nn ge 2 then begin

	nenergy = 16									; 16Ex4Dx16Ax1M
	avg_nrg = 64/nenergy
	ndef = 4
	avg_def=16/ndef
	nanode = 16
	avg_an = 16/nanode
	nbins = ndef*nanode
	nmass = 1

	magf = replicate(0.,nn)#[0.,0.,0.]
	quat_sc  = replicate(0.,nn)#[0.,0.,0.,0.]
	quat_mso = replicate(0.,nn)#[0.,0.,0.,0.]
	bins_sc = fix(replicate(1,nn)#replicate(1,nbins))
	quality_flag = intarr(nn)
	pos_sc_mso = replicate(0.,nn)#[0.,0.,0.]
	bkg   = fltarr(nn,nenergy,nbins,nmass)
	dead   = fltarr(nn,nenergy,nbins,nmass) & dead[*]=1.

;	energy2  = reform(reform(total(reform(nrg,n_swp,avg_nrg,nenergy),2)/avg_nrg,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)
;	denergy2 = reform(reform(total(reform(dnrg,n_swp,avg_nrg,nenergy),2)       ,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)

	an_ma = replicate(1.,nbins*nmass) 
	energy2  = reform(reform(total(reform(nrg,n_swp,avg_nrg,nenergy),2)/avg_nrg,n_swp*nenergy) # an_ma,n_swp,nenergy,nbins)
	denergy2 = reform(reform(total(reform(dnrg,n_swp,avg_nrg,nenergy),2)       ,n_swp*nenergy) # an_ma,n_swp,nenergy,nbins)

;	gf[n_swp,64,16,16,4]	sum geometric factor over energy, deflection and anode, why is there a normalization???????				; gf[iswp,en,def,an,att]
;	gf2 = reform(total(total(reform(gf,n_swp,avg_nrg,nenergy,avg_def,ndef,16,4),4),2),n_swp,nenergy,nbins,4)/avg_nrg/avg_def			;
	gf2 = reform(total(total(reform(gf,n_swp,avg_nrg,nenergy,avg_def,ndef,16,4),4),2),n_swp,nenergy,nbins,4)/(avg_nrg*avg_def)			;


; the following line assumes a constant efficiency as a default until other calibration code can be developed
;    a proper efficiency calibration is handled mvn_sta_dead_load.pro

	eff2 = fltarr(128,nenergy,nbins) & eff2[*]=def_eff  & eff_ind=intarr(nn)

;	mlut = md2mlut(md1)
	mlut = swp2mlut(swp_ind)
	mass_arr=total(total(reform(mas,n_swp,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	tof_arr=total(total(reform(tof,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	twt_arr=total(total(reform(twt,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/avg_nrg

	mass_arr=transpose(reform(reform(mass_arr,n_swp*nenergy*nmass)#replicate(1.,nbins),n_swp,nenergy,nmass,nbins),[0,1,3,2])
	tof_arr=transpose(reform(reform(tof_arr,n_mlut*nenergy*nmass)#replicate(1.,nbins),n_mlut,nenergy,nmass,nbins),[0,1,3,2])
	twt_arr=transpose(reform(reform(twt_arr,n_mlut*nenergy*nmass)#replicate(1.,nbins),n_mlut,nenergy,nmass,nbins),[0,1,3,2])

; the following uses def(n_swp,64,16) to generate theta and phi arrays that depend on iswp(md1)

; check the following????????????  - bug in theta - off by factor of 3???
;	theta = reform(reform(total(total(reform(def,n_swp,avg_nrg,nenergy,avg_def,ndef),4),2),n_swp*nenergy*ndef)#replicate(1.,nanode*nmass),n_swp,nenergy,nbins)/avg_nrg/avg_def
;	dtheta = reform(reform(total(reform(abs(def(*,*,15)-def(*,*,0))/(15.),n_swp,avg_nrg,nenergy),2),n_swp*nenergy)#replicate(1.,nbins*nmass),n_swp,nenergy,nbins)/avg_nrg
;	phi = 22.5*reform(reform(replicate(1.,n_swp*nenergy*ndef)#(findgen(nanode)-7.),1l*n_swp*nenergy*nbins)#replicate(1.,nmass),n_swp,nenergy,nbins)
;	dphi = fltarr(n_swp,nenergy,nbins,nmass) & dphi(*)=22.5

	theta = reform(reform(total(total(reform(def,n_swp,avg_nrg,nenergy,avg_def,ndef),4),2),n_swp*nenergy*ndef)#replicate(1.,nanode),n_swp,nenergy,nbins)/avg_nrg/avg_def
	dtheta = reform(reform(total(reform(abs(def(*,*,15)-def(*,*,0))/(15.),n_swp,avg_nrg,nenergy),2),n_swp*nenergy)#replicate(1.,nbins),n_swp,nenergy,nbins)/avg_nrg*avg_def
	phi = 22.5*reform(replicate(1.,n_swp*nenergy*ndef)#(findgen(nanode)-7.),n_swp,nenergy,nbins)
	dphi = fltarr(n_swp,nenergy,nbins) & dphi(*)=22.5
	domega = dphi*dtheta/!radeg^2

	ca_dat= {project_name:		'MAVEN',				$
		spacecraft:		'0', 					$
;		data_name:		'CA Energy-Angle-Mass', 		$
;		apid:			'CA',					$
		data_name:		'ca 16e4d16a', 				$
		apid:			'ca',					$
		units_name: 		'counts', 				$
		units_procedure: 	'mvn_sta_convert_units', 		$
		valid: 			replicate(1,nn), 			$
		quality_flag: 		quality_flag, 				$

		time:			tt1,					$
		end_time:		tt2,					$
		delta_t:		tt2-tt1,				$
		integ_t: 		(tt2-tt1)/(nenergy*ndef)*dt_cor,	$	

		eprom_ver:		eprom_ver,				$
		header:			header,					$
		mode:			md2,					$
		rate:			rt2,					$
		swp_ind:		swp_ind,				$
		mlut_ind:		mlut,					$
		eff_ind:		eff_ind,				$
		att_ind:		att0,					$

		nenergy: 		nenergy,				$
		energy: 		energy2, 				$
		denergy: 		denergy2, 				$

		nbins: 			nbins, 					$
		bins: 			replicate(1,nbins), 			$
		ndef:			ndef,					$
		nanode:			nanode,					$

		theta: 			theta,  				$
		dtheta: 		dtheta,  				$
		phi: 			phi,  					$
		dphi: 			dphi, 					$
		domega: 		domega,  				$

		gf: 			gf2, 					$
		eff: 			eff2,	 				$

		geom_factor: 		geom_factor,				$
		dead1: 			dead1,					$
		dead2: 			dead2,					$
		dead3: 			dead3,					$

		nmass:			nmass,					$
		mass: 			1.0438871e-02, 				$
		mass_arr:		mass_arr,				$
		tof_arr:		tof_arr,				$
		twt_arr:		twt_arr,				$

		charge: 		1., 					$
		sc_pot: 		replicate(0.,nn),			$
		magf:	 		magf, 					$
		quat_sc:	 	quat_sc, 				$
		quat_mso:	 	quat_mso, 				$
		bins_sc:		bins_sc,				$
		pos_sc_mso:		pos_sc_mso,				$

		bkg:	 		bkg,		 			$
		dead:	 		dead,		 			$

		data:			reform(tmp,nn,nenergy,nbins)}

		common mvn_ca,mvn_ca_ind,mvn_ca_dat & mvn_ca_dat=ca_dat & mvn_ca_ind=0l

   endif
endif


;***************************************************************************************************************
; APID CC


if keyword_set(apids) then test = fix((total(apids eq 'cc') + total(apids eq 'CC')) < 1) else test=0
if not keyword_set(apids) or test then begin
print,'Processing apid cc'

; the header bits (diagnostic, mode, averaging, atten) may be out of phase with the packet by one cycle - see "maven/ITF/ATLOData/ATLO/SelfTest/SelfTest_ATLO_20131001_pfp_all_l0_v1.dat"

	ndis=0
	get_data,'mvn_STA_CC_DATA',data=t
	if size(/type,t) eq 8 then begin
		npts=8192									; 32Ex8Dx1Ax32M
		np = 8										; np is number of packets per measurement
		ind1 = where(t.x gt 0, nn)
		tt=t.x[0:nn-1]

; 		find out-of-sequence times -- not expected for science data 
;			might occur if an averaging time is changed and the change does not occur on the correct 2^n boundary

; the following "if" makes sure there are at least two measurements so the out-of-order time correction works
	if nn ge 2*np then begin

		ind = where (tt[0:nn-1-np] gt tt[np:nn-1],nind)							
		if nind gt 0 then begin					
			print,' ERROR - times out of sequence, CC packet'  
			print,' # of out of sequence times = ',nind	
			for i=0,nind-1 do begin	
				print,i,tt[ind[i]]-tt[ind[i]+np],'  ',time_string(tt[ind[i]]),'  ',time_string(tt[ind[i]+np]),'  ',time_string(tt[ind[i]+2*np])
			endfor
		endif

;		form some diagnostic tplot structures

		get_data,'mvn_STA_CC_DIAG',data=diag
		en = (diag.y[0:nn-1] AND np-1)							
		dt=0.1
			store_data,'mvn_sta_CC_DIAG_EN',data={x:tt+en*dt,y:en}
				ylim,'mvn_sta_CC_DIAG_EN',-1,np,0
			get_data,'mvn_STA_CC_SEQ_CNTR',data=tmp2
			store_data,'mvn_sta_CC_SEQ_CNTR_EN',data={x:tt+en*dt,y:tmp2.y[0:nn-1]}
			store_data,'mvn_sta_CC_DATA_EN',data={x:tt+en*dt,y:total(t.y[0:nn-1,*],2)}

;		find index numbers for the first packets of a np packet set

;			ind1 = where(tt[0:nn-1-np] eq tt[np-1:nn-2],ndis1)					; make sure there are "np" packets in a row with same time, old code w/ error
			ind1 = where(tt[0:nn-np] eq tt[np-1:nn-1],ndis1)					; make sure there are "np" packets in a row with same time, changed 20140106

if ndis1 gt 1 then begin											; kluge for real time data stream which is missing too many packets

			ind2 = where(tt[ind1[0:ndis1-1]] le tt[[ind1[1:ndis1-1],ind1[ndis1-1]]],ndis)		; throw out any np-packet group that is out of time order, changed 20140106
			ind  = ind1[ind2] 						

			if ind[ndis-1]+2*np-1 eq nn-1 then begin
				ind=[ind,ind[ndis-1]+np]
				ndis=ndis+1
			endif




		if ndis ge 1 then begin

			aa = indgen(np)#replicate(1,ndis)							; extract out the proper complete packets
			bb = replicate(1,np)#ind
			dat = t.y[aa+bb,*]

			tdis = tt[ind[0:ndis-1]]

			get_data,'mvn_STA_CC_MODE',data=md
				md1 = md.y[ind[0:ndis-1]] and 127
				md2 = md.y[ind[0:ndis-1]]and 15
				rt2 = (md.y[ind[0:ndis-1]] and 112)/16

			get_data,'mvn_STA_CC_AVG',data=cavg
			avg = 2^(cavg.y[ind[0:ndis-1]] and 7)
			sum = (cavg.y[ind[0:ndis-1]] and 8)/8
			avg2 = sum*avg > 1


;	correct CC mode transitions using C6 data if it is available
		get_data,'mvn_sta_C6_mode',data=md6
		if size(/type,md6) eq 8 then begin
			get_data,'mvn_sta_C6_rate',data=rt6
			md2 = fix(round(interp(md6.y,md6.x,tdis)))
			rt2 = fix(round(interp(rt6.y,rt6.x,tdis)))
		endif
		md1 = rt2*16+md2	 

			tt1 = tdis - 2.*avg2 									; corrected timing for averaging, kluge for header mismatch
			tt2 = tdis + 2.*avg2 

			get_data,'mvn_STA_CC_ATTEN',data=catt						; attenuator state
			att0 = (catt.y[ind[0:ndis-1]] and replicate(192,ndis))/64
			if ndis ge 2 then ind0 = where(att0[0:ndis-2] ne att0[1:ndis-1],cnt0) else cnt0=0
			if cnt0 ne 0 then begin
				for i=0,cnt0-1 do begin
					inds = ind0[i]
					idelay = fix(2/avg[inds])
;					if idelay gt 0 then att0[inds+1:(inds+idelay)<(nn-1)] = att0[inds]
					if idelay gt 0 then att0[inds+1:(inds+idelay)<(ndis-1)] = att0[inds]
				endfor
			endif

;	correct CC attenuator transitions using C6 data if it is available
		get_data,'mvn_sta_C6_att',data=att6
		if size(/type,att6) eq 8 then att0 = fix(round(interp(att6.y,att6.x,tdis)))<3

			header = 256l^3*md.y[ind[0:ndis-1]] + 256l^2*cavg.y[ind[0:ndis-1]] + 256l*catt.y[ind[0:ndis-1]] + diag.y[ind[0:ndis-1]]

			store_data,'mvn_sta_CC_mode',data={x:tdis,y:md2}
				ylim,'mvn_sta_CC_mode',-1,7,0
			store_data,'mvn_sta_CC_att',data={x:tdis,y:att0}
				ylim,'mvn_sta_CC_att',-1,4,0

;			swp_ind = md2swp[md1]									; old version
;			swp_ind = conf2swp[fix(interp((config4.y and 255)*1.,config4.x,tdis)+.5),md2]					
			swp_ind = conf2swp[fix(interp((config4.y and 511)*1.,config4.x,tdis)+.5),md2]					
				eprom_ver = fix(interp((config4.y and 255)*1.,config4.x,tdis)+.5)
				if tdis[0] lt time_double('2014-10-1/0') then eprom_ver[*]=0

			energy=nrg[swp_ind,*]
			energy=total(reform(energy,ndis,2,32),2)/2.
			mass=mas[swp_ind,0,*]
			mass=total(reform(mass,ndis,2,32),2)/2.						; because there are only 32 masses
			deflection = total(reform(def[swp_ind,62,*],ndis,2,8),2)/2.

			tmp=decomp19[reform(transpose(reform(dat,np,ndis,32,8,4),[1,4,0,3,2]),ndis,32,8,32)]		; [time,en,def,ma]

			store_data,'mvn_sta_CC_P4A_E',data={x:tdis,y:total(total(tmp,4),3),v:energy}
			store_data,'mvn_sta_CC_P4A_D',data={x:tdis,y:total(total(tmp,4),2),v:deflection}
			store_data,'mvn_sta_CC_P4A_M',data={x:tdis,y:total(total(tmp,2),2),v:mass}
			store_data,'mvn_sta_CC_P4A_tot',data={x:tdis,y:total(total(total(tmp,4),3),2)}
			store_data,'mvn_sta_CC_P4A_all',data={x:tdis,y:reform(tmp,ndis,npts),v:indgen(npts)}

			ylim,'mvn_sta_CC_P4A_tot',0,0,1
			ylim,'mvn_sta_CC_P4A_E',.4,40000.,1
			ylim,'mvn_sta_CC_P4A_D',-45,45,0
			ylim,'mvn_sta_CC_P4A_M',.5,100,1
			zlim,'mvn_sta_CC_P4A_E',1,1.e5,1
			zlim,'mvn_sta_CC_P4A_D',1,1.e5,1
			zlim,'mvn_sta_CC_P4A_M',1,1.e5,1
			options,'mvn_sta_CC_P4A_E',datagap=128.
			options,'mvn_sta_CC_P4A_D',datagap=128.
			options,'mvn_sta_CC_P4A_M',datagap=128.
			options,'mvn_sta_CC_P4A_tot',datagap=128.
			options,'mvn_sta_CC_P4A_E','spec',1
			options,'mvn_sta_CC_P4A_D','spec',1
			options,'mvn_sta_CC_P4A_M','spec',1
			options,'mvn_sta_CC_P4A_E',ytitle='sta!CP4A-CC!C!CEnergy!CeV'
			options,'mvn_sta_CC_P4A_D',ytitle='sta!CP4A-CC!C!CDef!Ctheta'
			options,'mvn_sta_CC_P4A_M',ytitle='sta!CP4A-CC!C!Mass!Camu'
		endif
	endif
	endif


; Make CC common block

   if size(/type,t) eq 8 and ndis ge 2 then begin

	nenergy = 32							; 32Ex8Dx1Ax32M
	avg_nrg = 64/nenergy
	ndef = 8
	avg_def=16/ndef
	nanode = 1
	avg_an = 16/nanode
	nbins = ndef*nanode
	nmass = 32

	magf = replicate(0.,ndis)#[0.,0.,0.]
	quat_sc  = replicate(0.,ndis)#[0.,0.,0.,0.]
	quat_mso = replicate(0.,ndis)#[0.,0.,0.,0.]
	bins_sc = fix(replicate(1,ndis)#replicate(1,nbins))
	quality_flag = intarr(ndis)
	pos_sc_mso = replicate(0.,ndis)#[0.,0.,0.]
	bkg   = fltarr(ndis,nenergy,nbins,nmass)
	dead   = fltarr(ndis,nenergy,nbins,nmass) & dead[*]=1.

;	energy2  = reform(reform(total(reform(nrg,n_swp,avg_nrg,nenergy),2)/avg_nrg,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)
;	denergy2 = reform(reform(total(reform(dnrg,n_swp,avg_nrg,nenergy),2)       ,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)

	an_ma = replicate(1.,nbins*nmass) 
	energy2  = reform(reform(total(reform(nrg,n_swp,avg_nrg,nenergy),2)/avg_nrg,n_swp*nenergy) # an_ma,n_swp,nenergy,nbins,nmass)
	denergy2 = reform(reform(total(reform(dnrg,n_swp,avg_nrg,nenergy),2)       ,n_swp*nenergy) # an_ma,n_swp,nenergy,nbins,nmass)

;	gf[n_swp,64,16,16,4]	sum geometric factor over energy, deflection and anode, why is there a normalization???????				; gf[iswp,en,def,an,att]
;	gf2 = reform(total(total(reform(gf,n_swp,avg_nrg,nenergy,avg_def,ndef,16,4),4),2),n_swp,nenergy,nbins,4)/avg_nrg/avg_def			;

	gf2 = fltarr(n_swp,nenergy,ndef,4)
	gf1 = total(total(reform(gf,n_swp,avg_nrg,nenergy,avg_def,ndef,16,4),4),2)/(avg_nrg*avg_def)
	for i=0,n_swp-1 do gf2[i,*,*,*] = avg_an*total(gf1[i,*,*,swp2gfan[i,0]:swp2gfan[i,1],*],4)/(swp2gfan[i,1]-swp2gfan[i,0]+1)



; the following line assumes a constant efficiency as a default until other calibration code can be developed
;    a proper efficiency calibration is handled mvn_sta_dead_load.pro

	eff2 = fltarr(128,nenergy,nbins,nmass) & eff2[*]=def_eff  & eff_ind=intarr(ndis)

;	mlut = md2mlut(md1)
	mlut = swp2mlut(swp_ind)
	mass_arr=total(total(reform(mas,n_swp,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	tof_arr=total(total(reform(tof,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	twt_arr=total(total(reform(twt,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/avg_nrg

	mass_arr=transpose(reform(reform(mass_arr,n_swp*nenergy*nmass)#replicate(1.,nbins),n_swp,nenergy,nmass,nbins),[0,1,3,2])
	tof_arr=transpose(reform(reform(tof_arr,n_mlut*nenergy*nmass)#replicate(1.,nbins),n_mlut,nenergy,nmass,nbins),[0,1,3,2])
	twt_arr=transpose(reform(reform(twt_arr,n_mlut*nenergy*nmass)#replicate(1.,nbins),n_mlut,nenergy,nmass,nbins),[0,1,3,2])

; the following uses def(n_swp,64,16) to generate theta and phi arrays that depend on iswp(md1)

;theta and phi are screwed up????????????????????
	theta = reform(reform(total(total(reform(def,n_swp,avg_nrg,nenergy,avg_def,ndef),4),2),n_swp*nenergy*ndef)#replicate(1.,nanode*nmass),n_swp,nenergy,nbins,nmass)/avg_nrg/avg_def
	dtheta = reform(reform(total(reform(abs(def(*,*,15)-def(*,*,0))/(15.),n_swp,avg_nrg,nenergy),2),n_swp*nenergy)#replicate(1.,nbins*nmass),n_swp,nenergy,nbins,nmass)/avg_nrg*avg_def
;	phi = 22.5*reform(reform(replicate(1.,n_swp*nenergy*ndef)#(findgen(nanode)-7.),1l*n_swp*nenergy*nbins)#replicate(1.,nmass),n_swp,nenergy,nbins,nmass)
	phi = fltarr(n_swp,nenergy,nbins,nmass) & phi[*]=0.
	dphi = fltarr(n_swp,nenergy,nbins,nmass) & dphi[*]=360.
	domega = dphi*dtheta/!radeg^2

	cc_dat= {project_name:		'MAVEN',				$
		spacecraft:		'0', 					$
;		data_name:		'CC Energy-Angle-Mass', 		$
;		apid:			'CC',					$
		data_name:		'cc 32e8d32m', 				$
		apid:			'cc',					$
		units_name: 		'counts', 				$
		units_procedure: 	'mvn_sta_convert_units', 		$
		valid: 			replicate(1,ndis), 			$
		quality_flag: 		quality_flag, 				$

		time:			tt1,					$
		end_time:		tt2,					$
		delta_t:		tt2-tt1,				$
		integ_t: 		(tt2-tt1)/(nenergy*ndef)*dt_cor,	$	

		eprom_ver:		eprom_ver,				$
		header:			header,					$
		mode:			md2,					$
		rate:			rt2,					$
		swp_ind:		swp_ind,				$
		mlut_ind:		mlut,					$
		eff_ind:		eff_ind,				$
		att_ind:		att0,					$

		nenergy: 		nenergy,				$
		energy: 		energy2, 				$
		denergy: 		denergy2, 				$

		nbins: 			nbins, 					$
		bins: 			replicate(1,nbins), 			$
		ndef:			ndef,					$
		nanode:			nanode,					$

		theta: 			theta,  				$
		dtheta: 		dtheta,  				$
		phi: 			phi,  					$
		dphi: 			dphi, 					$
		domega: 		domega,  				$

		gf: 			gf2, 					$
		eff: 			eff2,	 				$

		geom_factor: 		geom_factor,				$
		dead1: 			dead1,					$
		dead2: 			dead2,					$
		dead3: 			dead3,					$

		nmass:			nmass,					$
		mass: 			1.0438871e-02, 				$
		mass_arr:		mass_arr,				$
		tof_arr:		tof_arr,				$
		twt_arr:		twt_arr,				$

		charge: 		1., 					$
		sc_pot: 		replicate(0.,ndis),			$
		magf:	 		magf, 					$
		quat_sc:	 	quat_sc, 				$
		quat_mso:	 	quat_mso, 				$
		bins_sc:		bins_sc,				$
		pos_sc_mso:		pos_sc_mso,				$

		bkg:	 		bkg,		 			$
		dead:	 		dead,		 			$

		data:			reform(tmp,ndis,nenergy,nbins,nmass)}

		common mvn_cc,mvn_cc_ind,mvn_cc_dat & mvn_cc_dat=cc_dat & mvn_cc_ind=0l

   endif

endif
endif


;***************************************************************************************************************
; APID CD


if keyword_set(apids) then test = fix((total(apids eq 'cd') + total(apids eq 'CD')) < 1) else test=0
if not keyword_set(apids) or test then begin
print,'Processing apid cd'


	ndis=0
	get_data,'mvn_STA_CD_DATA',data=t
	if size(/type,t) eq 8 then begin
		npts=8192									; 32Ex8Dx1Ax32M
		np = 8										; np is number of packets per measurement
		ind1 = where(t.x gt 0, nn)
		tt=t.x[0:nn-1]

; 		find out-of-sequence times -- not expected for science data 
;			might occur if an averaging time is changed and the change does not occur on the correct 2^n boundary

; the following "if" makes sure there are at least two measurements so the out-of-order time correction works
	if nn ge 2*np then begin

		ind = where (tt[0:nn-1-np] gt tt[np:nn-1],nind)							
		if nind gt 0 then begin					
			print,' ERROR - times out of sequence, CD packet'  
			print,' # of out of sequence times = ',nind	
			for i=0,nind-1 do begin	
				print,i,tt[ind[i]]-tt[ind[i]+np],'  ',time_string(tt[ind[i]]),'  ',time_string(tt[ind[i]+np]),'  ',time_string(tt[ind[i]+2*np])
			endfor
		endif

;		form some diagnostic tplot structures

		get_data,'mvn_STA_CD_DIAG',data=diag
		en = (diag.y[0:nn-1] AND 15)
		dt=0.1
			store_data,'mvn_sta_CD_DIAG_EN',data={x:tt+en*dt,y:en}
				ylim,'mvn_sta_CD_DIAG_EN',-1,np,0
			get_data,'mvn_STA_CD_SEQ_CNTR',data=tmp2
			store_data,'mvn_sta_CD_SEQ_CNTR_EN',data={x:tt+en*dt,y:tmp2.y[0:nn-1]}
			store_data,'mvn_sta_CD_DATA_EN',data={x:tt+en*dt,y:total(t.y[0:nn-1,*],2)}

;		find index numbers for the first packets of a np packet set

;			ind1 = where(tt[0:nn-1-np] eq tt[np-1:nn-2],ndis1)					; make sure there are "np" packets in a row with same time, old code w/ error
			ind1 = where(tt[0:nn-np] eq tt[np-1:nn-1],ndis1)					; make sure there are "np" packets in a row with same time, changed 20140106


			ind2 = where(tt[ind1[0:ndis1-1]] le tt[[ind1[1:ndis1-1],ind1[ndis1-1]]],ndis)		; throw out any np-packet group that is out of time order, changed 20140106
			ind  = ind1[ind2] 						

			if ind[ndis-1]+2*np-1 eq nn-1 then begin
				ind=[ind,ind[ndis-1]+np]
				ndis=ndis+1
			endif



		if ndis ge 1 then begin

			aa = indgen(np)#replicate(1,ndis)							; extract out the proper complete packets
			bb = replicate(1,np)#ind
			dat = t.y[aa+bb,*]

			tdis = tt[ind[0:ndis-1]]

			get_data,'mvn_STA_CD_MODE',data=md
				md1 = md.y[ind[0:ndis-1]] and 127
				md2 = md.y[ind[0:ndis-1]]and 15
				rt2 = (md.y[ind[0:ndis-1]] and 112)/16

			get_data,'mvn_STA_CD_AVG',data=cavg
			avg = 2^(cavg.y[ind[0:ndis-1]] and 7)
			sum = (cavg.y[ind[0:ndis-1]] and 8)/8
			avg2 = sum*avg > 1

;	correct CD mode transitions using C6 data if it is available
		get_data,'mvn_sta_C6_mode',data=md6
		if size(/type,md6) eq 8 then begin
			get_data,'mvn_sta_C6_rate',data=rt6
			md2 = fix(round(interp(md6.y,md6.x,tdis)))
			rt2 = fix(round(interp(rt6.y,rt6.x,tdis)))
			md1 = rt2*16+md2	 
		endif


			tt1 = tdis - 2.*avg2 									; corrected timing for averaging, kluge for header mismatch
			tt2 = tdis + 2.*avg2 

			get_data,'mvn_STA_CD_ATTEN',data=catt						; attenuator state
			att0 = (catt.y[ind[0:ndis-1]] and replicate(192,ndis))/64
			if ndis ge 2 then ind0 = where(att0[0:ndis-2] ne att0[1:ndis-1],cnt0) else cnt0=0
			if cnt0 ne 0 then begin
				for i=0,cnt0-1 do begin
					inds = ind0[i]
					idelay = fix(2/avg[inds])
;					if idelay gt 0 then att0[inds+1:(inds+idelay)<(nn-1)] = att0[inds]
					if idelay gt 0 then att0[inds+1:(inds+idelay)<(ndis-1)] = att0[inds]
				endfor
			endif

;	correct CD attenuator transitions using C6 data if it is available
		get_data,'mvn_sta_C6_att',data=att6
		if size(/type,att6) eq 8 then att0 = fix(round(interp(att6.y,att6.x,tdis)))<3

			header = 256l^3*md.y[ind[0:ndis-1]] + 256l^2*cavg.y[ind[0:ndis-1]] + 256l*catt.y[ind[0:ndis-1]] + diag.y[ind[0:ndis-1]]

			store_data,'mvn_sta_CD_mode',data={x:tdis,y:md2}
				ylim,'mvn_sta_CD_mode',-1,7,0
			store_data,'mvn_sta_CD_att',data={x:tdis,y:att0}
				ylim,'mvn_sta_CD_att',-1,4,0

;			swp_ind = md2swp[md1]									; old version
;			swp_ind = conf2swp[fix(interp((config4.y and 255)*1.,config4.x,tdis)+.5),md2]					
			swp_ind = conf2swp[fix(interp((config4.y and 511)*1.,config4.x,tdis)+.5),md2]					
				eprom_ver = fix(interp((config4.y and 255)*1.,config4.x,tdis)+.5)
				if tdis[0] lt time_double('2014-10-1/0') then eprom_ver[*]=0

			energy=nrg[swp_ind,*]
			energy=total(reform(energy,ndis,2,32),2)/2.
			mass=mas[swp_ind,0,*]
			mass=total(reform(mass,ndis,2,32),2)/2.						; because there are only 32 masses
			deflection = total(reform(def[swp_ind,62,*],ndis,2,8),2)/2.

			tmp=decomp19[reform(transpose(reform(dat,np,ndis,32,8,4),[1,4,0,3,2]),ndis,32,8,32)]		; [time,en,def,ma]

			store_data,'mvn_sta_CD_P4A_E',data={x:tdis,y:total(total(tmp,4),3),v:energy}
			store_data,'mvn_sta_CD_P4A_D',data={x:tdis,y:total(total(tmp,4),2),v:deflection}
			store_data,'mvn_sta_CD_P4A_M',data={x:tdis,y:total(total(tmp,2),2),v:mass}
			store_data,'mvn_sta_CD_P4A_tot',data={x:tdis,y:total(total(total(tmp,4),3),2)}
			store_data,'mvn_sta_CD_P4A_all',data={x:tdis,y:reform(tmp,ndis,npts),v:indgen(npts)}

			ylim,'mvn_sta_CD_P4A_tot',0,0,1
			ylim,'mvn_sta_CD_P4A_E',.4,40000.,1
			ylim,'mvn_sta_CD_P4A_D',-45,45,0
			ylim,'mvn_sta_CD_P4A_M',.5,100,1
			zlim,'mvn_sta_CD_P4A_E',1,1.e4,1
			zlim,'mvn_sta_CD_P4A_D',1,1.e4,1
			zlim,'mvn_sta_CD_P4A_M',1,1.e4,1
			options,'mvn_sta_CD_P4A_E',datagap=16.
			options,'mvn_sta_CD_P4A_D',datagap=16.
			options,'mvn_sta_CD_P4A_M',datagap=16.
			options,'mvn_sta_CD_P4A_tot',datagap=16.
			options,'mvn_sta_CD_P4A_E','spec',1
			options,'mvn_sta_CD_P4A_D','spec',1
			options,'mvn_sta_CD_P4A_M','spec',1
			options,'mvn_sta_CD_P4A_E',ytitle='sta!CP4A-CD!C!CEnergy!CeV'
			options,'mvn_sta_CD_P4A_D',ytitle='sta!CP4A-CD!C!CDef!Ctheta'
			options,'mvn_sta_CD_P4A_M',ytitle='sta!CP4A-CD!C!CMass!Camu'
		endif
	endif
	endif


; Make CD common block

   if size(/type,t) eq 8 and ndis ge 2 then begin

	nenergy = 32							; 32Ex8Dx1Ax32M
	avg_nrg = 64/nenergy
	ndef = 8
	avg_def=16/ndef
	nanode = 1
	avg_an = 16/nanode
	nbins = ndef*nanode
	nmass = 32

	magf = replicate(0.,ndis)#[0.,0.,0.]
	quat_sc  = replicate(0.,ndis)#[0.,0.,0.,0.]
	quat_mso = replicate(0.,ndis)#[0.,0.,0.,0.]
	bins_sc = fix(replicate(1,ndis)#replicate(1,nbins))
	quality_flag = intarr(ndis)
	pos_sc_mso = replicate(0.,ndis)#[0.,0.,0.]
	bkg   = fltarr(ndis,nenergy,nbins,nmass)
	dead   = fltarr(ndis,nenergy,nbins,nmass) & dead[*]=1.

;	energy2  = reform(reform(total(reform(nrg,n_swp,avg_nrg,nenergy),2)/avg_nrg,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)
;	denergy2 = reform(reform(total(reform(dnrg,n_swp,avg_nrg,nenergy),2)       ,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)

	an_ma = replicate(1.,nbins*nmass) 
	energy2  = reform(reform(total(reform(nrg,n_swp,avg_nrg,nenergy),2)/avg_nrg,n_swp*nenergy) # an_ma,n_swp,nenergy,nbins,nmass)
	denergy2 = reform(reform(total(reform(dnrg,n_swp,avg_nrg,nenergy),2)       ,n_swp*nenergy) # an_ma,n_swp,nenergy,nbins,nmass)

;	gf[n_swp,64,16,16,4]	sum geometric factor over energy, deflection and anode, why is there a normalization???????				; gf[iswp,en,def,an,att]
;	gf2 = reform(total(total(reform(gf,n_swp,avg_nrg,nenergy,avg_def,ndef,16,4),4),2),n_swp,nenergy,nbins,4)/avg_nrg/avg_def			;
;	gf2 = reform(total(total(total(reform(gf,n_swp,avg_nrg,nenergy,avg_def,ndef,16,4),6),4),2),n_swp,nenergy,nbins,4)/(avg_nrg*avg_def)			;

	gf2 = fltarr(n_swp,nenergy,ndef,4)
	gf1 = total(total(reform(gf,n_swp,avg_nrg,nenergy,avg_def,ndef,16,4),4),2)/(avg_nrg*avg_def)
	for i=0,n_swp-1 do gf2[i,*,*,*] = avg_an*total(gf1[i,*,*,swp2gfan[i,0]:swp2gfan[i,1],*],4)/(swp2gfan[i,1]-swp2gfan[i,0]+1)

; the following line assumes a constant efficiency as a default until other calibration code can be developed
;    a proper efficiency calibration is handled mvn_sta_dead_load.pro

	eff2 = fltarr(128,nenergy,nbins,nmass) & eff2[*]=def_eff  & eff_ind=intarr(ndis)

;	mlut = md2mlut(md1)
	mlut = swp2mlut(swp_ind)
	mass_arr=total(total(reform(mas,n_swp,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	tof_arr=total(total(reform(tof,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	twt_arr=total(total(reform(twt,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/avg_nrg

	mass_arr=transpose(reform(reform(mass_arr,n_swp*nenergy*nmass)#replicate(1.,nbins),n_swp,nenergy,nmass,nbins),[0,1,3,2])
	tof_arr=transpose(reform(reform(tof_arr,n_mlut*nenergy*nmass)#replicate(1.,nbins),n_mlut,nenergy,nmass,nbins),[0,1,3,2])
	twt_arr=transpose(reform(reform(twt_arr,n_mlut*nenergy*nmass)#replicate(1.,nbins),n_mlut,nenergy,nmass,nbins),[0,1,3,2])

; the following uses def(n_swp,64,16) to generate theta and phi arrays that depend on iswp(md1)

;theta and phi are screwed up????????????????????
	theta = reform(reform(total(total(reform(def,n_swp,avg_nrg,nenergy,avg_def,ndef),4),2),n_swp*nenergy*ndef)#replicate(1.,nanode*nmass),n_swp,nenergy,nbins,nmass)/avg_nrg/avg_def
	dtheta = reform(reform(total(reform(abs(def(*,*,15)-def(*,*,0))/(15.),n_swp,avg_nrg,nenergy),2),n_swp*nenergy)#replicate(1.,nbins*nmass),n_swp,nenergy,nbins,nmass)/avg_nrg*avg_def
;	phi = 22.5*reform(reform(replicate(1.,n_swp*nenergy*ndef)#(findgen(nanode)-7.),1l*n_swp*nenergy*nbins)#replicate(1.,nmass),n_swp,nenergy,nbins,nmass)
	phi = fltarr(n_swp,nenergy,nbins,nmass) & phi[*]=0.
	dphi = fltarr(n_swp,nenergy,nbins,nmass) & dphi(*)=360.
	domega = dphi*dtheta/!radeg^2

	cd_dat= {project_name:		'MAVEN',				$
		spacecraft:		'0', 					$
;		data_name:		'CD Energy-Angle-Mass', 		$
;		apid:			'CD',					$
		data_name:		'cd 32e8d32m', 				$
		apid:			'cd',					$
		units_name: 		'counts', 				$
		units_procedure: 	'mvn_sta_convert_units', 		$
		valid: 			replicate(1,ndis), 			$
		quality_flag: 		quality_flag, 				$

		time:			tt1,					$
		end_time:		tt2,					$
		delta_t:		tt2-tt1,				$
		integ_t: 		(tt2-tt1)/(nenergy*ndef)*dt_cor,	$	

		eprom_ver:		eprom_ver,				$
		header:			header,					$
		mode:			md2,					$
		rate:			rt2,					$
		swp_ind:		swp_ind,				$
		mlut_ind:		mlut,					$
		eff_ind:		eff_ind,				$
		att_ind:		att0,					$

		nenergy: 		nenergy,				$
		energy: 		energy2, 				$
		denergy: 		denergy2, 				$

		nbins: 			nbins, 					$
		bins: 			replicate(1,nbins), 			$
		ndef:			ndef,					$
		nanode:			nanode,					$

		theta: 			theta,  				$
		dtheta: 		dtheta,  				$
		phi: 			phi,  					$
		dphi: 			dphi, 					$
		domega: 		domega,  				$

		gf: 			gf2, 					$
		eff: 			eff2,	 				$

		geom_factor: 		geom_factor,				$
		dead1: 			dead1,					$
		dead2: 			dead2,					$
		dead3: 			dead3,					$

		nmass:			nmass,					$
		mass: 			1.0438871e-02, 				$
		mass_arr:		mass_arr,				$
		tof_arr:		tof_arr,				$
		twt_arr:		twt_arr,				$

		charge: 		1., 					$
		sc_pot: 		replicate(0.,ndis),			$
		magf:	 		magf, 					$
		quat_sc:	 	quat_sc, 				$
		quat_mso:	 	quat_mso, 				$
		bins_sc:		bins_sc,				$
		pos_sc_mso:		pos_sc_mso,				$

		bkg:	 		bkg,		 			$
		dead:	 		dead,		 			$

		data:			reform(tmp,ndis,nenergy,nbins,nmass)}

		common mvn_cd,mvn_cd_ind,mvn_cd_dat & mvn_cd_dat=cd_dat & mvn_cd_ind=0l

   endif
endif


;***************************************************************************************************************
; APID CE


if keyword_set(apids) then test = fix((total(apids eq 'ce') + total(apids eq 'CE')) < 1) else test=0
if not keyword_set(apids) or test then begin
print,'Processing apid ce'

; the header bits (diagnostic, mode, averaging, atten) may be out of phase with the packet by one cycle - see "maven/ITF/ATLOData/ATLO/SelfTest/SelfTest_ATLO_20131001_pfp_all_l0_v1.dat"

	ndis=0
	get_data,'mvn_STA_CE_DATA',data=t
	if size(/type,t) eq 8 then begin
		npts=16384									; 16Ex4Dx16Ax16M
		np = 16										; np is number of packets per measurement, npts/1024
		ind1 = where(t.x gt 0, nn)
		tt=t.x[0:nn-1]

; 		find out-of-sequence times -- not expected for science data 
;			might occur if an averaging time is changed and the change does not occur on the correct 2^n boundary

; the following "if" makes sure there are at least two measurements so the out-of-order time correction works
	if nn ge 2*np then begin

		ind = where (tt[0:nn-1-np] gt tt[np:nn-1],nind)							
		if nind gt 0 then begin					
			print,' ERROR - times out of sequence, CE packet'  
			print,' # of out of sequence times = ',nind	
			for i=0,nind-1 do begin	
				print,i,tt[ind[i]]-tt[ind[i]+np],'  ',time_string(tt[ind[i]]),'  ',time_string(tt[ind[i]+np]),'  ',time_string(tt[ind[i]+2*np])
			endfor
		endif

;		form some diagnostic tplot structures

		get_data,'mvn_STA_CE_DIAG',data=diag
		en = (diag.y[0:nn-1] AND 15)
		dt=0.1
			store_data,'mvn_sta_CE_DIAG_EN',data={x:tt+en*dt,y:en}
				ylim,'mvn_sta_CE_DIAG_EN',-1,np,0
			get_data,'mvn_STA_CE_SEQ_CNTR',data=tmp2
			store_data,'mvn_sta_CE_SEQ_CNTR_EN',data={x:tt+en*dt,y:tmp2.y[0:nn-1]}
			store_data,'mvn_sta_CE_DATA_EN',data={x:tt+en*dt,y:total(t.y[0:nn-1,*],2)}

;		find index numbers for the first packets of a np packet set

;			ind1 = where(tt[0:nn-1-np] eq tt[np-1:nn-2],ndis1)					; make sure there are "np" packets in a row with same time, old code w/ error
			ind1 = where(tt[0:nn-np] eq tt[np-1:nn-1],ndis1)					; make sure there are "np" packets in a row with same time, changed 20140106


			ind2 = where(tt[ind1[0:ndis1-1]] le tt[[ind1[1:ndis1-1],ind1[ndis1-1]]],ndis)		; throw out any np-packet group that is out of time order, changed 20140106
			ind  = ind1[ind2] 						

			if ind[ndis-1]+2*np-1 eq nn-1 then begin
				ind=[ind,ind[ndis-1]+np]
				ndis=ndis+1
			endif

;		ind = where(en eq 0,ndis)							; old code, ndis is number of complete distributions
;		if ind[ndis-1]+np-1 gt nn-1 then ndis=ndis-1					; old code, eliminate last distribution if not complete

		if ndis ge 1 then begin		

			aa = indgen(np)#replicate(1,ndis)							; extract out the proper complete packets
			bb = replicate(1,np)#ind
			dat = t.y[aa+bb,*]

			tdis = tt[ind[0:ndis-1]]

			get_data,'mvn_STA_CE_MODE',data=md
				md1 = md.y[ind[0:ndis-1]] and 127
				md2 = md.y[ind[0:ndis-1]]and 15
				rt2 = (md.y[ind[0:ndis-1]] and 112)/16

			get_data,'mvn_STA_CE_AVG',data=cavg
			avg = 2^(cavg.y[ind[0:ndis-1]] and 7)
			sum = (cavg.y[ind[0:ndis-1]] and 8)/8
			avg2 = sum*avg > 1

;	correct CE mode transitions using C6 data if it is available
		get_data,'mvn_sta_C6_mode',data=md6
		if size(/type,md6) eq 8 then begin
			get_data,'mvn_sta_C6_rate',data=rt6
			md2 = fix(round(interp(md6.y,md6.x,tdis)))
			rt2 = fix(round(interp(rt6.y,rt6.x,tdis)))
		endif
		md1 = rt2*16+md2	 

			tt1 = tdis - 2.*avg2 									; corrected timing for averaging, kluge for header mismatch
			tt2 = tdis + 2.*avg2 

			get_data,'mvn_STA_CE_ATTEN',data=catt						; attenuator state
			att0 = (catt.y[ind[0:ndis-1]] and replicate(192,ndis))/64
			if ndis ge 2 then ind0 = where(att0[0:ndis-2] ne att0[1:ndis-1],cnt0) else cnt0=0
			if cnt0 ne 0 then begin
				for i=0,cnt0-1 do begin
					inds = ind0[i]
					idelay = fix(2/avg[inds])
;					if idelay gt 0 then att0[inds+1:(inds+idelay)<(nn-1)] = att0[inds]
					if idelay gt 0 then att0[inds+1:(inds+idelay)<(ndis-1)] = att0[inds]
				endfor
			endif

;	correct CE attenuator transitions using C6 data if it is available
		get_data,'mvn_sta_C6_att',data=att6
		if size(/type,att6) eq 8 then att0 = fix(round(interp(att6.y,att6.x,tdis)))<3

			header = 256l^3*md.y[ind[0:ndis-1]] + 256l^2*cavg.y[ind[0:ndis-1]] + 256l*catt.y[ind[0:ndis-1]] + diag.y[ind[0:ndis-1]]

			store_data,'mvn_sta_CE_mode',data={x:tdis,y:md2}
				ylim,'mvn_sta_CE_mode',-1,7,0
			store_data,'mvn_sta_CE_att',data={x:tdis,y:att0}
				ylim,'mvn_sta_CE_att',-1,4,0

;			swp_ind = md2swp[md1]									; old version
;			swp_ind = conf2swp[fix(interp((config4.y and 255)*1.,config4.x,tdis)+.5),md2]					
			swp_ind = conf2swp[fix(interp((config4.y and 511)*1.,config4.x,tdis)+.5),md2]					
				eprom_ver = fix(interp((config4.y and 255)*1.,config4.x,tdis)+.5)
				if tdis[0] lt time_double('2014-10-1/0') then eprom_ver[*]=0

			energy=nrg[swp_ind,*]
			energy=total(reform(energy,ndis,4,16),2)/4.
			mass=mas[swp_ind,0,*]
			mass=total(reform(mass,ndis,4,16),2)/4.						; because there are only 16 masses
			deflection = total(reform(def[swp_ind,62,*],ndis,4,4),2)/4.

			tmp=decomp19[transpose(reform(dat,np,ndis,16,16,4),[1,0,4,2,3])]	; [time,en,def,an,ma]

			store_data,'mvn_sta_CE_P4B_E',data={x:tdis,y:total(total(total(tmp,5),4),3),v:energy}
			store_data,'mvn_sta_CE_P4B_D',data={x:tdis,y:total(total(total(tmp,5),4),2),v:deflection}
			store_data,'mvn_sta_CE_P4B_A',data={x:tdis,y:total(total(total(tmp,5),3),2),v:22.5*(findgen(16)-7.)}
			store_data,'mvn_sta_CE_P4B_M',data={x:tdis,y:total(total(total(tmp,4),3),2),v:mass}
			store_data,'mvn_sta_CE_P4B_tot',data={x:tdis,y:total(total(total(total(tmp,5),4),3),2)}
			store_data,'mvn_sta_CE_P4B_all',data={x:tdis,y:reform(tmp,ndis,npts),v:indgen(npts)}

			ylim,'mvn_sta_CE_P4B_tot',0,0,1
			ylim,'mvn_sta_CE_P4B_E',.4,40000.,1
			ylim,'mvn_sta_CE_P4B_D',-45,45,0
			ylim,'mvn_sta_CE_P4B_A',-180,200,0
			ylim,'mvn_sta_CE_P4B_M',.5,100,1
			zlim,'mvn_sta_CE_P4B_E',1,1.e5,1
			zlim,'mvn_sta_CE_P4B_D',1,1.e5,1
			zlim,'mvn_sta_CE_P4B_A',1,1.e5,1
			zlim,'mvn_sta_CE_P4B_M',1,1.e5,1
			options,'mvn_sta_CE_P4B_E',datagap=256.
			options,'mvn_sta_CE_P4B_D',datagap=256.
			options,'mvn_sta_CE_P4B_A',datagap=256.
			options,'mvn_sta_CE_P4B_M',datagap=256.
			options,'mvn_sta_CE_P4B_tot',datagap=256.
			options,'mvn_sta_CE_P4B_E','spec',1
			options,'mvn_sta_CE_P4B_D','spec',1
			options,'mvn_sta_CE_P4B_A','spec',1
			options,'mvn_sta_CE_P4B_M','spec',1
			options,'mvn_sta_CE_P4B_E',ytitle='sta!CP4B-CE!C!CEnergy!CeV'
			options,'mvn_sta_CE_P4B_D',ytitle='sta!CP4B-CE!C!CDef!Ctheta'
			options,'mvn_sta_CE_P4B_A',ytitle='sta!CP4B-CE!C!CAnode!Cphi'
			options,'mvn_sta_CE_P4B_M',ytitle='sta!CP4B-CE!C!CMass!Camu'
		endif
	endif
	endif


; Make CE common block

   if size(/type,t) eq 8 and ndis ge 2 then begin

	nenergy = 16							; 16Ex4Dx16Ax16M
	avg_nrg = 64/nenergy
	ndef = 4
	avg_def=16/ndef
	nanode = 16
	avg_an = 16/nanode
	nbins = ndef*nanode
	nmass = 16

	magf = replicate(0.,ndis)#[0.,0.,0.]
	quat_sc  = replicate(0.,ndis)#[0.,0.,0.,0.]
	quat_mso = replicate(0.,ndis)#[0.,0.,0.,0.]
	bins_sc = fix(replicate(1,ndis)#replicate(1,nbins))
	quality_flag = intarr(ndis)
	pos_sc_mso = replicate(0.,ndis)#[0.,0.,0.]
	bkg   = fltarr(ndis,nenergy,nbins,nmass)
	dead   = fltarr(ndis,nenergy,nbins,nmass) & dead[*]=1.

;	energy2  = reform(reform(total(reform(nrg,n_swp,avg_nrg,nenergy),2)/avg_nrg,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)
;	denergy2 = reform(reform(total(reform(dnrg,n_swp,avg_nrg,nenergy),2)       ,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)

	an_ma = replicate(1.,nbins*nmass) 
	energy2  = reform(reform(total(reform(nrg,n_swp,avg_nrg,nenergy),2)/avg_nrg,n_swp*nenergy) # an_ma,n_swp,nenergy,nbins,nmass)
	denergy2 = reform(reform(total(reform(dnrg,n_swp,avg_nrg,nenergy),2)       ,n_swp*nenergy) # an_ma,n_swp,nenergy,nbins,nmass)

;	gf[n_swp,64,16,16,4]	sum geometric factor over energy, deflection and anode, why is there a normalization???????				; gf[iswp,en,def,an,att]
;	gf2 = reform(total(total(reform(gf,n_swp,avg_nrg,nenergy,avg_def,ndef,16,4),4),2),n_swp,nenergy,nbins,4)/avg_nrg/avg_def			;
	gf2 = reform(total(total(reform(gf,n_swp,avg_nrg,nenergy,avg_def,ndef,16,4),4),2),n_swp,nenergy,nbins,4)/(avg_nrg*avg_def)			;


; the following line assumes a constant efficiency as a default until other calibration code can be developed
;    a proper efficiency calibration is handled mvn_sta_dead_load.pro

	eff2 = fltarr(128,nenergy,nbins,nmass) & eff2[*]=def_eff  & eff_ind=intarr(ndis)

;	mlut = md2mlut(md1)
	mlut = swp2mlut(swp_ind)
	mass_arr=total(total(reform(mas,n_swp,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	tof_arr=total(total(reform(tof,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	twt_arr=total(total(reform(twt,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/avg_nrg

	mass_arr=transpose(reform(reform(mass_arr,n_swp*nenergy*nmass)#replicate(1.,nbins),n_swp,nenergy,nmass,nbins),[0,1,3,2])
	tof_arr=transpose(reform(reform(tof_arr,n_mlut*nenergy*nmass)#replicate(1.,nbins),n_mlut,nenergy,nmass,nbins),[0,1,3,2])
	twt_arr=transpose(reform(reform(twt_arr,n_mlut*nenergy*nmass)#replicate(1.,nbins),n_mlut,nenergy,nmass,nbins),[0,1,3,2])

; the following uses def(n_swp,64,16) to generate theta and phi arrays that depend on iswp(md1)

;theta and phi are screwed up????????????????????
	theta = reform(reform(total(total(reform(def,n_swp,avg_nrg,nenergy,avg_def,ndef),4),2),n_swp*nenergy*ndef)#replicate(1.,nanode*nmass),n_swp,nenergy,nbins,nmass)/avg_nrg/avg_def
	dtheta = reform(reform(total(reform(abs(def(*,*,15)-def(*,*,0))/(15.),n_swp,avg_nrg,nenergy),2),n_swp*nenergy)#replicate(1.,nbins*nmass),n_swp,nenergy,nbins,nmass)/avg_nrg*avg_def
	phi = 22.5*reform(reform(replicate(1.,n_swp*nenergy*ndef)#(findgen(nanode)-7.),1l*n_swp*nenergy*nbins)#replicate(1.,nmass),n_swp,nenergy,nbins,nmass)
	dphi = fltarr(n_swp,nenergy,nbins,nmass) & dphi(*)=22.5
	domega = dphi*dtheta/!radeg^2

	ce_dat= {project_name:		'MAVEN',				$
		spacecraft:		'0', 					$
;		data_name:		'CE Energy-Angle-Mass', 		$
;		apid:			'CE',					$
		data_name:		'ce 16e4d16a16m', 			$
		apid:			'ce',					$
		units_name: 		'counts', 				$
		units_procedure: 	'mvn_sta_convert_units', 		$
		valid: 			replicate(1,ndis), 			$
		quality_flag: 		quality_flag, 				$

		time:			tt1,					$
		end_time:		tt2,					$
		delta_t:		tt2-tt1,				$
		integ_t: 		(tt2-tt1)/(nenergy*ndef)*dt_cor,	$	

		eprom_ver:		eprom_ver,				$
		header:			header,					$
		mode:			md2,					$
		rate:			rt2,					$
		swp_ind:		swp_ind,				$
		mlut_ind:		mlut,					$
		eff_ind:		eff_ind,				$
		att_ind:		att0,					$

		nenergy: 		nenergy,				$
		energy: 		energy2, 				$
		denergy: 		denergy2, 				$

		nbins: 			nbins, 					$
		bins: 			replicate(1,nbins), 			$
		ndef:			ndef,					$
		nanode:			nanode,					$

		theta: 			theta,  				$
		dtheta: 		dtheta,  				$
		phi: 			phi,  					$
		dphi: 			dphi, 					$
		domega: 		domega,  				$

		gf: 			gf2, 					$
		eff: 			eff2,	 				$

		geom_factor: 		geom_factor,				$
		dead1: 			dead1,					$
		dead2: 			dead2,					$
		dead3: 			dead3,					$

		nmass:			nmass,					$
		mass: 			1.0438871e-02, 				$
		mass_arr:		mass_arr,				$
		tof_arr:		tof_arr,				$
		twt_arr:		twt_arr,				$

		charge: 		1., 					$
		sc_pot: 		replicate(0.,ndis),			$
		magf:	 		magf, 					$
		quat_sc:	 	quat_sc, 				$
		quat_mso:	 	quat_mso, 				$
		bins_sc:		bins_sc,				$
		pos_sc_mso:		pos_sc_mso,				$

		bkg:	 		bkg,		 			$
		dead:	 		dead,		 			$

		data:			reform(tmp,ndis,nenergy,nbins,nmass)}

		common mvn_ce,mvn_ce_ind,mvn_ce_dat & mvn_ce_dat=ce_dat & mvn_ce_ind=0l

   endif
endif


;***************************************************************************************************************
; APID CF


if keyword_set(apids) then test = fix((total(apids eq 'cf') + total(apids eq 'CF')) < 1) else test=0
if not keyword_set(apids) or test then begin
print,'Processing apid cf'

; the header bits (diagnostic, mode, averaging, atten) may be out of phase with the packet by one cycle - see "maven/ITF/ATLOData/ATLO/SelfTest/SelfTest_ATLO_20131001_pfp_all_l0_v1.dat"

	ndis=0
	get_data,'mvn_STA_CF_DATA',data=t
	if size(/type,t) eq 8 then begin
		npts=16384									; 16Ex4Dx16Ax16M
		np = 16										; np is number of packets per measurement, npts/1024
		ind1 = where(t.x gt 0, nn)
		tt=t.x[0:nn-1]

; 		find out-of-sequence times -- not expected for science data 
;			might occur if an averaging time is changed and the change does not occur on the correct 2^n boundary

; the following "if" makes sure there are at least two measurements so the out-of-order time correction works
	if nn ge 2*np then begin

		ind = where (tt[0:nn-1-np] gt tt[np:nn-1],nind)							
		if nind gt 0 then begin					
			print,' ERROR - times out of sequence, CF packet'  
			print,' # of out of sequence times = ',nind	
			for i=0,nind-1 do begin	
				print,i,tt[ind[i]]-tt[ind[i]+np],'  ',time_string(tt[ind[i]]),'  ',time_string(tt[ind[i]+np]),'  ',time_string(tt[ind[i]+2*np])
			endfor
		endif

;		form some diagnostic tplot structures

		get_data,'mvn_STA_CF_DIAG',data=diag
		en = (diag.y[0:nn-1] AND 15)
		dt=0.1
			store_data,'mvn_sta_CF_DIAG_EN',data={x:tt+en*dt,y:en}
				ylim,'mvn_sta_CF_DIAG_EN',-1,np,0
			get_data,'mvn_STA_CF_SEQ_CNTR',data=tmp2
			store_data,'mvn_sta_CF_SEQ_CNTR_EN',data={x:tt+en*dt,y:tmp2.y[0:nn-1]}
			store_data,'mvn_sta_CF_DATA_EN',data={x:tt+en*dt,y:total(t.y[0:nn-1,*],2)}

;		find index numbers for the first packets of a np packet set

;			ind1 = where(tt[0:nn-1-np] eq tt[np-1:nn-2],ndis1)					; make sure there are "np" packets in a row with same time, old code w/ error
			ind1 = where(tt[0:nn-np] eq tt[np-1:nn-1],ndis1)					; make sure there are "np" packets in a row with same time, changed 20140106


			ind2 = where(tt[ind1[0:ndis1-1]] le tt[[ind1[1:ndis1-1],ind1[ndis1-1]]],ndis)		; throw out any np-packet group that is out of time order, changed 20140106
			ind  = ind1[ind2] 						

			if ind[ndis-1]+2*np-1 eq nn-1 then begin
				ind=[ind,ind[ndis-1]+np]
				ndis=ndis+1
			endif

;		ind = where(en eq 0,ndis)							; old code, ndis is number of complete distributions
;		if ind[ndis-1]+np-1 gt nn-1 then ndis=ndis-1					; old code, eliminate last distribution if not complete

		if ndis ge 1 then begin

			aa = indgen(np)#replicate(1,ndis)							; extract out the proper complete packets
			bb = replicate(1,np)#ind
			dat = t.y[aa+bb,*]

			tdis = tt[ind[0:ndis-1]]

			get_data,'mvn_STA_CF_MODE',data=md
				md1 = md.y[ind[0:ndis-1]] and 127
				md2 = md.y[ind[0:ndis-1]]and 15
				rt2 = (md.y[ind[0:ndis-1]] and 112)/16

			get_data,'mvn_STA_CF_AVG',data=cavg
			avg = 2^(cavg.y[ind[0:ndis-1]] and 7)
			sum = (cavg.y[ind[0:ndis-1]] and 8)/8
			avg2 = sum*avg > 1

;	correct CF mode transitions using C6 data if it is available
		get_data,'mvn_sta_C6_mode',data=md6
		if size(/type,md6) eq 8 then begin
			get_data,'mvn_sta_C6_rate',data=rt6
			md2 = fix(round(interp(md6.y,md6.x,tdis)))
			rt2 = fix(round(interp(rt6.y,rt6.x,tdis)))
			md1 = rt2*16+md2	 
		endif

			tt1 = tdis - 2.*avg2 									; corrected timing for averaging, kluge for header mismatch
			tt2 = tdis + 2.*avg2 

			get_data,'mvn_STA_CF_ATTEN',data=catt						; attenuator state
			att0 = (catt.y[ind[0:ndis-1]] and replicate(192,ndis))/64
			if ndis ge 2 then ind0 = where(att0[0:ndis-2] ne att0[1:ndis-1],cnt0) else cnt0=0
			if cnt0 ne 0 then begin
				for i=0,cnt0-1 do begin
					inds = ind0[i]
					idelay = fix(2/avg[inds])
;					if idelay gt 0 then att0[inds+1:(inds+idelay)<(nn-1)] = att0[inds]
					if idelay gt 0 then att0[inds+1:(inds+idelay)<(ndis-1)] = att0[inds]
				endfor
			endif

;	correct CF attenuator transitions using C6 data if it is available
		get_data,'mvn_sta_C6_att',data=att6
		if size(/type,att6) eq 8 then att0 = fix(round(interp(att6.y,att6.x,tdis)))<3

			header = 256l^3*md.y[ind[0:ndis-1]] + 256l^2*cavg.y[ind[0:ndis-1]] + 256l*catt.y[ind[0:ndis-1]] + diag.y[ind[0:ndis-1]]

			store_data,'mvn_sta_CF_mode',data={x:tdis,y:md2}
				ylim,'mvn_sta_CF_mode',-1,7,0
			store_data,'mvn_sta_CF_att',data={x:tdis,y:att0}
				ylim,'mvn_sta_CF_att',-1,4,0

;			swp_ind = md2swp[md1]									; old version
;			swp_ind = conf2swp[fix(interp((config4.y and 255)*1.,config4.x,tdis)+.5),md2]					
			swp_ind = conf2swp[fix(interp((config4.y and 511)*1.,config4.x,tdis)+.5),md2]					
				eprom_ver = fix(interp((config4.y and 255)*1.,config4.x,tdis)+.5)
				if tdis[0] lt time_double('2014-10-1/0') then eprom_ver[*]=0

			energy=nrg[swp_ind,*]
			energy=total(reform(energy,ndis,4,16),2)/4.
			mass=mas[swp_ind,0,*]
			mass=total(reform(mass,ndis,4,16),2)/4.						; because there are only 16 masses
			deflection = total(reform(def[swp_ind,62,*],ndis,4,4),2)/4.

			tmp=decomp19[transpose(reform(dat,np,ndis,16,16,4),[1,0,4,2,3])]	; [time,en,def,an,ma]

			store_data,'mvn_sta_CF_P4B_E',data={x:tdis,y:total(total(total(tmp,5),4),3),v:energy}
			store_data,'mvn_sta_CF_P4B_D',data={x:tdis,y:total(total(total(tmp,5),4),2),v:deflection}
			store_data,'mvn_sta_CF_P4B_A',data={x:tdis,y:total(total(total(tmp,5),3),2),v:22.5*(findgen(16)-7.)}
			store_data,'mvn_sta_CF_P4B_M',data={x:tdis,y:total(total(total(tmp,4),3),2),v:mass}
			store_data,'mvn_sta_CF_P4B_tot',data={x:tdis,y:total(total(total(total(tmp,5),4),3),2)}
			store_data,'mvn_sta_CF_P4B_all',data={x:tdis,y:reform(tmp,ndis,npts),v:indgen(npts)}

			ylim,'mvn_sta_CF_P4B_tot',0,0,1
			ylim,'mvn_sta_CF_P4B_E',.4,40000.,1
			ylim,'mvn_sta_CF_P4B_D',-45,45,0
			ylim,'mvn_sta_CF_P4B_A',-180,200,0
			ylim,'mvn_sta_CF_P4B_M',.5,100,1
			zlim,'mvn_sta_CF_P4B_E',1,1.e4,1
			zlim,'mvn_sta_CF_P4B_D',1,1.e4,1
			zlim,'mvn_sta_CF_P4B_A',1,1.e4,1
			zlim,'mvn_sta_CF_P4B_M',1,1.e4,1
			options,'mvn_sta_CF_P4B_E',datagap=64.
			options,'mvn_sta_CF_P4B_D',datagap=64.
			options,'mvn_sta_CF_P4B_A',datagap=64.
			options,'mvn_sta_CF_P4B_M',datagap=64.
			options,'mvn_sta_CF_P4B_tot',datagap=64.
			options,'mvn_sta_CF_P4B_E','spec',1
			options,'mvn_sta_CF_P4B_D','spec',1
			options,'mvn_sta_CF_P4B_A','spec',1
			options,'mvn_sta_CF_P4B_M','spec',1
			options,'mvn_sta_CF_P4B_E',ytitle='sta!CP4B-CF!C!CEnergy!CeV'
			options,'mvn_sta_CF_P4B_D',ytitle='sta!CP4B-CF!C!CDef!Ctheta'
			options,'mvn_sta_CF_P4B_A',ytitle='sta!CP4B-CF!C!CAnode!Cphi'
			options,'mvn_sta_CF_P4B_M',ytitle='sta!CP4B-CF!C!CMass!Camu'
		endif
	endif
	endif


; Make CF common block

   if size(/type,t) eq 8 and ndis ge 2 then begin

	nenergy = 16							; 16Ex4Dx16Ax16M
	avg_nrg = 64/nenergy
	ndef = 4
	avg_def=16/ndef
	nanode = 16
	avg_an = 16/nanode
	nbins = ndef*nanode
	nmass = 16

	magf = replicate(0.,ndis)#[0.,0.,0.]
	quat_sc  = replicate(0.,ndis)#[0.,0.,0.,0.]
	quat_mso = replicate(0.,ndis)#[0.,0.,0.,0.]
	bins_sc = fix(replicate(1,ndis)#replicate(1,nbins))
	quality_flag = intarr(ndis)
	pos_sc_mso = replicate(0.,ndis)#[0.,0.,0.]
	bkg   = fltarr(ndis,nenergy,nbins,nmass)
	dead   = fltarr(ndis,nenergy,nbins,nmass) & dead[*]=1.

;	energy2  = reform(reform(total(reform(nrg,n_swp,avg_nrg,nenergy),2)/avg_nrg,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)
;	denergy2 = reform(reform(total(reform(dnrg,n_swp,avg_nrg,nenergy),2)       ,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)

	an_ma = replicate(1.,nbins*nmass) 
	energy2  = reform(reform(total(reform(nrg,n_swp,avg_nrg,nenergy),2)/avg_nrg,n_swp*nenergy) # an_ma,n_swp,nenergy,nbins,nmass)
	denergy2 = reform(reform(total(reform(dnrg,n_swp,avg_nrg,nenergy),2)       ,n_swp*nenergy) # an_ma,n_swp,nenergy,nbins,nmass)

;	gf[n_swp,64,16,16,4]	sum geometric factor over energy, deflection and anode, why is there a normalization???????				; gf[iswp,en,def,an,att]
;	gf2 = reform(total(total(reform(gf,n_swp,avg_nrg,nenergy,avg_def,ndef,16,4),4),2),n_swp,nenergy,nbins,4)/avg_nrg/avg_def			;
	gf2 = reform(total(total(reform(gf,n_swp,avg_nrg,nenergy,avg_def,ndef,16,4),4),2),n_swp,nenergy,nbins,4)/(avg_nrg*avg_def)			;

; the following line assumes a constant efficiency as a default until other calibration code can be developed
;    a proper efficiency calibration is handled mvn_sta_dead_load.pro

	eff2 = fltarr(128,nenergy,nbins,nmass) & eff2[*]=def_eff  & eff_ind=intarr(ndis)

;	mlut = md2mlut(md1)
	mlut = swp2mlut(swp_ind)
	mass_arr=total(total(reform(mas,n_swp,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	tof_arr=total(total(reform(tof,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	twt_arr=total(total(reform(twt,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/avg_nrg

	mass_arr=transpose(reform(reform(mass_arr,n_swp*nenergy*nmass)#replicate(1.,nbins),n_swp,nenergy,nmass,nbins),[0,1,3,2])
	tof_arr=transpose(reform(reform(tof_arr,n_mlut*nenergy*nmass)#replicate(1.,nbins),n_mlut,nenergy,nmass,nbins),[0,1,3,2])
	twt_arr=transpose(reform(reform(twt_arr,n_mlut*nenergy*nmass)#replicate(1.,nbins),n_mlut,nenergy,nmass,nbins),[0,1,3,2])

; the following uses def(n_swp,64,16) to generate theta and phi arrays that depend on iswp(md1)

;theta and phi are screwed up????????????????????
	theta = reform(reform(total(total(reform(def,n_swp,avg_nrg,nenergy,avg_def,ndef),4),2),n_swp*nenergy*ndef)#replicate(1.,nanode*nmass),n_swp,nenergy,nbins,nmass)/avg_nrg/avg_def
	dtheta = reform(reform(total(reform(abs(def(*,*,15)-def(*,*,0))/(15.),n_swp,avg_nrg,nenergy),2),n_swp*nenergy)#replicate(1.,nbins*nmass),n_swp,nenergy,nbins,nmass)/avg_nrg*avg_def
	phi = 22.5*reform(reform(replicate(1.,n_swp*nenergy*ndef)#(findgen(nanode)-7.),1l*n_swp*nenergy*nbins)#replicate(1.,nmass),n_swp,nenergy,nbins,nmass)
	dphi = fltarr(n_swp,nenergy,nbins,nmass) & dphi(*)=22.5
	domega = dphi*dtheta/!radeg^2

	cf_dat= {project_name:		'MAVEN',				$
		spacecraft:		'0', 					$
;		data_name:		'CF Energy-Angle-Mass', 		$
;		apid:			'CF',					$
		data_name:		'cf 16e4d16a16m', 			$
		apid:			'cf',					$
		units_name: 		'counts', 				$
		units_procedure: 	'mvn_sta_convert_units', 		$
		valid: 			replicate(1,ndis), 			$
		quality_flag: 		quality_flag, 				$

		time:			tt1,					$
		end_time:		tt2,					$
		delta_t:		tt2-tt1,				$
		integ_t: 		(tt2-tt1)/(nenergy*ndef)*dt_cor,	$	

		eprom_ver:		eprom_ver,				$
		header:			header,					$
		mode:			md2,					$
		rate:			rt2,					$
		swp_ind:		swp_ind,				$
		mlut_ind:		mlut,					$
		eff_ind:		eff_ind,				$
		att_ind:		att0,					$

		nenergy: 		nenergy,				$
		energy: 		energy2, 				$
		denergy: 		denergy2, 				$

		nbins: 			nbins, 					$
		bins: 			replicate(1,nbins), 			$
		ndef:			ndef,					$
		nanode:			nanode,					$

		theta: 			theta,  				$
		dtheta: 		dtheta,  				$
		phi: 			phi,  					$
		dphi: 			dphi, 					$
		domega: 		domega,  				$

		gf: 			gf2, 					$
		eff: 			eff2,	 				$

		geom_factor: 		geom_factor,				$
		dead1: 			dead1,					$
		dead2: 			dead2,					$
		dead3: 			dead3,					$

		nmass:			nmass,					$
		mass: 			1.0438871e-02, 				$
		mass_arr:		mass_arr,				$
		tof_arr:		tof_arr,				$
		twt_arr:		twt_arr,				$

		charge: 		1., 					$
		sc_pot: 		replicate(0.,ndis),			$
		magf:	 		magf, 					$
		quat_sc:	 	quat_sc, 				$
		quat_mso:	 	quat_mso, 				$
		bins_sc:		bins_sc,				$
		pos_sc_mso:		pos_sc_mso,				$

		bkg:	 		bkg,		 			$
		dead:	 		dead,		 			$

		data:			reform(tmp,ndis,nenergy,nbins,nmass)}

		common mvn_cf,mvn_cf_ind,mvn_cf_dat & mvn_cf_dat=cf_dat & mvn_cf_ind=0l

   endif
endif


;***************************************************************************************************************
; APID D0

if keyword_set(apids) then test = fix((total(apids eq 'd0') + total(apids eq 'D0')) < 1) else test=0
if not keyword_set(apids) or test then begin
print,'Processing apid d0'

; the header bits (diagnostic, mode, averaging, atten) may be out of phase with the packet by one cycle - see "maven/ITF/ATLOData/ATLO/SelfTest/SelfTest_ATLO_20131001_pfp_all_l0_v1.dat"

	ndis=0
	get_data,'mvn_STA_D0_DATA',data=t
	if size(/type,t) eq 8 then begin
		npts=16384									; 32Ex4Dx16Ax8M
		np = 16										; np is number of packets per measurement, npts/1024
		ind1 = where(t.x gt 0, nn)
		tt=t.x[0:nn-1]

; 		find out of sequence times, not expected for science data
;			might occur if an averaging time is changed and the change does not occur on the correct 2^n boundary

; the following "if" makes sure there are at least two measurements so the out-of-order time correction works
	if nn ge 2*np then begin

		ind = where (tt[0:nn-1-np] gt tt[np:nn-1],nind)							
		if nind gt 0 then begin									; out of seq data should not occur for normal mode changes
			print,' ERROR - times out of sequence, D0 packet' 				; but can occur if a mode change just changes the averaging times 
			print,' # of out of sequence times = ',nind					; and if not all the header bits are changed in time.
			for i=0,nind-1 do begin	
				print,i,tt[ind[i]]-tt[ind[i]+np],'  ',time_string(tt[ind[i]]),'  ',time_string(tt[ind[i]+np]),'  ',time_string(tt[ind[i]+2*np])
			endfor
		endif

;		form some diagnostic tplot structures

		get_data,'mvn_STA_D0_DIAG',data=diag
		en = (diag.y[0:nn-1] AND 15)
		dt=0.1
			store_data,'mvn_sta_D0_DIAG_EN',data={x:tt+en*dt,y:en}
				ylim,'mvn_sta_D0_DIAG_EN',-1,np,0
			get_data,'mvn_STA_D0_SEQ_CNTR',data=seq
			store_data,'mvn_sta_D0_SEQ_CNTR_EN',data={x:tt+en*dt,y:seq.y[0:nn-1]}
			store_data,'mvn_sta_D0_DATA_EN',data={x:tt+en*dt,y:total(t.y[0:nn-1,*],2)}

;		find index numbers for the first packets of a np packet set

;			ind  = where(tt[0:nn-1-np] eq tt[np-1:nn-2],ndis)					; old code, make sure there are 16 packets in a row with same time
			ind1 = where(tt[0:nn-1-np] eq tt[np-1:nn-2],ndis1)					; make sure there are 16 packets in a row with same time

; problems with these lines
			ind2 = where(tt[ind1[0:ndis1-1]] le tt[[ind1[1:ndis1-1],ind1[ndis1-1]]],ndis)		; throw out any 16 packet group that is not time ordered
			ind  = ind1[ind2] 
						
			if ind[ndis-1]+2*np-1 eq nn-1 then begin
				ind=[ind,ind[ndis-1]+np]
				ndis=ndis+1
			endif
; 		   old method does not handle missing packets correctly
;			ind = where(en eq 0,ndis)
;			if ind[ndis-1]+np-1 gt nn-1 then ndis=ndis-1					; eliminate last distribution if not complete

		if ndis ge 1 then begin

			aa = indgen(np)#replicate(1,ndis)
			bb = replicate(1,np)#ind
			dat = t.y[aa+bb,*]

			tdis = tt[ind[0:ndis-1]]

			get_data,'mvn_STA_D0_MODE',data=md
				md1 = md.y[ind[0:ndis-1]] and 127
				md2 = md.y[ind[0:ndis-1]]and 15
				rt2 = (md.y[ind[0:ndis-1]] and 112)/16

			get_data,'mvn_STA_D0_AVG',data=cavg
			avg = 2^(cavg.y[ind[0:ndis-1]] and 7)
			sum = (cavg.y[ind[0:ndis-1]] and 8)/8
			avg2 = sum*avg > 1

;	correct D0 mode transitions using C6 data if it is available
		get_data,'mvn_sta_C6_mode',data=md6
		if size(/type,md6) eq 8 then begin
			get_data,'mvn_sta_C6_rate',data=rt6
			md2 = fix(round(interp(md6.y,md6.x,tdis)))
			rt2 = fix(round(interp(rt6.y,rt6.x,tdis)))
		endif
		md1 = rt2*16+md2	 

			tt1 = tdis - 2.*avg2 									; corrected timing for averaging, kluge for header mismatch
			tt2 = tdis + 2.*avg2 

			get_data,'mvn_STA_D0_ATTEN',data=catt						; attenuator state
			att0 = (catt.y[ind[0:ndis-1]] and replicate(192,ndis))/64
			if ndis ge 2 then ind0 = where(att0[0:ndis-2] ne att0[1:ndis-1],cnt0) else cnt0=0
			if cnt0 ne 0 then begin
				for i=0,cnt0-1 do begin
					inds = ind0[i]
					idelay = fix(2/avg[inds])
;					if idelay gt 0 then att0[inds+1:(inds+idelay)<(nn-1)] = att0[inds]
					if idelay gt 0 then att0[inds+1:(inds+idelay)<(ndis-1)] = att0[inds]
				endfor
			endif

;	correct D0 attenuator transitions using C6 data if it is available
		get_data,'mvn_sta_C6_att',data=att6
		if size(/type,att6) eq 8 then att0 = fix(round(interp(att6.y,att6.x,tdis)))<3

			header = 256l^3*md.y[ind[0:ndis-1]] + 256l^2*cavg.y[ind[0:ndis-1]] + 256l*catt.y[ind[0:ndis-1]] + diag.y[ind[0:ndis-1]]

			store_data,'mvn_sta_D0_mode',data={x:tdis,y:md2}
				ylim,'mvn_sta_D0_mode',-1,7,0
			store_data,'mvn_sta_D0_att',data={x:tdis,y:att0}
				ylim,'mvn_sta_D0_att',-1,4,0

;			swp_ind = md2swp[md1]									; old version
;			swp_ind = conf2swp[fix(interp((config4.y and 255)*1.,config4.x,tdis)+.5),md2]					
			swp_ind = conf2swp[fix(interp((config4.y and 511)*1.,config4.x,tdis)+.5),md2]					
				eprom_ver = fix(interp((config4.y and 255)*1.,config4.x,tdis)+.5)
				if tdis[0] lt time_double('2014-10-1/0') then eprom_ver[*]=0

			energy=nrg[swp_ind,*]
			energy=total(reform(energy,ndis,2,32),2)/2.
			mass=mas[swp_ind,0,*]
			mass=total(reform(mass,ndis,8,8),2)/8.						; because there are only 8 masses
			deflection = total(reform(def[swp_ind,62,*],ndis,4,4),2)/4.

			tmp=decomp19[reform(transpose(reform(dat,np,ndis,16,8,4,2),[1,5,0,4,2,3]),ndis,32,4,16,8)]	; [time,en,def,an,ma]

			store_data,'mvn_sta_D0_P4C_E',data={x:tdis,y:total(total(total(tmp,5),4),3),v:energy}
			store_data,'mvn_sta_D0_P4C_D',data={x:tdis,y:total(total(total(tmp,5),4),2),v:deflection}
			store_data,'mvn_sta_D0_P4C_A',data={x:tdis,y:total(total(total(tmp,5),3),2),v:22.5*(findgen(16)-7.)}
			store_data,'mvn_sta_D0_P4C_M',data={x:tdis,y:total(total(total(tmp,4),3),2),v:mass}
			store_data,'mvn_sta_D0_P4C_tot',data={x:tdis,y:total(total(total(total(tmp,5),4),3),2)}
			store_data,'mvn_sta_D0_P4C_all',data={x:tdis,y:reform(tmp,ndis,npts),v:indgen(npts)}

			ylim,'mvn_sta_D0_P4C_tot',0,0,1
			ylim,'mvn_sta_D0_P4C_E',.4,40000.,1
			ylim,'mvn_sta_D0_P4C_D',-45,45,0
			ylim,'mvn_sta_D0_P4C_A',-180,200,0
			ylim,'mvn_sta_D0_P4C_M',.5,100,1
			zlim,'mvn_sta_D0_P4C_E',1,1.e5,1
			zlim,'mvn_sta_D0_P4C_D',1,1.e5,1
			zlim,'mvn_sta_D0_P4C_A',1,1.e5,1
			zlim,'mvn_sta_D0_P4C_M',1,1.e5,1
			options,'mvn_sta_D0_P4C_E',datagap=512.
			options,'mvn_sta_D0_P4C_D',datagap=512.
			options,'mvn_sta_D0_P4C_A',datagap=512.
			options,'mvn_sta_D0_P4C_M',datagap=512.
			options,'mvn_sta_D0_P4C_tot',datagap=512.
			options,'mvn_sta_D0_P4C_E','spec',1
			options,'mvn_sta_D0_P4C_D','spec',1
			options,'mvn_sta_D0_P4C_A','spec',1
			options,'mvn_sta_D0_P4C_M','spec',1
			options,'mvn_sta_D0_P4C_E',ytitle='sta!CP4C-D0!C!CEnergy!CeV'
			options,'mvn_sta_D0_P4C_D',ytitle='sta!CP4C-D0!C!CDef!Ctheta'
			options,'mvn_sta_D0_P4C_A',ytitle='sta!CP4C-D0!C!CAnode!Cphi'
			options,'mvn_sta_D0_P4C_M',ytitle='sta!CP4C-D0!C!CMass!Camu'
		endif
	endif
	endif


; Make D0 common block

   if size(/type,t) eq 8 and ndis ge 2 then begin

	nenergy = 32
	avg_nrg = 64/nenergy
	ndef = 4
	avg_def=16/ndef
	nanode = 16
	avg_an = 16/nanode
	nbins = ndef*nanode
	nmass = 8

	magf = replicate(0.,ndis)#[0.,0.,0.]
	quat_sc  = replicate(0.,ndis)#[0.,0.,0.,0.]
	quat_mso = replicate(0.,ndis)#[0.,0.,0.,0.]
	bins_sc = fix(replicate(1,ndis)#replicate(1,nbins))
	quality_flag = intarr(ndis)
	pos_sc_mso = replicate(0.,ndis)#[0.,0.,0.]
	bkg   = fltarr(ndis,nenergy,nbins,nmass)
	dead   = fltarr(ndis,nenergy,nbins,nmass) & dead[*]=1.

;	energy2  = reform(reform(total(reform(nrg,n_swp,avg_nrg,nenergy),2)/avg_nrg,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)
;	denergy2 = reform(reform(total(reform(dnrg,n_swp,avg_nrg,nenergy),2)       ,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)

	an_ma = replicate(1.,nbins*nmass) 
	energy2  = reform(reform(total(reform(nrg,n_swp,avg_nrg,nenergy),2)/avg_nrg,n_swp*nenergy) # an_ma,n_swp,nenergy,nbins,nmass)
	denergy2 = reform(reform(total(reform(dnrg,n_swp,avg_nrg,nenergy),2)       ,n_swp*nenergy) # an_ma,n_swp,nenergy,nbins,nmass)

;	gf[n_swp,64,16,16,4]	sum geometric factor over energy, deflection and anode, why is there a normalization???????				; gf[iswp,en,def,an,att]
;	gf2 = reform(total(total(reform(gf,n_swp,avg_nrg,nenergy,avg_def,ndef,16,4),4),2),n_swp,nenergy,nbins,4)/avg_nrg/avg_def			;
	gf2 = reform(total(total(reform(gf,n_swp,avg_nrg,nenergy,avg_def,ndef,16,4),4),2),n_swp,nenergy,nbins,4)/(avg_nrg*avg_def)			;

; the following line assumes a constant efficiency as a default until other calibration code can be developed
;    a proper efficiency calibration is handled mvn_sta_dead_load.pro

	eff2 = fltarr(128,nenergy,nbins,nmass) & eff2[*]=def_eff  & eff_ind=intarr(ndis)

;	mlut = md2mlut(md1)
	mlut = swp2mlut(swp_ind)
	mass_arr=total(total(reform(mas,n_swp,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	tof_arr=total(total(reform(tof,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	twt_arr=total(total(reform(twt,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/avg_nrg

	mass_arr=transpose(reform(reform(mass_arr,n_swp*nenergy*nmass)#replicate(1.,nbins),n_swp,nenergy,nmass,nbins),[0,1,3,2])
	tof_arr=transpose(reform(reform(tof_arr,n_mlut*nenergy*nmass)#replicate(1.,nbins),n_mlut,nenergy,nmass,nbins),[0,1,3,2])
	twt_arr=transpose(reform(reform(twt_arr,n_mlut*nenergy*nmass)#replicate(1.,nbins),n_mlut,nenergy,nmass,nbins),[0,1,3,2])

; the following uses def(n_swp,64,16) to generate theta and phi arrays that depend on iswp(md1)

;theta and phi are screwed up????????????????????
	theta = reform(reform(total(total(reform(def,n_swp,avg_nrg,nenergy,avg_def,ndef),4),2),n_swp*nenergy*ndef)#replicate(1.,nanode*nmass),n_swp,nenergy,nbins,nmass)/avg_nrg/avg_def
	dtheta = reform(reform(total(reform(abs(def(*,*,15)-def(*,*,0))/(15.),n_swp,avg_nrg,nenergy),2),n_swp*nenergy)#replicate(1.,nbins*nmass),n_swp,nenergy,nbins,nmass)/avg_nrg*avg_def
	phi = 22.5*reform(reform(replicate(1.,n_swp*nenergy*ndef)#(findgen(nanode)-7.),1l*n_swp*nenergy*nbins)#replicate(1.,nmass),n_swp,nenergy,nbins,nmass)
	dphi = fltarr(n_swp,nenergy,nbins,nmass) & dphi(*)=22.5
	domega = dphi*dtheta/!radeg^2

	d0_dat= {project_name:		'MAVEN',				$
		spacecraft:		'0', 					$
;		data_name:		'D0 Energy-Angle-Mass', 		$
;		apid:			'D0',					$
		data_name:		'd0 32e4d16a8m', 			$
		apid:			'd0',					$
		units_name: 		'counts', 				$
		units_procedure: 	'mvn_sta_convert_units', 		$
		valid: 			replicate(1,ndis), 			$
		quality_flag: 		quality_flag, 				$

		time:			tt1,					$
		end_time:		tt2,					$
		delta_t:		tt2-tt1,				$
		integ_t: 		(tt2-tt1)/(nenergy*ndef)*dt_cor,	$	

		eprom_ver:		eprom_ver,				$
		header:			header,					$
		mode:			md2,					$
		rate:			rt2,					$
		swp_ind:		swp_ind,				$
		mlut_ind:		mlut,					$
		eff_ind:		eff_ind,				$
		att_ind:		att0,					$

		nenergy: 		nenergy,				$
		energy: 		energy2, 				$
		denergy: 		denergy2, 				$

		nbins: 			nbins, 					$
		bins: 			replicate(1,nbins), 			$
		ndef:			ndef,					$
		nanode:			nanode,					$

		theta: 			theta,  				$
		dtheta: 		dtheta,  				$
		phi: 			phi,  					$
		dphi: 			dphi, 					$
		domega: 		domega,  				$

		gf: 			gf2, 					$
		eff: 			eff2,	 				$

		geom_factor: 		geom_factor,				$
		dead1: 			dead1,					$
		dead2: 			dead2,					$
		dead3: 			dead3,					$

		nmass:			nmass,					$
		mass: 			1.0438871e-02, 				$
		mass_arr:		mass_arr,				$
		tof_arr:		tof_arr,				$
		twt_arr:		twt_arr,				$

		charge: 		1., 					$
		sc_pot: 		replicate(0.,ndis),			$
		magf:	 		magf, 					$
		quat_sc:	 	quat_sc, 				$
		quat_mso:	 	quat_mso, 				$
		bins_sc:		bins_sc,				$
		pos_sc_mso:		pos_sc_mso,				$

		bkg:	 		bkg,		 			$
		dead:	 		dead,		 			$

		data:			reform(tmp,ndis,nenergy,nbins,nmass)}

		common mvn_d0,mvn_d0_ind,mvn_d0_dat & mvn_d0_dat=d0_dat & mvn_d0_ind=0l

   endif
endif


;***************************************************************************************************************
; APID D1


if keyword_set(apids) then test = fix((total(apids eq 'd1') + total(apids eq 'D1')) < 1) else test=0
if not keyword_set(apids) or test then begin
print,'Processing apid d1'

; the header bits (diagnostic, mode, averaging, atten) may be out of phase with the packet by one cycle - see "maven/ITF/ATLOData/ATLO/SelfTest/SelfTest_ATLO_20131001_pfp_all_l0_v1.dat"

	ndis=0
	get_data,'mvn_STA_D1_DATA',data=t
	if size(/type,t) eq 8 then begin
		npts=16384									; 32Ex4Dx16Ax8M
		np = 16										; np is number of packets per measurement, npts/1024
		ind1 = where(t.x gt 0, nn)
		tt=t.x[0:nn-1]

; 		find out-of-sequence times -- not expected for science data 
;			might occur if an averaging time is changed and the change does not occur on the correct 2^n boundary

; the following "if" makes sure there are at least two measurements so the out-of-order time correction works
	if nn ge 2*np then begin

		ind = where (tt[0:nn-1-np] gt tt[np:nn-1],nind)							
		if nind gt 0 then begin					
			print,' ERROR - times out of sequence, D1 packet'  
			print,' # of out of sequence times = ',nind	
			for i=0,nind-1 do begin	
				print,i,tt[ind[i]]-tt[ind[i]+np],'  ',time_string(tt[ind[i]]),'  ',time_string(tt[ind[i]+np]),'  ',time_string(tt[ind[i]+2*np])
			endfor
		endif

;		form some diagnostic tplot structures

		get_data,'mvn_STA_D1_DIAG',data=diag
		en = (diag.y[0:nn-1] AND 15)
		dt=0.1
			store_data,'mvn_sta_D1_DIAG_EN',data={x:tt+en*dt,y:en}
				ylim,'mvn_sta_D1_DIAG_EN',-1,np,0
			get_data,'mvn_STA_D1_SEQ_CNTR',data=tmp2
			store_data,'mvn_sta_D1_SEQ_CNTR_EN',data={x:tt+en*dt,y:tmp2.y[0:nn-1]}
			store_data,'mvn_sta_D1_DATA_EN',data={x:tt+en*dt,y:total(t.y[0:nn-1,*],2)}

;		find index numbers for the first packets of a np packet set

;			ind1 = where(tt[0:nn-1-np] eq tt[np-1:nn-2],ndis1)					; make sure there are "np" packets in a row with same time, old code w/ error
			ind1 = where(tt[0:nn-np] eq tt[np-1:nn-1],ndis1)					; make sure there are "np" packets in a row with same time, changed 20140106
			ind2 = where(tt[ind1[0:ndis1-1]] le tt[[ind1[1:ndis1-1],ind1[ndis1-1]]],ndis)		; throw out any np-packet group that is out of time order, changed 20140106
			ind  = ind1[ind2] 						
			if ind[ndis-1]+2*np-1 eq nn-1 then begin
				ind=[ind,ind[ndis-1]+np]
				ndis=ndis+1
			endif

;		ind = where(en eq 0,ndis)									; old code, ndis is number of complete distributions
;		if ind[ndis-1]+np-1 gt nn-1 then ndis=ndis-1							; old code, eliminate last distribution if not complete

		if ndis ge 1 then begin

			aa = indgen(np)#replicate(1,ndis)							; extract out the proper complete packets
			bb = replicate(1,np)#ind
			dat = t.y[aa+bb,*]

			tdis = tt[ind[0:ndis-1]]

			get_data,'mvn_STA_D1_MODE',data=md
				md1 = md.y[ind[0:ndis-1]] and 127
				md2 = md.y[ind[0:ndis-1]]and 15
				rt2 = (md.y[ind[0:ndis-1]] and 112)/16

			get_data,'mvn_STA_D1_AVG',data=cavg
			avg = 2^(cavg.y[ind[0:ndis-1]] and 7)
			sum = (cavg.y[ind[0:ndis-1]] and 8)/8
			avg2 = sum*avg > 1

;	correct D1 mode transitions using C6 data if it is available
		get_data,'mvn_sta_C6_mode',data=md6
		if size(/type,md6) eq 8 then begin
			get_data,'mvn_sta_C6_rate',data=rt6
			md2 = fix(round(interp(md6.y,md6.x,tdis)))
			rt2 = fix(round(interp(rt6.y,rt6.x,tdis)))
			md1 = rt2*16+md2	 
		endif

			tt1 = tdis - 2.*avg2 									; corrected timing for averaging, kluge for header mismatch
			tt2 = tdis + 2.*avg2 
;			if ndis gt 2 then begin
;				tt2[0:ndis-2] = tt2[0:ndis-2] < tt1[1:ndis-1]
;				tt3 = (tt1 + tt2)/2.
;				print,tt3-tt
;				tt = tt3
;			endif

			get_data,'mvn_STA_D1_ATTEN',data=catt							; attenuator state
			att0 = (catt.y[ind[0:ndis-1]] and replicate(192,ndis))/64
			if ndis ge 2 then ind0 = where(att0[0:ndis-2] ne att0[1:ndis-1],cnt0) else cnt0=0
			if cnt0 ne 0 then begin
				for i=0,cnt0-1 do begin
					inds = ind0[i]
					idelay = fix(2/avg[inds])
;					if idelay gt 0 then att0[inds+1:(inds+idelay)<(nn-1)] = att0[inds]
					if idelay gt 0 then att0[inds+1:(inds+idelay)<(ndis-1)] = att0[inds]
				endfor
			endif

;	correct D1 attenuator transitions using C6 data if it is available
		get_data,'mvn_sta_C6_att',data=att6
		if size(/type,att6) eq 8 then att0 = fix(round(interp(att6.y,att6.x,tdis)))<3

			header = 256l^3*md.y[ind[0:ndis-1]] + 256l^2*cavg.y[ind[0:ndis-1]] + 256l*catt.y[ind[0:ndis-1]] + diag.y[ind[0:ndis-1]]

			store_data,'mvn_sta_D1_mode',data={x:tdis,y:md2}
				ylim,'mvn_sta_D1_mode',-1,7,0
			store_data,'mvn_sta_D1_att',data={x:tdis,y:att0}
				ylim,'mvn_sta_D1_att',-1,4,0

;			swp_ind = md2swp[md1]									; old version
;			swp_ind = conf2swp[fix(interp((config4.y and 255)*1.,config4.x,tdis)+.5),md2]					
			swp_ind = conf2swp[fix(interp((config4.y and 511)*1.,config4.x,tdis)+.5),md2]					
				eprom_ver = fix(interp((config4.y and 255)*1.,config4.x,tdis)+.5)
				if tdis[0] lt time_double('2014-10-1/0') then eprom_ver[*]=0

			energy=nrg[swp_ind,*]
			energy=total(reform(energy,ndis,2,32),2)/2.
			mass=mas[swp_ind,0,*]
			mass=total(reform(mass,ndis,8,8),2)/8.						; because there are only 8 masses
			deflection = total(reform(def[swp_ind,62,*],ndis,4,4),2)/4.

			tmp=decomp19[reform(transpose(reform(dat,np,ndis,16,8,4,2),[1,5,0,4,2,3]),ndis,32,4,16,8)]	; [time,en,def,an,ma]

			store_data,'mvn_sta_D1_P4C_E',data={x:tdis,y:total(total(total(tmp,5),4),3),v:energy}
			store_data,'mvn_sta_D1_P4C_D',data={x:tdis,y:total(total(total(tmp,5),4),2),v:deflection}
			store_data,'mvn_sta_D1_P4C_A',data={x:tdis,y:total(total(total(tmp,5),3),2),v:22.5*(findgen(16)-7.)}
			store_data,'mvn_sta_D1_P4C_M',data={x:tdis,y:total(total(total(tmp,4),3),2),v:mass}
			store_data,'mvn_sta_D1_P4C_tot',data={x:tdis,y:total(total(total(total(tmp,5),4),3),2)}
			store_data,'mvn_sta_D1_P4C_all',data={x:tdis,y:reform(tmp,ndis,npts),v:indgen(npts)}

			ylim,'mvn_sta_D1_P4C_tot',0,0,1
			ylim,'mvn_sta_D1_P4C_E',.4,40000.,1
			ylim,'mvn_sta_D1_P4C_D',-45,45,0
			ylim,'mvn_sta_D1_P4C_A',-180,200,0
			ylim,'mvn_sta_D1_P4C_M',.5,100,1
			zlim,'mvn_sta_D1_P4C_E',1,1.e4,1
			zlim,'mvn_sta_D1_P4C_D',1,1.e4,1
			zlim,'mvn_sta_D1_P4C_A',1,1.e4,1
			zlim,'mvn_sta_D1_P4C_M',1,1.e4,1
			options,'mvn_sta_D1_P4C_E',datagap=64.
			options,'mvn_sta_D1_P4C_D',datagap=64.
			options,'mvn_sta_D1_P4C_A',datagap=64.
			options,'mvn_sta_D1_P4C_M',datagap=64.
			options,'mvn_sta_D1_P4C_tot',datagap=64.
			options,'mvn_sta_D1_P4C_E','spec',1
			options,'mvn_sta_D1_P4C_D','spec',1
			options,'mvn_sta_D1_P4C_A','spec',1
			options,'mvn_sta_D1_P4C_M','spec',1
			options,'mvn_sta_D1_P4C_E',ytitle='sta!CP4C-D1!C!CEnergy!CeV'
			options,'mvn_sta_D1_P4C_D',ytitle='sta!CP4C-D1!C!CDef!Ctheta'
			options,'mvn_sta_D1_P4C_A',ytitle='sta!CP4C-D1!C!CAnode!Cphi'
			options,'mvn_sta_D1_P4C_M',ytitle='sta!CP4C-D1!C!CMass!Camu'
		endif
	endif
	endif


; Make D1 common block

   if size(/type,t) eq 8 and ndis ge 2 then begin

	nenergy = 32
	avg_nrg = 64/nenergy
	ndef = 4
	avg_def=16/ndef
	nanode = 16
	avg_an = 16/nanode
	nbins = ndef*nanode
	nmass = 8

	magf = replicate(0.,ndis)#[0.,0.,0.]
	quat_sc  = replicate(0.,ndis)#[0.,0.,0.,0.]
	quat_mso = replicate(0.,ndis)#[0.,0.,0.,0.]
	bins_sc = fix(replicate(1,ndis)#replicate(1,nbins))
	quality_flag = intarr(ndis)
	pos_sc_mso = replicate(0.,ndis)#[0.,0.,0.]
	bkg   = fltarr(ndis,nenergy,nbins,nmass)
	dead   = fltarr(ndis,nenergy,nbins,nmass) & dead[*]=1.

;	energy2  = reform(reform(total(reform(nrg,n_swp,avg_nrg,nenergy),2)/avg_nrg,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)
;	denergy2 = reform(reform(total(reform(dnrg,n_swp,avg_nrg,nenergy),2)       ,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)

	an_ma = replicate(1.,nbins*nmass) 
	energy2  = reform(reform(total(reform(nrg,n_swp,avg_nrg,nenergy),2)/avg_nrg,n_swp*nenergy) # an_ma,n_swp,nenergy,nbins,nmass)
	denergy2 = reform(reform(total(reform(dnrg,n_swp,avg_nrg,nenergy),2)       ,n_swp*nenergy) # an_ma,n_swp,nenergy,nbins,nmass)

;	gf[n_swp,64,16,16,4]	sum geometric factor over energy, deflection and anode, why is there a normalization???????				; gf[iswp,en,def,an,att]
;	gf2 = reform(total(total(reform(gf,n_swp,avg_nrg,nenergy,avg_def,ndef,16,4),4),2),n_swp,nenergy,nbins,4)/avg_nrg/avg_def			;
	gf2 = reform(total(total(reform(gf,n_swp,avg_nrg,nenergy,avg_def,ndef,16,4),4),2),n_swp,nenergy,nbins,4)/(avg_nrg*avg_def)			;

; junk dna
;	gf2 = fltarr(n_swp,nenergy,ndef,nanode,4)
;	gf1 = reform(total(total(reform(gf,n_swp,avg_nrg,nenergy,avg_def,ndef,16,4),4),2),n_swp,nenergy,ndef*16,4)		;
;	gf1 = total(reform(gf,n_swp,avg_nrg,nenergy,16,16,4),2)		;
;	for i=0,n_swp-1 do gf2[i,*,*] = total(total(gf1[i,*,swp2gfdf[i,0]:swp2gfdf[i,1],swp2gfan[i,0]:swp2gfan[i,1],*],3),3)/(swp2gfdf[i,1]-swp2gfdf[i,0]+1.)/(swp2gfan[i,1]-swp2gfan[i,0]+1)
;	for i=0,n_swp-1 do gf2[i,*,*] = total(total(gf1[i,*,swp2gfdf[i,0]:swp2gfdf[i,1],swp2gfan[i,0]:swp2gfan[i,1],*],3),3)
;	for i=0,n_swp-1 do gf2[i,*,*,*,*] = total(total(gf1[i,*,swp2gfdf[i,0]:swp2gfdf[i,1],swp2gfan[i,0]:swp2gfan[i,1],*],3),3)

; the following line assumes a constant efficiency as a default until other calibration code can be developed
;    a proper efficiency calibration is handled mvn_sta_dead_load.pro

	eff2 = fltarr(128,nenergy,nbins,nmass) & eff2[*]=def_eff  & eff_ind=intarr(ndis)

;	mlut = md2mlut(md1)
	mlut = swp2mlut(swp_ind)
	mass_arr=total(total(reform(mas,n_swp,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	tof_arr=total(total(reform(tof,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	twt_arr=total(total(reform(twt,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/avg_nrg

	mass_arr=transpose(reform(reform(mass_arr,n_swp*nenergy*nmass)#replicate(1.,nbins),n_swp,nenergy,nmass,nbins),[0,1,3,2])
	tof_arr=transpose(reform(reform(tof_arr,n_mlut*nenergy*nmass)#replicate(1.,nbins),n_mlut,nenergy,nmass,nbins),[0,1,3,2])
	twt_arr=transpose(reform(reform(twt_arr,n_mlut*nenergy*nmass)#replicate(1.,nbins),n_mlut,nenergy,nmass,nbins),[0,1,3,2])

; the following uses def(n_swp,64,16) to generate theta and phi arrays that depend on iswp(md1)

	theta = reform(reform(total(total(reform(def,n_swp,avg_nrg,nenergy,avg_def,ndef),4),2),n_swp*nenergy*ndef)#replicate(1.,nanode*nmass),n_swp,nenergy,nbins,nmass)/avg_nrg/avg_def
	dtheta = reform(reform(total(reform(abs(def(*,*,15)-def(*,*,0))/(15.),n_swp,avg_nrg,nenergy),2),n_swp*nenergy)#replicate(1.,nbins*nmass),n_swp,nenergy,nbins,nmass)/avg_nrg*avg_def
	phi = 22.5*reform(reform(replicate(1.,n_swp*nenergy*ndef)#(findgen(nanode)-7.),1l*n_swp*nenergy*nbins)#replicate(1.,nmass),n_swp,nenergy,nbins,nmass)
	dphi = fltarr(n_swp,nenergy,nbins,nmass) & dphi(*)=22.5
	domega = dphi*dtheta/!radeg^2

	d1_dat= {project_name:		'MAVEN',				$
		spacecraft:		'0', 					$
;		data_name:		'D1 Energy-Angle-Mass', 		$
;		apid:			'D1',					$
		data_name:		'd1 32e4d16a8m', 			$
		apid:			'd1',					$
		units_name: 		'counts', 				$
		units_procedure: 	'mvn_sta_convert_units', 		$
		valid: 			replicate(1,ndis), 			$
		quality_flag: 		quality_flag, 				$

		time:			tt1,					$
		end_time:		tt2,					$
		delta_t:		tt2-tt1,				$
		integ_t: 		(tt2-tt1)/(nenergy*ndef)*dt_cor,	$	

		eprom_ver:		eprom_ver,				$
		header:			header,					$
		mode:			md2,					$
		rate:			rt2,					$
		swp_ind:		swp_ind,				$
		mlut_ind:		mlut,					$
		eff_ind:		eff_ind,				$
		att_ind:		att0,					$

		nenergy: 		nenergy,				$
		energy: 		energy2, 				$
		denergy: 		denergy2, 				$

		nbins: 			nbins, 					$
		bins: 			replicate(1,nbins), 			$
		ndef:			ndef,					$
		nanode:			nanode,					$

		theta: 			theta,  				$
		dtheta: 		dtheta,  				$
		phi: 			phi,  					$
		dphi: 			dphi, 					$
		domega: 		domega,  				$

		gf: 			gf2, 					$
		eff: 			eff2,	 				$

		geom_factor: 		geom_factor,				$
		dead1: 			dead1,					$
		dead2: 			dead2,					$
		dead3: 			dead3,					$

		nmass:			nmass,					$
		mass: 			1.0438871e-02, 				$
		mass_arr:		mass_arr,				$
		tof_arr:		tof_arr,				$
		twt_arr:		twt_arr,				$

		charge: 		1., 					$
		sc_pot: 		replicate(0.,ndis),			$
		magf:	 		magf, 					$
		quat_sc:	 	quat_sc, 				$
		quat_mso:	 	quat_mso, 				$
		bins_sc:		bins_sc,				$
		pos_sc_mso:		pos_sc_mso,				$

		bkg:	 		bkg,		 			$
		dead:	 		dead,		 			$

		data:			reform(tmp,ndis,nenergy,nbins,nmass)}

		common mvn_d1,mvn_d1_ind,mvn_d1_dat & mvn_d1_dat=d1_dat & mvn_d1_ind=0l

   endif
endif


;***************************************************************************************************************
; APID D2


if keyword_set(apids) then test = fix((total(apids eq 'd2') + total(apids eq 'D2')) < 1) else test=0
if not keyword_set(apids) or test then begin
print,'Processing apid d2'

; the header bits (diagnostic, mode, averaging, atten) may be out of phase with the packet by one cycle - see "maven/ITF/ATLOData/ATLO/SelfTest/SelfTest_ATLO_20131001_pfp_all_l0_v1.dat"

	ndis=0
	get_data,'mvn_STA_D2_DATA',data=t
	if size(/type,t) eq 8 then begin
		npts=4096									; 32Ex1Dx16Ax8M
		np = 4										; np is number of packets per measurement, npts/1024
		ind1 = where(t.x gt 0, nn)
		tt=t.x[0:nn-1]

; 		find out-of-sequence times -- not expected for science data 
;			might occur if an averaging time is changed and the change does not occur on the correct 2^n boundary

; the following "if" makes sure there are at least two measurements so the out-of-order time correction works
	if nn ge 2*np then begin

		ind = where (tt[0:nn-1-np] gt tt[np:nn-1],nind)							
		if nind gt 0 then begin					
			print,' ERROR - times out of sequence, D2 packet'  
			print,' # of out of sequence times = ',nind	
			for i=0,nind-1 do begin	
				print,i,tt[ind[i]]-tt[ind[i]+np],'  ',time_string(tt[ind[i]]),'  ',time_string(tt[ind[i]+np]),'  ',time_string(tt[ind[i]+2*np])
			endfor
		endif

;		form some diagnostic tplot structures

		get_data,'mvn_STA_D2_DIAG',data=diag
		en = (diag.y[0:nn-1] AND 15)
		dt=0.1
			store_data,'mvn_sta_D2_DIAG_EN',data={x:tt+en*dt,y:en}
				ylim,'mvn_sta_D2_DIAG_EN',-1,np,0
			get_data,'mvn_STA_D2_SEQ_CNTR',data=tmp2
			store_data,'mvn_sta_D2_SEQ_CNTR_EN',data={x:tt+en*dt,y:tmp2.y[0:nn-1]}
			store_data,'mvn_sta_D2_DATA_EN',data={x:tt+en*dt,y:total(t.y[0:nn-1,*],2)}

;		find index numbers for the first packets of a np packet set

;			ind1 = where(tt[0:nn-1-np] eq tt[np-1:nn-2],ndis1)					; make sure there are "np" packets in a row with same time, old code w/ error
			ind1 = where(tt[0:nn-np] eq tt[np-1:nn-1],ndis1)					; make sure there are "np" packets in a row with same time, changed 20140106
			ind2 = where(tt[ind1[0:ndis1-1]] le tt[[ind1[1:ndis1-1],ind1[ndis1-1]]],ndis)		; throw out any np-packet group that is out of time order, changed 20140106
			ind  = ind1[ind2] 						
			if ind[ndis-1]+2*np-1 eq nn-1 then begin
				ind=[ind,ind[ndis-1]+np]
				ndis=ndis+1
			endif

;		ind = where(en eq 0,ndis)							; old code, ndis is number of complete distributions
;		if ind[ndis-1]+np-1 gt nn-1 then ndis=ndis-1					; old code, eliminate last distribution if not complete

		if ndis ge 1 then begin

			aa = indgen(np)#replicate(1,ndis)							; extract out the proper complete packets
			bb = replicate(1,np)#ind
			dat = t.y[aa+bb,*]

			tdis = tt[ind[0:ndis-1]]

			get_data,'mvn_STA_D2_MODE',data=md
				md1 = md.y[ind[0:ndis-1]] and 127
				md2 = md.y[ind[0:ndis-1]]and 15
				rt2 = (md.y[ind[0:ndis-1]] and 112)/16

			get_data,'mvn_STA_D2_AVG',data=cavg
			avg = 2^(cavg.y[ind[0:ndis-1]] and 7)
			sum = (cavg.y[ind[0:ndis-1]] and 8)/8
			avg2 = sum*avg > 1

;	correct D2 mode transitions using C6 data if it is available
		get_data,'mvn_sta_C6_mode',data=md6
		if size(/type,md6) eq 8 then begin
			get_data,'mvn_sta_C6_rate',data=rt6
			md2 = fix(round(interp(md6.y,md6.x,tdis)))
			rt2 = fix(round(interp(rt6.y,rt6.x,tdis)))
		endif
		md1 = rt2*16+md2	 

			tt1 = tdis - 2.*avg2 									; corrected timing for averaging, kluge for header mismatch
			tt2 = tdis + 2.*avg2 

			get_data,'mvn_STA_D2_ATTEN',data=catt						; attenuator state
			att0 = (catt.y[ind[0:ndis-1]] and replicate(192,ndis))/64
			if ndis ge 2 then ind0 = where(att0[0:ndis-2] ne att0[1:ndis-1],cnt0) else cnt0=0
			if cnt0 ne 0 then begin
				for i=0,cnt0-1 do begin
					inds = ind0[i]
					idelay = fix(2/avg[inds])
;					if idelay gt 0 then att0[inds+1:(inds+idelay)<(nn-1)] = att0[inds]
					if idelay gt 0 then att0[inds+1:(inds+idelay)<(ndis-1)] = att0[inds]
				endfor
			endif

;	correct D2 attenuator transitions using C6 data if it is available
		get_data,'mvn_sta_C6_att',data=att6
		if size(/type,att6) eq 8 then att0 = fix(round(interp(att6.y,att6.x,tdis)))<3

			header = 256l^3*md.y[ind[0:ndis-1]] + 256l^2*cavg.y[ind[0:ndis-1]] + 256l*catt.y[ind[0:ndis-1]] + diag.y[ind[0:ndis-1]]

			store_data,'mvn_sta_D2_mode',data={x:tdis,y:md2}
				ylim,'mvn_sta_D2_mode',-1,7,0
			store_data,'mvn_sta_D2_att',data={x:tdis,y:att0}
				ylim,'mvn_sta_D2_att',-1,4,0

;			swp_ind = md2swp[md1]									; old version
;			swp_ind = conf2swp[fix(interp((config4.y and 255)*1.,config4.x,tdis)+.5),md2]					
			swp_ind = conf2swp[fix(interp((config4.y and 511)*1.,config4.x,tdis)+.5),md2]					
				eprom_ver = fix(interp((config4.y and 255)*1.,config4.x,tdis)+.5)
				if tdis[0] lt time_double('2014-10-1/0') then eprom_ver[*]=0

			energy=nrg[swp_ind,*]
			energy=total(reform(energy,ndis,2,32),2)/2.
			mass=mas[swp_ind,0,*]
			mass=total(reform(mass,ndis,8,8),2)/8.						; because there are only 8 masses

			tmp=decomp19[reform(transpose(reform(dat,np,ndis,16,8,8),[1,4,0,2,3]),ndis,32,16,8)]	; [time,en,an,ma]

			store_data,'mvn_sta_D2_P4D_E',data={x:tdis,y:total(total(tmp,4),3),v:energy}
			store_data,'mvn_sta_D2_P4D_A',data={x:tdis,y:total(total(tmp,4),2),v:22.5*(findgen(16)-7.)}
			store_data,'mvn_sta_D2_P4D_M',data={x:tdis,y:total(total(tmp,3),2),v:mass}
			store_data,'mvn_sta_D2_P4D_tot',data={x:tdis,y:total(total(total(tmp,4),3),2)}
			store_data,'mvn_sta_D2_P4D_all',data={x:tdis,y:reform(tmp,ndis,npts),v:indgen(npts)}

			ylim,'mvn_sta_D2_P4D_tot',0,0,1
			ylim,'mvn_sta_D2_P4D_E',.4,40000.,1
			ylim,'mvn_sta_D2_P4D_A',-180,200,0
			ylim,'mvn_sta_D2_P4D_M',.5,100,1
			zlim,'mvn_sta_D2_P4D_E',1,1.e4,1
			zlim,'mvn_sta_D2_P4D_A',1,1.e4,1
			zlim,'mvn_sta_D2_P4D_M',1,1.e4,1
			options,'mvn_sta_D2_P4D_E',datagap=256.
			options,'mvn_sta_D2_P4D_A',datagap=256.
			options,'mvn_sta_D2_P4D_M',datagap=256.
			options,'mvn_sta_D2_P4D_tot',datagap=256.
			options,'mvn_sta_D2_P4D_E','spec',1
			options,'mvn_sta_D2_P4D_A','spec',1
			options,'mvn_sta_D2_P4D_M','spec',1
			options,'mvn_sta_D2_P4D_E',ytitle='sta!CP4D-D2!C!CEnergy!CeV'
			options,'mvn_sta_D2_P4D_A',ytitle='sta!CP4D-D2!C!CAnode!Cphi'
			options,'mvn_sta_D2_P4D_M',ytitle='sta!CP4D-D2!C!CMass!Camu'
		endif
	endif
	endif


; Make D2 common block

   if size(/type,t) eq 8 and ndis ge 2 then begin

	nenergy = 32
	avg_nrg = 64/nenergy
	ndef = 1
	avg_def=16/ndef
	nanode = 16
	avg_an = 16/nanode
	nbins = ndef*nanode
	nmass = 8

	magf = replicate(0.,ndis)#[0.,0.,0.]
	quat_sc  = replicate(0.,ndis)#[0.,0.,0.,0.]
	quat_mso = replicate(0.,ndis)#[0.,0.,0.,0.]
	bins_sc = fix(replicate(1,ndis)#replicate(1,nbins))
	quality_flag = intarr(ndis)
	pos_sc_mso = replicate(0.,ndis)#[0.,0.,0.]
	bkg   = fltarr(ndis,nenergy,nbins,nmass)
	dead   = fltarr(ndis,nenergy,nbins,nmass) & dead[*]=1.

;	energy2  = reform(reform(total(reform(nrg,n_swp,avg_nrg,nenergy),2)/avg_nrg,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)
;	denergy2 = reform(reform(total(reform(dnrg,n_swp,avg_nrg,nenergy),2)       ,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)

	an_ma = replicate(1.,nbins*nmass) 
	energy2  = reform(reform(total(reform(nrg,n_swp,avg_nrg,nenergy),2)/avg_nrg,n_swp*nenergy) # an_ma,n_swp,nenergy,nbins,nmass)
	denergy2 = reform(reform(total(reform(dnrg,n_swp,avg_nrg,nenergy),2)       ,n_swp*nenergy) # an_ma,n_swp,nenergy,nbins,nmass)

;	gf[n_swp,64,16,16,4]	sum geometric factor over energy, deflection and anode, why is there a normalization???????				; gf[iswp,en,def,an,att]
;	gf2 = reform(total(total(reform(gf,n_swp,avg_nrg,nenergy,avg_def,ndef,16,4),4),2),n_swp,nenergy,nbins,4)/avg_nrg/avg_def			;
;	gf2 = reform(total(total(reform(gf,n_swp,avg_nrg,nenergy,avg_def,ndef,16,4),4),2),n_swp,nenergy,nbins,4)/(avg_nrg*avg_def)			;
	gf2 = reform(total(reform(gf[*,*,7,*,*],n_swp,avg_nrg,nenergy,16,4),2),n_swp,nenergy,nbins,4)/avg_nrg			;

; junk dna
;	gf2 = fltarr(n_swp,nenergy,ndef,nanode,4)
;	gf1 = reform(total(total(reform(gf,n_swp,avg_nrg,nenergy,avg_def,ndef,16,4),4),2),n_swp,nenergy,ndef*16,4)		;
;	gf1 = total(reform(gf,n_swp,avg_nrg,nenergy,16,16,4),2)		;
;	for i=0,n_swp-1 do gf2[i,*,*] = total(total(gf1[i,*,swp2gfdf[i,0]:swp2gfdf[i,1],swp2gfan[i,0]:swp2gfan[i,1],*],3),3)/(swp2gfdf[i,1]-swp2gfdf[i,0]+1.)/(swp2gfan[i,1]-swp2gfan[i,0]+1)
;	for i=0,n_swp-1 do gf2[i,*,*] = total(total(gf1[i,*,swp2gfdf[i,0]:swp2gfdf[i,1],swp2gfan[i,0]:swp2gfan[i,1],*],3),3)
;	for i=0,n_swp-1 do gf2[i,*,*,*,*] = total(total(gf1[i,*,swp2gfdf[i,0]:swp2gfdf[i,1],swp2gfan[i,0]:swp2gfan[i,1],*],3),3)

; the following line assumes a constant efficiency as a default until other calibration code can be developed
;    a proper efficiency calibration is handled mvn_sta_dead_load.pro

	eff2 = fltarr(128,nenergy,nbins,nmass) & eff2[*]=def_eff  & eff_ind=intarr(ndis)

;	mlut = md2mlut(md1)
	mlut = swp2mlut(swp_ind)
	mass_arr=total(total(reform(mas,n_swp,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	tof_arr=total(total(reform(tof,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	twt_arr=total(total(reform(twt,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/avg_nrg

	mass_arr=transpose(reform(reform(mass_arr,n_swp*nenergy*nmass)#replicate(1.,nbins),n_swp,nenergy,nmass,nbins),[0,1,3,2])
	tof_arr=transpose(reform(reform(tof_arr,n_mlut*nenergy*nmass)#replicate(1.,nbins),n_mlut,nenergy,nmass,nbins),[0,1,3,2])
	twt_arr=transpose(reform(reform(twt_arr,n_mlut*nenergy*nmass)#replicate(1.,nbins),n_mlut,nenergy,nmass,nbins),[0,1,3,2])

; the following uses def(n_swp,64,16) to generate theta and phi arrays that depend on iswp(md1)

	theta = reform(reform(total(total(reform(def,n_swp,avg_nrg,nenergy,avg_def,ndef),4),2),n_swp*nenergy*ndef)#replicate(1.,nanode*nmass),n_swp,nenergy,nbins,nmass)/avg_nrg/avg_def
	dtheta = reform(reform(total(reform(abs(def(*,*,15)-def(*,*,0))/(15.),n_swp,avg_nrg,nenergy),2),n_swp*nenergy)#replicate(1.,nbins*nmass),n_swp,nenergy,nbins,nmass)/avg_nrg*avg_def 
	dtheta = dtheta > 6.
	phi = 22.5*reform(reform(replicate(1.,n_swp*nenergy*ndef)#(findgen(nanode)-7.),1l*n_swp*nenergy*nbins)#replicate(1.,nmass),n_swp,nenergy,nbins,nmass)
	dphi = fltarr(n_swp,nenergy,nbins,nmass) & dphi(*)=22.5
	domega = dphi*dtheta/!radeg^2

	d2_dat= {project_name:		'MAVEN',				$
		spacecraft:		'0', 					$
;		data_name:		'D2 Energy-Angle-Mass', 		$
;		apid:			'D2',					$
		data_name:		'd2 32e16a8m', 				$
		apid:			'd2',					$
		units_name: 		'counts', 				$
		units_procedure: 	'mvn_sta_convert_units', 		$
		valid: 			replicate(1,ndis), 			$
		quality_flag: 		quality_flag, 				$

		time:			tt1,					$
		end_time:		tt2,					$
		delta_t:		tt2-tt1,				$
		integ_t: 		(tt2-tt1)/(nenergy*ndef)*dt_cor,	$	

		eprom_ver:		eprom_ver,				$
		header:			header,					$
		mode:			md2,					$
		rate:			rt2,					$
		swp_ind:		swp_ind,				$
		mlut_ind:		mlut,					$
		eff_ind:		eff_ind,				$
		att_ind:		att0,					$

		nenergy: 		nenergy,				$
		energy: 		energy2, 				$
		denergy: 		denergy2, 				$

		nbins: 			nbins, 					$
		bins: 			replicate(1,nbins), 			$
		ndef:			ndef,					$
		nanode:			nanode,					$

		theta: 			theta,  				$
		dtheta: 		dtheta,  				$
		phi: 			phi,  					$
		dphi: 			dphi, 					$
		domega: 		domega,  				$

		gf: 			gf2, 					$
		eff: 			eff2,	 				$

		geom_factor: 		geom_factor,				$
		dead1: 			dead1,					$
		dead2: 			dead2,					$
		dead3: 			dead3,					$

		nmass:			nmass,					$
		mass: 			1.0438871e-02, 				$
		mass_arr:		mass_arr,				$
		tof_arr:		tof_arr,				$
		twt_arr:		twt_arr,				$

		charge: 		1., 					$
		sc_pot: 		replicate(0.,ndis),			$
		magf:	 		magf, 					$
		quat_sc:	 	quat_sc, 				$
		quat_mso:	 	quat_mso, 				$
		bins_sc:		bins_sc,				$
		pos_sc_mso:		pos_sc_mso,				$

		bkg:	 		bkg,		 			$
		dead:	 		dead,		 			$

		data:			reform(tmp,ndis,nenergy,nbins,nmass)}

		common mvn_d2,mvn_d2_ind,mvn_d2_dat & mvn_d2_dat=d2_dat & mvn_d2_ind=0l

   endif
endif


;***************************************************************************************************************
; APID D3


if keyword_set(apids) then test = fix((total(apids eq 'd3') + total(apids eq 'D3')) < 1) else test=0
if not keyword_set(apids) or test then begin
print,'Processing apid d3'

; the header bits (diagnostic, mode, averaging, atten) may be out of phase with the packet by one cycle - see "maven/ITF/ATLOData/ATLO/SelfTest/SelfTest_ATLO_20131001_pfp_all_l0_v1.dat"

	ndis=0
	get_data,'mvn_STA_D3_DATA',data=t
	if size(/type,t) eq 8 then begin
		npts=4096									; 32Ex1Dx16Ax8M
		np = 4										; np is number of packets per measurement, npts/1024
		ind1 = where(t.x gt 0, nn)
		tt=t.x[0:nn-1]

; 		find out-of-sequence times -- not expected for science data 
;			might occur if an averaging time is changed and the change does not occur on the correct 2^n boundary

; the following "if" makes sure there are at least two measurements so the out-of-order time correction works
	if nn ge 2*np then begin

		ind = where (tt[0:nn-1-np] gt tt[np:nn-1],nind)							
		if nind gt 0 then begin					
			print,' ERROR - times out of sequence, D3 packet'  
			print,' # of out of sequence times = ',nind	
			for i=0,nind-1 do begin	
				print,i,tt[ind[i]]-tt[ind[i]+np],'  ',time_string(tt[ind[i]]),'  ',time_string(tt[ind[i]+np]),'  ',time_string(tt[ind[i]+2*np])
			endfor
		endif

;		form some diagnostic tplot structures

		get_data,'mvn_STA_D3_DIAG',data=diag
		en = (diag.y[0:nn-1] AND 15)
		dt=0.1
			store_data,'mvn_sta_D3_DIAG_EN',data={x:tt+en*dt,y:en}
				ylim,'mvn_sta_D3_DIAG_EN',-1,np,0
			get_data,'mvn_STA_D3_SEQ_CNTR',data=tmp2
			store_data,'mvn_sta_D3_SEQ_CNTR_EN',data={x:tt+en*dt,y:tmp2.y[0:nn-1]}
			store_data,'mvn_sta_D3_DATA_EN',data={x:tt+en*dt,y:total(t.y[0:nn-1,*],2)}

;		find index numbers for the first packets of a np packet set

;			ind1 = where(tt[0:nn-1-np] eq tt[np-1:nn-2],ndis1)					; make sure there are "np" packets in a row with same time, old code w/ error
			ind1 = where(tt[0:nn-np] eq tt[np-1:nn-1],ndis1)					; make sure there are "np" packets in a row with same time, changed 20140106
			ind2 = where(tt[ind1[0:ndis1-1]] le tt[[ind1[1:ndis1-1],ind1[ndis1-1]]],ndis)		; throw out any np-packet group that is out of time order, changed 20140106
			ind  = ind1[ind2] 						
			if ind[ndis-1]+2*np-1 eq nn-1 then begin
				ind=[ind,ind[ndis-1]+np]
				ndis=ndis+1
			endif

;		ind = where(en eq 0,ndis)							; ndis is number of complete distributions
;		if ind[ndis-1]+np-1 gt nn-1 then ndis=ndis-1					; eliminate last distribution if not complete

		if ndis ge 1 then begin

			aa = indgen(np)#replicate(1,ndis)							; extract out the proper complete packets
			bb = replicate(1,np)#ind
			dat = t.y[aa+bb,*]

			tdis = tt[ind[0:ndis-1]]

			get_data,'mvn_STA_D3_MODE',data=md
				md1 = md.y[ind[0:ndis-1]] and 127
				md2 = md.y[ind[0:ndis-1]]and 15
				rt2 = (md.y[ind[0:ndis-1]] and 112)/16

			get_data,'mvn_STA_D3_AVG',data=cavg
			avg = 2^(cavg.y[ind[0:ndis-1]] and 7)
			sum = (cavg.y[ind[0:ndis-1]] and 8)/8
			avg2 = sum*avg > 1

;	correct D3 mode transitions using C6 data if it is available
		get_data,'mvn_sta_C6_mode',data=md6
		if size(/type,md6) eq 8 then begin
			get_data,'mvn_sta_C6_rate',data=rt6
			md2 = fix(round(interp(md6.y,md6.x,tdis)))
			rt2 = fix(round(interp(rt6.y,rt6.x,tdis)))
			md1 = rt2*16+md2	 
		endif

			tt1 = tdis - 2.*avg2 									; corrected timing for averaging, kluge for header mismatch
			tt2 = tdis + 2.*avg2 

			get_data,'mvn_STA_D3_ATTEN',data=catt						; attenuator state
			att0 = (catt.y[ind[0:ndis-1]] and replicate(192,ndis))/64
			if ndis ge 2 then ind0 = where(att0[0:ndis-2] ne att0[1:ndis-1],cnt0) else cnt0=0
			if cnt0 ne 0 then begin
				for i=0,cnt0-1 do begin
					inds = ind0[i]
					idelay = fix(2/avg[inds])
;					if idelay gt 0 then att0[inds+1:(inds+idelay)<(nn-1)] = att0[inds]
					if idelay gt 0 then att0[inds+1:(inds+idelay)<(ndis-1)] = att0[inds]
				endfor
			endif

;	correct D3 attenuator transitions using C6 data if it is available
		get_data,'mvn_sta_C6_att',data=att6
		if size(/type,att6) eq 8 then att0 = fix(round(interp(att6.y,att6.x,tdis)))<3

			header = 256l^3*md.y[ind[0:ndis-1]] + 256l^2*cavg.y[ind[0:ndis-1]] + 256l*catt.y[ind[0:ndis-1]] + diag.y[ind[0:ndis-1]]

			store_data,'mvn_sta_D3_mode',data={x:tdis,y:md2}
				ylim,'mvn_sta_D3_mode',-1,7,0
			store_data,'mvn_sta_D3_att',data={x:tdis,y:att0}
				ylim,'mvn_sta_D3_att',-1,4,0

;			swp_ind = md2swp[md1]									; old version
;			swp_ind = conf2swp[fix(interp((config4.y and 255)*1.,config4.x,tdis)+.5),md2]					
			swp_ind = conf2swp[fix(interp((config4.y and 511)*1.,config4.x,tdis)+.5),md2]					
				eprom_ver = fix(interp((config4.y and 255)*1.,config4.x,tdis)+.5)
				if tdis[0] lt time_double('2014-10-1/0') then eprom_ver[*]=0

			energy=nrg[swp_ind,*]
			energy=total(reform(energy,ndis,2,32),2)/2.
			mass=mas[swp_ind,0,*]
			mass=total(reform(mass,ndis,8,8),2)/8.						; because there are only 8 masses

			tmp=decomp19[reform(transpose(reform(dat,np,ndis,16,8,8),[1,4,0,2,3]),ndis,32,16,8)]	; [time,en,an,ma]

			store_data,'mvn_sta_D3_P4D_E',data={x:tdis,y:total(total(tmp,4),3),v:energy}
			store_data,'mvn_sta_D3_P4D_A',data={x:tdis,y:total(total(tmp,4),2),v:22.5*(findgen(16)-7.)}
			store_data,'mvn_sta_D3_P4D_M',data={x:tdis,y:total(total(tmp,3),2),v:mass}
			store_data,'mvn_sta_D3_P4D_tot',data={x:tdis,y:total(total(total(tmp,4),3),2)}
			store_data,'mvn_sta_D3_P4D_all',data={x:tdis,y:reform(tmp,ndis,npts),v:indgen(npts)}

			ylim,'mvn_sta_D3_P4D_tot',0,0,1
			ylim,'mvn_sta_D3_P4D_E',.4,40000.,1
			ylim,'mvn_sta_D3_P4D_A',-180,200,0
			ylim,'mvn_sta_D3_P4D_M',.5,100,1
			zlim,'mvn_sta_D3_P4D_E',1,1.e4,1
			zlim,'mvn_sta_D3_P4D_A',1,1.e4,1
			zlim,'mvn_sta_D3_P4D_M',1,1.e4,1
			options,'mvn_sta_D3_P4D_E',datagap=64.
			options,'mvn_sta_D3_P4D_A',datagap=64.
			options,'mvn_sta_D3_P4D_M',datagap=64.
			options,'mvn_sta_D3_P4D_tot',datagap=64.
			options,'mvn_sta_D3_P4D_E','spec',1
			options,'mvn_sta_D3_P4D_A','spec',1
			options,'mvn_sta_D3_P4D_M','spec',1
			options,'mvn_sta_D3_P4D_E',ytitle='sta!CP4D-D3!C!CEnergy!CeV'
			options,'mvn_sta_D3_P4D_A',ytitle='sta!CP4D-D3!C!CAnode!Cphi'
			options,'mvn_sta_D3_P4D_M',ytitle='sta!CP4D-D3!C!CMass!Camu'
		endif
	endif
	endif


; Make D3 common block

   if size(/type,t) eq 8 and ndis ge 2 then begin

	nenergy = 32
	avg_nrg = 64/nenergy
	ndef = 1
	avg_def=16/ndef
	nanode = 16
	avg_an = 16/nanode
	nbins = ndef*nanode
	nmass = 8

	magf = replicate(0.,ndis)#[0.,0.,0.]
	quat_sc  = replicate(0.,ndis)#[0.,0.,0.,0.]
	quat_mso = replicate(0.,ndis)#[0.,0.,0.,0.]
	bins_sc = fix(replicate(1,ndis)#replicate(1,nbins))
	quality_flag = intarr(ndis)
	pos_sc_mso = replicate(0.,ndis)#[0.,0.,0.]
	bkg   = fltarr(ndis,nenergy,nbins,nmass)
	dead   = fltarr(ndis,nenergy,nbins,nmass) & dead[*]=1.

;	energy2  = reform(reform(total(reform(nrg,n_swp,avg_nrg,nenergy),2)/avg_nrg,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)
;	denergy2 = reform(reform(total(reform(dnrg,n_swp,avg_nrg,nenergy),2)       ,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)

	an_ma = replicate(1.,nbins*nmass) 
	energy2  = reform(reform(total(reform(nrg,n_swp,avg_nrg,nenergy),2)/avg_nrg,n_swp*nenergy) # an_ma,n_swp,nenergy,nbins,nmass)
	denergy2 = reform(reform(total(reform(dnrg,n_swp,avg_nrg,nenergy),2)       ,n_swp*nenergy) # an_ma,n_swp,nenergy,nbins,nmass)

;	gf[n_swp,64,16,16,4]	sum geometric factor over energy, deflection and anode, why is there a normalization???????				; gf[iswp,en,def,an,att]
;	gf2 = reform(total(total(reform(gf,n_swp,avg_nrg,nenergy,avg_def,ndef,16,4),4),2),n_swp,nenergy,nbins,4)/avg_nrg/avg_def			;
;	gf2 = reform(total(total(reform(gf,n_swp,avg_nrg,nenergy,avg_def,ndef,16,4),4),2),n_swp,nenergy,nbins,4)/(avg_nrg*avg_def)			;
	gf2 = reform(total(reform(gf[*,*,7,*,*],n_swp,avg_nrg,nenergy,16,4),2),n_swp,nenergy,nbins,4)/avg_nrg			;

; junk dna
;	gf2 = fltarr(n_swp,nenergy,ndef,nanode,4)
;	gf1 = reform(total(total(reform(gf,n_swp,avg_nrg,nenergy,avg_def,ndef,16,4),4),2),n_swp,nenergy,ndef*16,4)		;
;	gf1 = total(reform(gf,n_swp,avg_nrg,nenergy,16,16,4),2)		;
;	for i=0,n_swp-1 do gf2[i,*,*] = total(total(gf1[i,*,swp2gfdf[i,0]:swp2gfdf[i,1],swp2gfan[i,0]:swp2gfan[i,1],*],3),3)/(swp2gfdf[i,1]-swp2gfdf[i,0]+1.)/(swp2gfan[i,1]-swp2gfan[i,0]+1)
;	for i=0,n_swp-1 do gf2[i,*,*] = total(total(gf1[i,*,swp2gfdf[i,0]:swp2gfdf[i,1],swp2gfan[i,0]:swp2gfan[i,1],*],3),3)
;	for i=0,n_swp-1 do gf2[i,*,*,*,*] = total(total(gf1[i,*,swp2gfdf[i,0]:swp2gfdf[i,1],swp2gfan[i,0]:swp2gfan[i,1],*],3),3)

; the following line assumes a constant efficiency as a default until other calibration code can be developed
;    a proper efficiency calibration is handled mvn_sta_dead_load.pro

	eff2 = fltarr(128,nenergy,nbins,nmass) & eff2[*]=def_eff  & eff_ind=intarr(ndis)

;	mlut = md2mlut(md1)
	mlut = swp2mlut(swp_ind)
	mass_arr=total(total(reform(mas,n_swp,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	tof_arr=total(total(reform(tof,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	twt_arr=total(total(reform(twt,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/avg_nrg

	mass_arr=transpose(reform(reform(mass_arr,n_swp*nenergy*nmass)#replicate(1.,nbins),n_swp,nenergy,nmass,nbins),[0,1,3,2])
	tof_arr=transpose(reform(reform(tof_arr,n_mlut*nenergy*nmass)#replicate(1.,nbins),n_mlut,nenergy,nmass,nbins),[0,1,3,2])
	twt_arr=transpose(reform(reform(twt_arr,n_mlut*nenergy*nmass)#replicate(1.,nbins),n_mlut,nenergy,nmass,nbins),[0,1,3,2])

; the following uses def(n_swp,64,16) to generate theta and phi arrays that depend on iswp(md1)

	theta = reform(reform(total(total(reform(def,n_swp,avg_nrg,nenergy,avg_def,ndef),4),2),n_swp*nenergy*ndef)#replicate(1.,nanode*nmass),n_swp,nenergy,nbins,nmass)/avg_nrg/avg_def
	dtheta = reform(reform(total(reform(abs(def(*,*,15)-def(*,*,0))/(15.),n_swp,avg_nrg,nenergy),2),n_swp*nenergy)#replicate(1.,nbins*nmass),n_swp,nenergy,nbins,nmass)/avg_nrg*avg_def 
	dtheta = dtheta > 6.
	phi = 22.5*reform(reform(replicate(1.,n_swp*nenergy*ndef)#(findgen(nanode)-7.),1l*n_swp*nenergy*nbins)#replicate(1.,nmass),n_swp,nenergy,nbins,nmass)
	dphi = fltarr(n_swp,nenergy,nbins,nmass) & dphi(*)=22.5
	domega = dphi*dtheta/!radeg^2

	d3_dat= {project_name:		'MAVEN',				$
		spacecraft:		'0', 					$
;		data_name:		'D3 Energy-Angle-Mass', 		$
;		apid:			'D3',					$
		data_name:		'd3 32e16a8m', 				$
		apid:			'd3',					$
		units_name: 		'counts', 				$
		units_procedure: 	'mvn_sta_convert_units', 		$
		valid: 			replicate(1,ndis), 			$
		quality_flag: 		quality_flag, 				$

		time:			tt1,					$
		end_time:		tt2,					$
		delta_t:		tt2-tt1,				$
		integ_t: 		(tt2-tt1)/(nenergy*ndef)*dt_cor,	$	

		eprom_ver:		eprom_ver,				$
		header:			header,					$
		mode:			md2,					$
		rate:			rt2,					$
		swp_ind:		swp_ind,				$
		mlut_ind:		mlut,					$
		eff_ind:		eff_ind,				$
		att_ind:		att0,					$

		nenergy: 		nenergy,				$
		energy: 		energy2, 				$
		denergy: 		denergy2, 				$

		nbins: 			nbins, 					$
		bins: 			replicate(1,nbins), 			$
		ndef:			ndef,					$
		nanode:			nanode,					$

		theta: 			theta,  				$
		dtheta: 		dtheta,  				$
		phi: 			phi,  					$
		dphi: 			dphi, 					$
		domega: 		domega,  				$

		gf: 			gf2, 					$
		eff: 			eff2,	 				$

		geom_factor: 		geom_factor,				$
		dead1: 			dead1,					$
		dead2: 			dead2,					$
		dead3: 			dead3,					$

		nmass:			nmass,					$
		mass: 			1.0438871e-02, 				$
		mass_arr:		mass_arr,				$
		tof_arr:		tof_arr,				$
		twt_arr:		twt_arr,				$

		charge: 		1., 					$
		sc_pot: 		replicate(0.,ndis),			$
		magf:	 		magf, 					$
		quat_sc:	 	quat_sc, 				$
		quat_mso:	 	quat_mso, 				$
		bins_sc:		bins_sc,				$
		pos_sc_mso:		pos_sc_mso,				$

		bkg:	 		bkg,		 			$
		dead:	 		dead,		 			$

		data:			reform(tmp,ndis,nenergy,nbins,nmass)}

		common mvn_d3,mvn_d3_ind,mvn_d3_dat & mvn_d3_dat=d3_dat & mvn_d3_ind=0l

   endif
endif

		
;***************************************************************************************************************
; APID D4


if keyword_set(apids) then test = fix((total(apids eq 'd4') + total(apids eq 'D4')) < 1) else test=0
if not keyword_set(apids) or test then begin
print,'Processing apid d4'

	nn=0
	get_data,'mvn_STA_D4_DATA',data=t
	if size(/type,t) eq 8 then begin
		npts=128									; 1Ex4Dx16Ax2M
		ind1 = where(t.x gt 0, nn)
		tt=t.x[0:nn-1]
	if nn ge 2 then begin

		get_data,'mvn_STA_D4_DIAG',data=diag

		get_data,'mvn_STA_D4_MODE',data=md
			md1 = md.y[0:nn-1] and 127
			md2 = md.y[0:nn-1] and 15
			rt2 = (md.y[0:nn-1] and 112)/16

		get_data,'mvn_STA_D4_AVG',data=cavg
		avg = 2^(cavg.y and replicate(7,nn))
		sum = (cavg.y and replicate(8,nn))/8
			avg2 = sum*avg > 1

		comp = (cavg.y and replicate(192,nn))/128
		ind = where(avg[0:nn-2] ne avg[1:nn-1],count)
		if count ne 0 then begin
			for i=0,count-1 do begin
				a0 = avg[ind[i]]
				a1 = avg[ind[i]+1]
				dt = a1*4.
				nf = abs(round( ( (tt[ind[i]+1]-tt[ind[i]])/4. -(a0+a1)/2. ) /(a1-a0) ))
				if nf gt 7 then nf=0
				for j=ind[i]-nf+1,ind[i] do begin
					tt[j]=tt[ind[i]+1]-dt*(ind[i]+1-j)
					avg2[j]=avg2[ind[i]+1]
					md2[j]=md2[ind[i]+1]
					rt2[j]=rt2[ind[i]+1]
					md1[j]=md1[ind[i]+1]
				endfor
			endfor
		endif

;	correct D4 mode transitions using C6 data if it is available
		get_data,'mvn_sta_C6_mode',data=md6
		if size(/type,md6) eq 8 then begin
			get_data,'mvn_sta_C6_rate',data=rt6
			md2 = fix(round(interp(md6.y,md6.x,tt)))
			rt2 = fix(round(interp(rt6.y,rt6.x,tt)))
			md1 = rt2*16+md2	 
		endif

			tt1 = tt - 2.*avg2 								; corrected timing for averaging, kluge for header mismatch
			tt2 = tt + 2.*avg2 
			if nn gt 2 then begin
				tt2[0:nn-2] = tt2[0:nn-2] < tt1[1:nn-1]
				tt3 = (tt1 + tt2)/2.
;				print,'C0 correction for averaging error: tt3-tt = ',tt3-tt
				tt = tt3
			endif

;	correct D4 mode transitions using C6 data if it is available -- old code??????
;		get_data,'mvn_sta_C6_mode',data=md6
;		if size(/type,md6) eq 8 then begin
;			get_data,'mvn_sta_C6_rate',data=rt6
;			ind0 = where (md2[0:nn-2] ne md2[1:nn-1],count) 
;			if count gt 0 then begin
;				for i=0,count-1 do begin
;					j0=0>(ind0[i]-8)
;					j1=(nn-1)<(ind0[i]+8)
;					for j=j0,j1 do begin
;						tmpmin = min(abs(md6.x - tt[j]),ind6)
;						if tmpmin lt 1. and md6.y[ind6] ne md2[j] then begin
;							md2[j]=md6.y[ind6]
;							rt2[j]=rt6.y[ind6]
;						endif 
;					endfor
;				endfor
;			endif
;		endif
;		md1 = rt2*16+md2	 

		get_data,'mvn_STA_D4_ATTEN',data=catt						; attenuator state
		att1 = (catt.y[0:nn-1] and replicate(192,nn))/64
		att0 = att1
		store_data,'mvn_STA_D4_att_s',data={x:tt,y:att1}
		att2 = (catt.y[0:nn-1] and replicate(48,nn))/16
		store_data,'mvn_STA_D4_att_e',data={x:tt,y:att2}
		att3 = (catt.y[0:nn-1] and replicate(15,nn))
		store_data,'mvn_STA_D4_att_w',data={x:tt,y:att3}
		ind0 = where(att1[0:nn-2] ne att1[1:nn-1],cnt0)					; find att transitions
		if cnt0 ne 0 then begin
			nmax = 1024/npts
			for i=0,cnt0-1 do begin
				inds = ind0[i]
				if att3[inds] ge nmax then print,'APID D4 packet header error: WWWW too large, wwww=',att3[inds]
;				idelay = fix(2/avg[inds])					; observed internal delays of 2 x 4sec, hence the "2"
				idelay = fix(2/avg2[inds])					; observed internal delays of 2 x 4sec, hence the "2"
				iww = att3[inds] - 1
				if iww lt 0 then iww = nmax-1
				att0[inds-nmax+1:inds] = att1[inds+1] 				; replace transition att w/ next value
				att0[inds-nmax+1:inds-nmax+1+iww+idelay] = att1[inds]		; use ww and interal delays to correct att at previous value
			endfor
		endif

;	correct D4 attenuator transitions using C6 data if it is available
		get_data,'mvn_sta_C6_att',data=att6
		if size(/type,att6) eq 8 then att0 = fix(round(interp(att6.y,att6.x,tt)))<3


		header = 256l^3*md.y[0:nn-1] + 256l^2*cavg.y[0:nn-1] + 256l*catt.y[0:nn-1] + diag.y[0:nn-1]

		store_data,'mvn_sta_D4_mode',data={x:tt,y:md2}					; corrected modes
			ylim,'mvn_sta_D4_mode',-1,7,0
		store_data,'mvn_sta_D4_rate',data={x:tt,y:rt2}					; corrected modes
			ylim,'mvn_sta_D4_rate',-1,8,0
		store_data,'mvn_sta_D4_att',data={x:tt,y:att0}
			ylim,'mvn_sta_D4_att',-1,4,0

;		swp_ind = md2swp[md1]									; old version
;		swp_ind = conf2swp[fix(interp((config4.y and 255)*1.,config4.x,tt)+.5),md2]					
		swp_ind = conf2swp[fix(interp((config4.y and 511)*1.,config4.x,tt)+.5),md2]					
			eprom_ver = fix(interp((config4.y and 255)*1.,config4.x,tt)+.5)
			if tt[0] lt time_double('2014-10-1/0') then eprom_ver[*]=0

		energy=nrg[swp_ind,*]
		energy=total(energy,2)/64.							; because there is only 1 energy
		mass=mas[swp_ind,0,*]
		mass=total(reform(mass,nn,2,32),3)/32.						; because there are only 2 masses
		deflection = total(reform(def[swp_ind,62,*],nn,4,4),2)/4.

		tmp=decomp19[transpose(reform(t.y[0:nn-1,*],nn,16,2,4),[0,3,1,2])]			; [time,def,an,ma]

		store_data,'mvn_sta_D4_P4E_D',data={x:tt,y:reform(total(total(tmp,4),3),nn,4),v:deflection}
		store_data,'mvn_sta_D4_P4E_A',data={x:tt,y:reform(total(total(tmp,4),2),nn,16),v:22.5*(findgen(16)-7.)}
		store_data,'mvn_sta_D4_P4E_M',data={x:tt,y:reform(total(total(tmp,2),2),nn,2),v:mass}
		store_data,'mvn_sta_D4_P4E_tot',data={x:tt,y:total(total(total(tmp,2),2),2)}
		store_data,'mvn_sta_D4_P4E_all',data={x:tt,y:reform(tmp,nn,npts),v:findgen(npts)}

		ylim,'mvn_sta_D4_P4E_tot',0,0,1
		ylim,'mvn_sta_D4_P4E_D',-45,45,0
		ylim,'mvn_sta_D4_P4E_A',-180,200,0
		ylim,'mvn_sta_D4_P4E_M',.5,100,1
		zlim,'mvn_sta_D4_P4E_D',1,1.e4,1
		zlim,'mvn_sta_D4_P4E_A',1,1.e4,1
		zlim,'mvn_sta_D4_P4E_M',1,1.e4,1
		options,'mvn_sta_D4_P4E_D',datagap=64.
		options,'mvn_sta_D4_P4E_A',datagap=64.
		options,'mvn_sta_D4_P4E_M',datagap=64.
		options,'mvn_sta_D4_P4E_tot',datagap=64.
		options,'mvn_sta_D4_P4E_D','spec',1
		options,'mvn_sta_D4_P4E_A','spec',1
		options,'mvn_sta_D4_P4E_M','spec',1
		options,'mvn_sta_D4_P4E_D',ytitle='sta!CP4E-D4!C!CDef!Ctheta'
		options,'mvn_sta_D4_P4E_A',ytitle='sta!CP4E-D4!C!CAnode!Cphi'
		options,'mvn_sta_D4_P4E_M',ytitle='sta!CP4E-D4!C!CMass!Camu'
	endif
	endif


; Make D4 common block

   if size(/type,t) eq 8 and nn ge 2 then begin

	nenergy = 1
	avg_nrg = 64/nenergy
	ndef = 4
	avg_def=16/ndef
	nanode = 16
	avg_an = 16/nanode
	nbins = ndef*nanode
	nmass = 2

	magf = replicate(0.,nn)#[0.,0.,0.]
	quat_sc  = replicate(0.,nn)#[0.,0.,0.,0.]
	quat_mso = replicate(0.,nn)#[0.,0.,0.,0.]
	bins_sc = fix(replicate(1,nn)#replicate(1,nbins))
	quality_flag = intarr(nn)
	pos_sc_mso = replicate(0.,nn)#[0.,0.,0.]
	bkg   = fltarr(nn,nenergy,nbins,nmass)
	dead   = fltarr(nn,nenergy,nbins,nmass) & dead[*]=1.

;	energy2  = reform(reform(total(reform(nrg,n_swp,avg_nrg,nenergy),2)/avg_nrg,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)
;	denergy2 = reform(reform(total(reform(dnrg,n_swp,avg_nrg,nenergy),2)       ,n_swp*nenergy) # replicate(1.,nmass),n_swp,nenergy,nmass)

	an_ma = replicate(1.,nbins*nmass) 
	energy2  = reform(reform(total(reform(nrg,n_swp,avg_nrg,nenergy),2)/avg_nrg,n_swp*nenergy) # an_ma,n_swp,nenergy,nbins,nmass)
	denergy2 = reform(reform(total(reform(dnrg,n_swp,avg_nrg,nenergy),2)       ,n_swp*nenergy) # an_ma,n_swp,nenergy,nbins,nmass)

;	gf[n_swp,64,16,16,4]	sum geometric factor over energy, deflection and anode, why is there a normalization???????				; gf[iswp,en,def,an,att]
;	gf2 = reform(total(total(reform(gf,n_swp,avg_nrg,nenergy,avg_def,ndef,16,4),4),2),n_swp,nenergy,nbins,4)/avg_nrg/avg_def			;
	gf2 = reform(total(total(reform(gf,n_swp,avg_nrg,nenergy,avg_def,ndef,16,4),4),2),n_swp,nenergy,nbins,4)/(avg_nrg*avg_def)			;

; junk dna
;	gf2 = fltarr(n_swp,nenergy,ndef,nanode,4)
;	gf1 = reform(total(total(reform(gf,n_swp,avg_nrg,nenergy,avg_def,ndef,16,4),4),2),n_swp,nenergy,ndef*16,4)		;
;	gf1 = total(reform(gf,n_swp,avg_nrg,nenergy,16,16,4),2)		;
;	for i=0,n_swp-1 do gf2[i,*,*] = total(total(gf1[i,*,swp2gfdf[i,0]:swp2gfdf[i,1],swp2gfan[i,0]:swp2gfan[i,1],*],3),3)/(swp2gfdf[i,1]-swp2gfdf[i,0]+1.)/(swp2gfan[i,1]-swp2gfan[i,0]+1)
;	for i=0,n_swp-1 do gf2[i,*,*] = total(total(gf1[i,*,swp2gfdf[i,0]:swp2gfdf[i,1],swp2gfan[i,0]:swp2gfan[i,1],*],3),3)
;	for i=0,n_swp-1 do gf2[i,*,*,*,*] = total(total(gf1[i,*,swp2gfdf[i,0]:swp2gfdf[i,1],swp2gfan[i,0]:swp2gfan[i,1],*],3),3)

; the following line assumes a constant efficiency as a default until other calibration code can be developed
;    a proper efficiency calibration is handled mvn_sta_dead_load.pro

	eff2 = fltarr(128,nenergy,nbins,nmass) & eff2[*]=def_eff  & eff_ind=intarr(nn)

;	mlut = md2mlut(md1)
	mlut = swp2mlut(swp_ind)
	mass_arr=total(total(reform(mas,n_swp,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	tof_arr=total(total(reform(tof,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/(64./nmass)/avg_nrg
	twt_arr=total(total(reform(twt,n_mlut,avg_nrg,nenergy,64/nmass,nmass),4),2)/avg_nrg

	mass_arr=transpose(reform(reform(mass_arr,n_swp*nenergy*nmass)#replicate(1.,nbins),n_swp,nenergy,nmass,nbins),[0,1,3,2])
	tof_arr=transpose(reform(reform(tof_arr,n_mlut*nenergy*nmass)#replicate(1.,nbins),n_mlut,nenergy,nmass,nbins),[0,1,3,2])
	twt_arr=transpose(reform(reform(twt_arr,n_mlut*nenergy*nmass)#replicate(1.,nbins),n_mlut,nenergy,nmass,nbins),[0,1,3,2])

; the following uses def(n_swp,64,16) to generate theta and phi arrays that depend on iswp(md1)

	theta = reform(reform(total(total(reform(def,n_swp,avg_nrg,nenergy,avg_def,ndef),4),2),n_swp*nenergy*ndef)#replicate(1.,nanode*nmass),n_swp,nenergy,nbins,nmass)/avg_nrg/avg_def
	dtheta = reform(reform(total(reform(abs(def(*,*,15)-def(*,*,0))/(15.),n_swp,avg_nrg,nenergy),2),n_swp*nenergy)#replicate(1.,nbins*nmass),n_swp,nenergy,nbins,nmass)/avg_nrg*avg_def
	phi = 22.5*reform(reform(replicate(1.,n_swp*nenergy*ndef)#(findgen(nanode)-7.),1l*n_swp*nenergy*nbins)#replicate(1.,nmass),n_swp,nenergy,nbins,nmass)
	dphi = fltarr(n_swp,nenergy,nbins,nmass) & dphi(*)=22.5
	domega = dphi*dtheta/!radeg^2

	d4_dat= {project_name:		'MAVEN',				$
		spacecraft:		'0', 					$
;		data_name:		'D4 Energy-Angle-Mass', 		$
;		apid:			'D4',					$
		data_name:		'd4 4d16a2m', 				$
		apid:			'd4',					$
		units_name: 		'counts', 				$
		units_procedure: 	'mvn_sta_convert_units', 		$
		valid: 			replicate(1,nn), 			$
		quality_flag: 		quality_flag, 				$

		time:			tt1,					$
		end_time:		tt2,					$
		delta_t:		tt2-tt1,				$
		integ_t: 		(tt2-tt1)/(nenergy*ndef)*dt_cor,	$	

		eprom_ver:		eprom_ver,				$
		header:			header,					$
		mode:			md2,					$
		rate:			rt2,					$
		swp_ind:		swp_ind,				$
		mlut_ind:		mlut,					$
		eff_ind:		eff_ind,				$
		att_ind:		att0,					$

		nenergy: 		nenergy,				$
		energy: 		energy2, 				$
		denergy: 		denergy2, 				$

		nbins: 			nbins, 					$
		bins: 			replicate(1,nbins), 			$
		ndef:			ndef,					$
		nanode:			nanode,					$

		theta: 			theta,  				$
		dtheta: 		dtheta,  				$
		phi: 			phi,  					$
		dphi: 			dphi, 					$
		domega: 		domega,  				$

		gf: 			gf2, 					$
		eff: 			eff2,	 				$

		geom_factor: 		geom_factor,				$
		dead1: 			dead1,					$
		dead2: 			dead2,					$
		dead3: 			dead3,					$

		nmass:			nmass,					$
		mass: 			1.0438871e-02, 				$
		mass_arr:		mass_arr,				$
		tof_arr:		tof_arr,				$
		twt_arr:		twt_arr,				$

		charge: 		1., 					$
		sc_pot: 		replicate(0.,nn),			$
		magf:	 		magf, 					$
		quat_sc:	 	quat_sc, 				$
		quat_mso:	 	quat_mso, 				$
		bins_sc:		bins_sc,				$
		pos_sc_mso:		pos_sc_mso,				$

		bkg:	 		bkg,		 			$
		dead:	 		dead,		 			$

		data:			reform(tmp,nn,nenergy,nbins,nmass)}

		common mvn_d4,mvn_d4_ind,mvn_d4_dat & mvn_d4_dat=d4_dat & mvn_d4_ind=0l

   endif
endif


;***************************************************************************************************************
; APID D6

; this section is new code 

if not keyword_set(ignore) then begin

if keyword_set(apids) then test = fix((total(apids eq 'd6') + total(apids eq 'D6')) < 1) else test=0
if not keyword_set(apids) or test then begin
print,'Processing apid d6'

	iy=0l
	get_data,'mvn_STA_D6_DATA',data=t
	if size(/type,t) eq 8 then begin
	
		npkts = dimen1(t.y)

		get_data,'mvn_STA_D6_MODE',data=md

; 		if any packet of a 48 event packet set is missing, throw away the entire set - too much trouble to reconstruct
; 		these are diagnostic packets and are not needed for science  	
		get_data,'mvn_STA_D6_DIAG',data=di
			mm = di.y and 63
			mpts = n_elements(mm)
			ind1 = where(mm eq 0,count)
			if (count gt 0) then ind2 = where(mm[(ind1+47)<(mpts-1)] eq 47,ndis) else ndis=0
	if ndis gt 0 and npkts ge 48 then begin
			ind1 = ind1[ind2]
			n_events = n_elements(ind1)
			if n_events gt npkts/48 then begin
				print,'Error 1 - D6 packets were missing'
				print,'n_events,npkts/48=',n_events,npkts/48
				print,'Truncating n_events from ',n_events,' to ',npkts/48
				n_events = npkts/48
			endif

		nmax = n_events*8192l
			tdc_1 = intarr(nmax)	
			tdc_2 = intarr(nmax) 	
			tdc_3 = intarr(nmax)	
			tdc_4 = intarr(nmax)	
			mode = intarr(nmax) 
			rate = intarr(nmax) 
			swp_i = intarr(nmax) 
			event_code = intarr(nmax) 
			cyclestep = intarr(nmax) 
			energy = fltarr(nmax)
			time_unix = dblarr(nmax)
			valid = intarr(nmax) 
			qual_flag = intarr(nmax) 

		dt1 = 4./1024.
		dt2 = dt1/64.
		npts = 1024l*48

		for i=0,n_events-1 do begin

			aa = reform(transpose(t.y[ind1[i]:ind1[i]+47,*]),48l*1024l)	

			t0 = t.x[ind1[i]]
			vd = 1								; valid data
			if t0 ne t.x[ind1[i]+47] then begin
				print,'Error 2 - D6 packets header time error'	
				vd = 0
			endif

			tp  = (di.y[ind1[i]] and 128)/128				; test pulser
			dm  = (di.y[ind1[i]] and 64)/64					; diagnostic mode
			md2 =  md.y[ind1[i]] and 15					; mode (ram, conic, pickup)
			rt2 = (md.y[ind1[i]] and 112)/16				; rate 
			pc  =  md.y[ind1[i]] and 128					; packet compression

;			swp_ind = conf2swp[fix(interp((config4.y and 255)*1.,config4.x,t0)+.5),md2]					
			swp_ind = conf2swp[fix(interp((config4.y and 511)*1.,config4.x,t0)+.5),md2]					

			ix  = 0l					; index stepping through an event
			cy1 = 0l
			cy_last = 0l

			while (aa[ix] and 252)/4 eq 52 and ix lt npts-10 do begin
				lf = aa[ix+1]
				cy = aa[ix+2]*256 + aa[ix+3]
				if cy le cy_last then cy1=cy1+1
				cy_last = cy
				for j=0,lf/3-1 do begin
				    if ix+8+j*6 lt npts then begin
					tdc_1[iy] 	=  aa[ix+4+j*6]*4		+ (aa[ix+5+j*6] and 192)/64	
					tdc_2[iy]  	= (aa[ix+6+j*6] and 3)*256 	+  aa[ix+7+j*6]  	
					tdc_3[iy]  	= (aa[ix+6+j*6] and 252)/4	+ (aa[ix+9+j*6] and 15)*64	
					tdc_4[iy]  	= (aa[ix+8+j*6] and 63)*16	+ (aa[ix+9+j*6] and 240)/16	
					event_code[iy]  = (aa[ix+5+j*6] and 63)
					cyclestep[iy]	= cy
					energy[iy]	= nrg[swp_ind,fix(cy/16)]
					time_unix[iy] 	= t0 + (cy1*1024l+cy)*dt1 + j*dt2
					valid[iy]	= vd+2*tp+4*dm+32*pc
					qual_flag[iy]	= 1
					mode[iy]	= md2
					rate[iy]	= rt2
					swp_i[iy]	= swp_ind
;			print,valid[iy],ix,ix+8+j*6,lf,j,cy,cy1,iy

					iy=iy+1
				    endif
				endfor
				ix = (ix + (lf+2)*2) < (npts-1)
			endwhile 
			
			if ix lt npts-20 then print,'Error 3 - D6 packets are scrambled'
		endfor

;	get rid of extra points

			tdc_1 = tdc_1[0:iy-1]	
			tdc_2 = tdc_2[0:iy-1] 	
			tdc_3 = tdc_3[0:iy-1]	
			tdc_4 = tdc_4[0:iy-1]	
			mode = mode[0:iy-1] 
			rate = rate[0:iy-1]
			swp_i = swp_i[0:iy-1] 
			event_code = event_code[0:iy-1] 
			cyclestep = cyclestep[0:iy-1]
			energy = energy[0:iy-1]
			time_unix = time_unix[0:iy-1]
			valid = valid[0:iy-1] 
			qual_flag = qual_flag[0:iy-1] 


; 	make some tplot quantities

			ev1 = (event_code and 1)
			ev2 = (event_code and 2)
			ev3 = (event_code and 4)/4*3
			ev4 = (event_code and 8)/8*4
			ev5 = (event_code and 16)/16*5
			ev6 = (event_code and 32)/32*6
			ev_cd = [[ev1],[ev2],[ev3],[ev4],[ev5],[ev6]]
		store_data,'mvn_sta_D6_tdc1',data={x:time_unix,y:tdc_1+1}
		store_data,'mvn_sta_D6_tdc2',data={x:time_unix,y:tdc_2+1}
		store_data,'mvn_sta_D6_tdc3',data={x:time_unix,y:tdc_3*(-2*ev1+1)}
		store_data,'mvn_sta_D6_tdc4',data={x:time_unix,y:tdc_4*(-ev2+1)}
		store_data,'mvn_sta_D6_ev',data={x:time_unix,y:ev_cd,v:[1,2,3,4,5,6]}
		store_data,'mvn_sta_D6_cy',data={x:time_unix,y:cyclestep}
		store_data,'mvn_sta_D6_en',data={x:time_unix,y:energy}

		ylim,'mvn_sta_D6_tdc1',.5,1024,1
		ylim,'mvn_sta_D6_tdc2',.5,1024,1
		ylim,'mvn_sta_D6_tdc3',-530,530,0
		ylim,'mvn_sta_D6_tdc4',-530,530,0
		ylim,'mvn_sta_D6_ev',-1,7,0
		ylim,'mvn_sta_D6_cy',-1,1024,0
		ylim,'mvn_sta_D6_en',.1,30000.,1
		options,'mvn_sta_D6_tdc1',psym=3
		options,'mvn_sta_D6_tdc2',psym=3
		options,'mvn_sta_D6_tdc3',psym=3
		options,'mvn_sta_D6_tdc4',psym=3
		options,'mvn_sta_D6_ev',psym=3
		options,'mvn_sta_D6_cy',psym=3
		options,'mvn_sta_D6_en',psym=3

	endif
	endif


; Make D6 common block

   if size(/type,t) eq 8 and ndis gt 0 and iy gt 1 then begin

	d6_dat= {project_name:		'MAVEN',				$
		spacecraft:		'0', 					$
		data_name:		'd6 events', 				$
		apid:			'd6',					$

		valid: 			valid, 					$
		quality_flag: 		qual_flag, 				$
		time:			time_unix,				$
; these lines were used for testing
;		mode:			mode,					$
;		rate:			rate,					$
;		swp_ind:		swp_i,					$
		tdc_1: 			tdc_1,					$
		tdc_2: 			tdc_2,					$
		tdc_3: 			tdc_3,					$
		tdc_4: 			tdc_4,					$
		event_code: 		event_code,				$
		cyclestep: 		cyclestep,				$
		energy: 		energy, 				$

		tdc1_conv: 		1./b_ns,				$
		tdc2_conv: 		1./b_ns,				$
		tdc3_conv: 		1./p_ns_3,				$
		tdc4_conv: 		1./p_ns_4,				$
		tdc1_offset: 		tdc1_offset,				$
		tdc2_offset: 		tdc2_offset,				$
		tdc3_offset: 		tdc3_offset,				$
		tdc4_offset: 		tdc4_offset,				$
		an_bin_tdc3: 		an_bin_tdc3,				$
		an_bin_tdc4: 		an_bin_tdc4,				$
		ms_bias_offset: 	mass_bias_offset,			$
		evconvlut:		evconvlut,				$
		timerst:		timerst}

		common mvn_d6,mvn_d6_ind,mvn_d6_dat & mvn_d6_dat=d6_dat & mvn_d6_ind=0l

   endif
endif

endif

;***************************************************************************************************************
; APID D7


if keyword_set(apids) then test = fix((total(apids eq 'd7') + total(apids eq 'D7')) < 1) else test=0
if not keyword_set(apids) or test then begin
print,'Processing apid d7'

	nn=0
	get_data,'mvn_STA_D7_DATA',data=t
	if size(/type,t) eq 8 then begin

		name_hkp=['Temp_Dig','Imon_ADC5V','+5V_D','+3.3V_D','+5V_A','-5V_A','+12V_A','+28V',$
		'Vmon_Swp','Vmon_Swp_Err','Vmon_Def1','Vmon_Def1_Err','Vmon_Def2','Vmon_Def2_Err','Vmon_Vgrid','Temp_FPGA',$
		'Imon_15kV','Vmon_15kV','Imon_MCP','Vmon_MCP','Imon_Raw','Vmon_Def_Raw','Temp_LVPS','Vmon_Swp_Raw']


		A0=[1.6484E+02,0.,0.,0.,0.,0.,0.,0.,$
			0.,0.,0.,0.,0.,0.,0.,1.6484E+02,$
			0.,0.,0.,0.,0.,0.,2.3037E+02,0.]

		A1=[3.9360E-02,-0.030518,-0.000191,-0.000153,-0.000191,-0.000191,-0.000458,-0.001097,$
			0.152588,-0.000153,-0.152740,-0.000153,-0.152740,-0.000153,-0.000951,3.9360E-02,$
			-0.001176,0.571490,-0.003101,-0.143006,-0.000763,-0.189468,5.8791E-02,-0.189468]

		aa=[0,15]
		A2=replicate(0.,24) & A2[aa]=5.6761E-06 & A2[22]=8.8802E-06
		A3=replicate(0.,24) & A3[aa]=4.4329E-10 & A3[22]=6.9447E-10
		A4=replicate(0.,24) & A4[aa]=1.6701E-14 & A4[22]=2.5920E-14
		A5=replicate(0.,24) & A5[aa]=2.4223E-19 & A5[22]=3.6994E-19
		A6=replicate(0.,24) 
		A7=replicate(0.,24) 

		hkp_par = dblarr(8,24)
		hkp_par[*,*]=1.d
		hkp_par[0,0:23]=A0
		hkp_par[1,0:23]=A1
		hkp_par[2,0:23]=A2
		hkp_par[3,0:23]=A3
		hkp_par[4,0:23]=A4
		hkp_par[5,0:23]=A5
		hkp_par[6,0:23]=A6
		hkp_par[7,0:23]=A7

		npts=512									; 512 points
		dt = 4.d/512.*findgen(512)
;		ind1 = where(t.x gt 0, nn)
		nn = dimen(t.x)
		tt_fhkp= reform(replicate(1.d,512)#t.x[0:nn-1] + dt#replicate(1.d,nn),nn*512)

		get_data,'mvn_STA_D7_MUX',data=mux
		mx= reform(replicate(1,512)#mux.y[0:nn-1],nn*512) - 1

		dd = reform(transpose(t.y[0:nn-1,*]),nn*512)
		cal=dblarr(512l*nn)
		fcal=fltarr(512l*nn)
		for i=0,7 do cal = cal + hkp_par[i,mx]*(dd*1.d)^i
		fcal[*] = cal[*]
		store_data,'mvn_sta_D7_data',data={x:tt_fhkp,y:1.*dd}
		store_data,'mvn_sta_D7_data_cal',data={x:tt_fhkp,y:fcal}
		store_data,'mvn_sta_D7_data_mux',data={x:tt_fhkp,y:mx}
			options,'mvn_sta_D7_data_cal',datagap=1.
			options,'mvn_sta_D7_data_mux',datagap=1.
			options,'mvn_sta_D7_data',datagap=1.

		valid = replicate(1,512l*nn)
		qual  = intarr(512l*nn)

	endif


; Make D7 common block

    if size(/type,t) eq 8 and nn gt 0 then begin

	d7_dat= {project_name:		'MAVEN',				$
		spacecraft:		'0', 					$
		data_name:		'd7 fsthkp', 				$
		apid:			'd7',					$

		valid: 			valid, 					$
		quality_flag: 		qual, 					$

		time:			tt_fhkp,				$

		hkp_raw:		dd,					$
		hkp_calib:		fcal,					$
		hkp_ind:		mx,					$

		nhkp: 			24,					$
		hkp_conv: 		hkp_par,				$
		hkp_labels: 		name_hkp}

		common mvn_d7,mvn_d7_ind,mvn_d7_dat & mvn_d7_dat=d7_dat & mvn_d7_ind=0l

    endif

endif


;***************************************************************************************************************
; APID D8


if keyword_set(apids) then test = fix((total(apids eq 'd8') + total(apids eq 'D8')) < 1) else test=0
if not keyword_set(apids) or test then begin
print,'Processing apid d8'

	nn=0
	get_data,'mvn_STA_D8_DATA',data=t
	if size(/type,t) eq 8 then begin
		npts=12									; 12R
		ind1 = where(t.x gt 0, nn)
		tt=t.x[0:nn-1]

		get_data,'mvn_STA_D8_DIAG',data=diag
		get_data,'mvn_STA_D8_ATTEN',data=catt						; attenuator state

		get_data,'mvn_STA_D8_MODE',data=md
			md1 = md.y[0:nn-1] and 127
			md2 = md.y[0:nn-1] and 15
			rt2 = (md.y[0:nn-1] and 112)/16

		get_data,'mvn_STA_D8_AVG',data=cavg
		avg = 2^(cavg.y and replicate(7,nn))
		sum = (cavg.y and replicate(8,nn))/8
			avg2 = sum*avg > 1

		comp = (cavg.y and replicate(192,nn))/128

;	correct D8 mode transitions using C6 data if it is available
		get_data,'mvn_sta_C6_mode',data=md6
		if size(/type,md6) eq 8 then begin
			get_data,'mvn_sta_C6_rate',data=rt6
			md2 = fix(round(interp(md6.y,md6.x,tt)))
			rt2 = fix(round(interp(rt6.y,rt6.x,tt)))
		endif
		md1 = rt2*16+md2	 

		tt1 = tt - 2.*avg2 	
		tt2 = tt + 2.*avg2 

		ind = where(avg[0:nn-2] ne avg[1:nn-1],count)
		if count ne 0 then begin
			for i=0,count-1 do begin
				a0 = 2^avg[ind[i]]
				a1 = 2^avg[ind[i]+1]
				dt = a1*4.
				nf = abs(round( ( (tt[ind[i]+1]-tt[ind[i]])/4. -(a0+a1)/2. ) /(a1-a0) ))
				if nf gt 15 then nf=0
				for j=ind[i]-nf+1,ind[i] do tt[j]=tt[ind[i]+1]-dt*(ind[i]+1-j)
			endfor
		endif

		header = 256l^3*md.y[0:nn-1] + 256l^2*cavg.y[0:nn-1] + 256l*catt.y[0:nn-1] + diag.y[0:nn-1]

		store_data,'mvn_sta_D8_mode',data={x:tt,y:md2}
			ylim,'mvn_sta_D8_mode',-1,7,0

;		swp_ind = conf2swp[fix(interp((config4.y and 255)*1.,config4.x,tt)+.5),md2]					
		swp_ind = conf2swp[fix(interp((config4.y and 511)*1.,config4.x,tt)+.5),md2]					
			eprom_ver = fix(interp((config4.y and 255)*1.,config4.x,tt)+.5)
			if tt[0] lt time_double('2014-10-1/0') then eprom_ver[*]=0

		tmp=decomp19[t.y[0:nn-1,*]]						; [time,rate]

		store_data,'mvn_sta_D8_R1_Time_ABCD',data={x:tt,y:tmp[*,0:3],v:findgen(4)}
		store_data,'mvn_sta_D8_R1_Time_RST',	data={x:tt,y:tmp[*,4]}
		store_data,'mvn_sta_D8_R1_Time_NoStart',	data={x:tt,y:tmp[*,5]}
		store_data,'mvn_sta_D8_R1_Time_Unqual',	data={x:tt,y:tmp[*,6]}
		store_data,'mvn_sta_D8_R1_Time_Qual',	data={x:tt,y:tmp[*,7]}
		store_data,'mvn_sta_D8_R1_Time_AnRej',	data={x:tt,y:tmp[*,8]}
		store_data,'mvn_sta_D8_R1_Time_MaRej',	data={x:tt,y:tmp[*,9]}
		store_data,'mvn_sta_D8_R1_Time_A&B',	data={x:tt,y:tmp[*,10]}
		store_data,'mvn_sta_D8_R1_Time_C&D',	data={x:tt,y:tmp[*,11]}
		store_data,'mvn_sta_D8_R1_all',data={x:tt,y:tmp,v:findgen(12)}

		store_data,'mvn_sta_D8_R1_eff_start',data={x:tt,y:tmp[*,7]/tmp[*,11]}
		options,'mvn_sta_D8_R1_eff_start',colors=cols.green
		store_data,'mvn_sta_D8_R1_eff_stop',data={x:tt,y:tmp[*,7]/tmp[*,10]}
		options,'mvn_sta_D8_R1_eff_stop',colors=cols.red
		store_data,'mvn_sta_D8_R1_eff',data={x:tt,y:tmp[*,7]*tmp[*,7]/tmp[*,11]/tmp[*,10]}
		store_data,'mvn_sta_D8_R1_eff_all',data=['mvn_sta_D8_R1_eff_start','mvn_sta_D8_R1_eff_stop','mvn_sta_D8_R1_eff']
		ylim,'mvn_sta_D8_R1_eff_all',.1,1,1

		options,'mvn_sta_D8_R1_Time_ABCD','colors',[cols.green,cols.blue,cols.cyan,cols.red]

		ylim,'mvn_sta_D8_R1*',0,0,1
		options,'mvn_sta_D8_R1*',datagap=64.
		ylim,'mvn_sta_D8_R1*',10.,1.e4,1

		store_data,'mvn_sta_D8_R1_tot',data={x:tt,y:reform(tmp[*,4])}
			ylim,'mvn_sta_D8_R1_tot',min(tmp[*,4])>1.,max(tmp[*,4]),1
			options,'mvn_sta_D8_R1_tot',psym=-1

	endif


; Make d8 common block

   if size(/type,t) eq 8 and nn ge 1 then begin

	integ_time = (tt2-tt1)*dt_cor
	rates = tmp/(integ_time#replicate(1.,12))
	rate_labels = ['R1_Time_A','R1_Time_B','R1_Time_C','R1_Time_D','R1_Time_RST','R1_Time_NoStart',$
		'R1_Time_Unqual','R1_Time_Qual','R1_Time_AnRej','R1_Time_MaRej','R1_Time_A&B','R1_Time_C&D']

	d8_dat= {project_name:		'MAVEN',				$
		spacecraft:		'0', 					$
		data_name:		'd8 12r1e', 				$
		apid:			'd8',					$
;		units_name: 		'Hz', 					$
		valid: 			replicate(1,nn), 			$
		quality_flag: 		replicate(0,nn), 			$

		time:			tt1,					$
		end_time:		tt2,					$
		integ_t: 		integ_time,				$	

		eprom_ver:		eprom_ver,				$
		header:			header,					$
		mode:			md2,					$
		rate:			rt2,					$
		swp_ind:		swp_ind,				$

; note nswp is part of cdf support data but is not explicity in the common blocks - may need to add it to most common blocks
;		nswp:			n_swp,					$

		energy:			nrg,					$
		nrate:			12,					$
		rate_labels:		rate_labels,				$

		rates: 			rates}

	common mvn_d8,mvn_d8_ind,mvn_d8_dat & mvn_d8_dat=d8_dat & mvn_d8_ind=0l

   endif
endif


;***************************************************************************************************************
; APID D9

if not keyword_set(ignore) then begin

if keyword_set(apids) then test = fix((total(apids eq 'd9') + total(apids eq 'D9')) < 1) else test=0
if not keyword_set(apids) or test then begin
print,'Processing apid d9'

; Rates: 0:TA, 1:TB, 2:TC, 3:TD, 4:Trst, 5:nostart, 6:unqual, 7:qual, 8:ano_rej, 9:mass_rej, 10:A&B, 11:C&D, 

; eff_start = qual/C&D ~ 0.65 (EM)
; eff_stop  = qual/A&B ~ 0.47 (EM)
; qual/Trst = (1. + (1.-eff_start)*(1.-eff_stop)) * eff_start * eff_stop

; 0.36 ~ qual/Trst = (1. + (1.-eff_start)*(1.-eff_stop)) * eff_start * eff_stop ~ 0.36
; print,(1. + (1.-.65)*(1.-.47)) * .65 * .47

	nn=0
	get_data,'mvn_STA_D9_DATA',data=t
	if size(/type,t) eq 8 then begin
		npts=768									; 64Ex12R
		ind1 = where(t.x gt 0, nn)
		tt=t.x[0:nn-1]

		get_data,'mvn_STA_D9_DIAG',data=diag
		get_data,'mvn_STA_D9_ATTEN',data=catt						; attenuator state

		get_data,'mvn_STA_D9_MODE',data=md
			md1 = md.y[0:nn-1] and 127
			md2 = md.y[0:nn-1] and 15
			rt2 = (md.y[0:nn-1] and 112)/16



		get_data,'mvn_STA_D9_AVG',data=cavg
		avg = 2^(cavg.y and replicate(7,nn))
		sum = (cavg.y and replicate(8,nn))/8
			avg2 = sum*avg > 1

		comp = (cavg.y and replicate(192,nn))/128

;	correct D9 mode transitions using C6 data if it is available
		get_data,'mvn_sta_C6_mode',data=md6
		if size(/type,md6) eq 8 then begin
			get_data,'mvn_sta_C6_rate',data=rt6
			md2 = fix(round(interp(md6.y,md6.x,tt)))
			rt2 = fix(round(interp(rt6.y,rt6.x,tt)))
		endif
		md1 = rt2*16+md2	 

		tt1 = tt - 2.*avg2 	
		tt2 = tt + 2.*avg2 

		header = 256l^3*md.y[0:nn-1] + 256l^2*cavg.y[0:nn-1] + 256l*catt.y[0:nn-1] + diag.y[0:nn-1]

		store_data,'mvn_sta_D9_mode',data={x:tt,y:md2}
			ylim,'mvn_sta_D9_mode',-1,7,0

;		swp_ind = conf2swp[fix(interp((config4.y and 255)*1.,config4.x,tt)+.5),md2]					
		swp_ind = conf2swp[fix(interp((config4.y and 511)*1.,config4.x,tt)+.5),md2]					
			eprom_ver = fix(interp((config4.y and 255)*1.,config4.x,tt)+.5)
			if tt[0] lt time_double('2014-10-1/0') then eprom_ver[*]=0

		tmp=decomp19[transpose(reform(t.y[0:nn-1,*],nn,12,64),[0,2,1])]			; [time,en,rate]
		tmp2=decomp19[reform(t.y[0:nn-1,*],nn,12,64)]					; [time,rate,en]

		store_data,'mvn_sta_D9_R2_Eeff',data={x:tt,y:reform(tmp[*,*,7]/(tmp[*,*,4]+.1),nn,64),v:findgen(64)}
		store_data,'mvn_sta_D9_R2_Aeff',data={x:tt,y:reform(total(tmp[*,*,7],2)/(total(tmp[*,*,4],2)+.1),nn)}
		store_data,'mvn_sta_D9_R2_RST',data={x:tt,y:reform(total(tmp[*,*,4],2))}
		store_data,'mvn_sta_D9_R2_all',data={x:tt,y:reform(tmp,nn,npts),v:findgen(npts)}

			mqual_ind = intarr(nn)
			trst      = fltarr(nn)
			nostart   = fltarr(nn)
			unqual    = fltarr(nn)
			qual      = fltarr(nn)
			eff_start = fltarr(nn)
			eff_stop  = fltarr(nn)
			eff       = fltarr(nn)
			fqual     = fltarr(nn)
			fqual2    = fltarr(nn)
			btrst     = fltarr(nn)
			cd_bg     = fltarr(nn)
			ab_bg     = fltarr(nn)
			bqual     = fltarr(nn)
;.r
		for i=0,nn-1 do begin
			mqual = max(tmp[i,*,7],mind) 
			mqual_ind[i] = mind
			trst[i]  = tmp[i,mind,4]
			nostart[i] = tmp[i,mind,5]
			unqual[i] = tmp[i,mind,6]
			qual[i] = tmp[i,mind,7]

			mtrst = min(tmp[i,*,4],bind) 
			bgnd = tmp[i,bind,4]
			cd_bgnd = tmp[i,bind,11]
			ab_bgnd = tmp[i,bind,10]

			eff_start[i] = tmp[i,mind,7]/((tmp[i,mind,11]-cd_bgnd*(1.+1./cd_bgnd^.5))>1.)
			eff_stop[i]  = tmp[i,mind,7]/((tmp[i,mind,10]-ab_bgnd*(1.+1./ab_bgnd^.5))>1.)
			eff[i] = eff_start[i] * eff_stop[i]

			fqual[i] = tmp[i,mind,7]/(tmp[i,mind,4]-bgnd*(1.+1./bgnd^.5))
			fqual2[i]= (1. + (1.-eff_start[i])*(1.-eff_stop[i])) * eff[i]
			btrst[i] = bgnd
			cd_bg[i] = cd_bgnd
			ab_bg[i] = ab_bgnd
			bqual[i] = tmp[i,bind,7]
		endfor
;end
		store_data,'mvn_sta_D9_R2_eff_ind',data={x:tt,y:mqual_ind}
		store_data,'mvn_sta_D9_R2_eff_start',data={x:tt,y:eff_start}	&	options,'mvn_sta_D9_R2_eff_start',colors=cols.green
		store_data,'mvn_sta_D9_R2_eff_stop',data={x:tt,y:eff_stop}	&	options,'mvn_sta_D9_R2_eff_stop',colors=cols.red
		store_data,'mvn_sta_D9_R2_eff',data={x:tt,y:eff}
		store_data,'mvn_sta_D9_R2_fqual',data={x:tt,y:fqual}
		store_data,'mvn_sta_D9_R2_fqual2',data={x:tt,y:fqual2} & options,'mvn_sta_D9_R2_fqual2',colors=cols.red
		store_data,'mvn_sta_D9_R2_fqual3',data=['mvn_sta_D9_R2_fqual','mvn_sta_D9_R2_fqual2'] & ylim,'mvn_sta_D9_R2_fqual3',0,0,0
		store_data,'mvn_sta_D9_R2_btrst',data={x:tt,y:btrst}
		store_data,'mvn_sta_D9_R2_cd_bg',data={x:tt,y:cd_bg}
		store_data,'mvn_sta_D9_R2_ab_bg',data={x:tt,y:ab_bg}
		store_data,'mvn_sta_D9_R2_trst',data={x:tt,y:trst}
		store_data,'mvn_sta_D9_R2_qual',data={x:tt,y:qual}
		store_data,'mvn_sta_D9_R2_unqual',data={x:tt,y:unqual}
		store_data,'mvn_sta_D9_R2_nostart',data={x:tt,y:nostart}
		store_data,'mvn_sta_D9_R2_startthenstop',data={x:tt,y:trst-nostart-unqual-qual}
		store_data,'mvn_sta_D9_R2_bqual',data={x:tt,y:bqual}

		store_data,'mvn_sta_D9_R2_eff_all',data=['mvn_sta_D9_R2_eff','mvn_sta_D9_R2_eff_start','mvn_sta_D9_R2_eff_stop']
		ylim,'mvn_sta_D9_R2_eff_all',0.1,1.0,1
		options,'mvn_sta_D9_R2_eff_all',ytitle='sta D9!C!CStart-Stop!CTotal!C!CEfficiency'

;tplot,['mvn_sta_C0_P1A_E','mvn_sta_D9_R2_eff_ind','mvn_sta_D9_R2_eff_start','mvn_sta_D9_R2_eff_stop','mvn_sta_D9_R2_eff','mvn_sta_D9_R2_fqual3',$
;		'mvn_sta_D9_R2_trst','mvn_sta_D9_R2_unqual','mvn_sta_D9_R2_qual','mvn_sta_D9_R2_nostart','mvn_sta_D9_R2_bqual',$
;		'mvn_sta_D9_R2_btrst','mvn_sta_D9_R2_cd_bg','mvn_sta_D9_R2_ab_bg','mvn_sta_D9_R2_startthenstop']


		ylim,'mvn_sta_D9_R2*',0,0,1
		options,'mvn_sta_D9_R2_Eeff',datagap=64.
		options,'mvn_sta_D9_R2_Aeff',datagap=64.
		options,'mvn_sta_D9_R2_RST',datagap=64.
		options,'mvn_sta_D9_R2_all',datagap=64.
		options,'mvn_sta_D9_R2_Eeff','spec',1
		options,'mvn_sta_D9_R2_Eeff',ytitle='sta!CEeff-D9!C!CEnergy!Cbin'
		zlim,'mvn_sta_D9_R2_Eeff',0.,1.,0

		store_data,'mvn_sta_D9_R2_tot',data={x:tt,y:trst}
			ylim,'mvn_sta_D9_R2_tot',min(trst)>1.,max(trst),1
			options,'mvn_sta_D9_R2_tot',psym=-1



	endif


; Make d9 common block

   if size(/type,t) eq 8 and nn ge 1 then begin

	integ_time = ((tt2-tt1)/64.)*dt_cor
	rates = tmp2/(integ_time#replicate(1.,12*64))	
	rate_labels = ['R2_Time_A','R2_Time_B','R2_Time_C','R2_Time_D','R2_Time_RST','R2_Time_NoStart',$
		'R2_Time_Unqual','R2_Time_Qual','R2_Time_AnRej','R2_Time_MaRej','R2_Time_A&B','R2_Time_C&D']

	d9_dat= {project_name:		'MAVEN',				$
		spacecraft:		'0', 					$
		data_name:		'd9 12r64e', 				$
		apid:			'd9',					$
;		units_name: 		'Hz', 					$
		valid: 			replicate(1,nn), 			$
		quality_flag: 		replicate(0,nn), 			$

		time:			tt1,					$
		end_time:		tt2,					$
		integ_t: 		integ_time,				$	

		eprom_ver:		eprom_ver,				$
		header:			header,					$
		mode:			md2,					$
		rate:			rt2,					$
		swp_ind:		swp_ind,				$

; note nswp is part of cdf support data but is not explicity in the common blocks - may need to add it to most common blocks
;		nswp:			n_swp,					$

		energy:			nrg,					$
		nrate:			12,					$
		rate_labels:		rate_labels,				$

		rates: 			rates}

	common mvn_d9,mvn_d9_ind,mvn_d9_dat & mvn_d9_dat=d9_dat & mvn_d9_ind=0l

   endif
endif

endif

;***************************************************************************************************************
; APID DA


if keyword_set(apids) then test = fix((total(apids eq 'da') + total(apids eq 'DA')) < 1) else test=0
if not keyword_set(apids) or test then begin
print,'Processing apid da'

	nn=0
	get_data,'mvn_STA_DA_DATA',data=t
	if size(/type,t) eq 8 && n_elements(where(t.x gt 0)) Gt 1 then begin
		npts=1024									; 64Ex1R

		ind1 = where(t.x gt 0, nn)
		tt=t.x[0:nn-1]
		da=decomp19[t.y[0:nn-1,*]]

;	Correct tt for mode change boundaries, code could be simplified
;	assume first measurement in a packet may be an average at old cadence
;	This may not be needed since for flight I plan to not average data for apid DA
 
		nda = indgen(nn,/long)
		for k=0,nn-1 do begin
			itmp = where(da[k,*] ne decomp19[255],count)
			nda[k]=count
		endfor
		store_data,'mvn_sta_DA_ndata',data={x:tt,y:nda}
		store_data,'mvn_sta_DA_ndata2',data={x:tt,y:1025-nda}
			ylim,'mvn_sta_DA_ndata2',.5,1024,1

		get_data,'mvn_STA_DA_AVG',data=avg
			gg = [64,128,256,1024]
			g2 = (avg.y[0:nn-1] and 48)/2^4		; g2 = ind into gg array
			nd = gg[g2]				; nd = # data points per sweep
			nm = nda/nd				; nm = # sweeps in a packet
			cd = 2^(avg.y[0:nn-1] and 7)		; cd = # sweeps between measurements, cadence
		dt3=tt
	; NOTE: corrections like this can screw up if packets are dropped.
		if nn gt 2 then begin
			dt3[0:nn-2] = (tt[1:nn-1] - tt[0:nn-2] - nm[0:nn-2]*cd[0:nn-2]*4.d)
;			print,dt3
			tt[0:nn-2] = tt[0:nn-2] + dt3[0:nn-2]
		endif


; 	Necessary code

		get_data,'mvn_STA_DA_DIAG',data=diag
		get_data,'mvn_STA_DA_ATTEN',data=catt						; attenuator state
		get_data,'mvn_STA_DA_AVG',data=cavg

		get_data,'mvn_STA_DA_MODE',data=md
			md1 = md.y[0:nn-1] and 127
			md2 = md.y[0:nn-1] and 15
			rt2 = (md.y[0:nn-1] and 112)/16

		header = reform(replicate(1l,16) # (256l^3*md.y[0:nn-1] + 256l^2*cavg.y[0:nn-1] + 256l*catt.y[0:nn-1] + diag.y[0:nn-1]),16*nn)

;	correct DA mode transitions using C6 data if it is available

		get_data,'mvn_sta_C6_mode',data=md6
		if size(/type,md6) eq 8 then begin
			get_data,'mvn_sta_C6_rate',data=rt6
			md2 = fix(round(interp(md6.y,md6.x,tt)))
			rt2 = fix(round(interp(rt6.y,rt6.x,tt)))
		endif
		md1 = rt2*16+md2	 

; 	the following should not be necessary since we don't plan to average

			avg = cavg.y and replicate(7,nn)
			sum = (cavg.y and replicate(8,nn))/8

			avg2 = sum*avg > 1

		comp = (cavg.y and replicate(192,nn))/128

; may need the following for CDFs
;		tt1 = tt - 2.*avg2 	
;		tt2 = tt + 2.*avg2 

;		swp_ind = md2swp[md1]									; old version
;		swp_ind = conf2swp[fix(interp((config4.y and 255)*1.,config4.x,tt)+.5),md2]					
		swp_ind = conf2swp[fix(interp((config4.y and 511)*1.,config4.x,tt)+.5),md2]					
			eprom_ver = fix(interp((config4.y and 255)*1.,config4.x,tt)+.5)
			if tt[0] lt time_double('2014-10-1/0') then eprom_ver[*]=0
		eprom_ver = fix(reform(replicate(1,16) # eprom_ver,16*nn))

		energy=nrg[swp_ind,*]

;	this section makes time series out of DA data
		; the following is correct when cd=1, spreads our measurements in time otherwise 

		get_data,'mvn_STA_DA_AVG',data=avg
			gg = [64,128,256,1024]
			g2 = (avg.y[0:nn-1] and 48)/2^4		; g2 = ind into gg array
			nd = gg[g2]				; nd = # data points per sweep
			nm = 1024/nd				; nm = # sweeps in a packet
			cd = 2^(avg.y[0:nn-1] and 7)		; cd = # sweeps between measurements, cadence
			ss = (avg.y[0:nn-1] and 8)/2^3		; ss = snapshot or average
			n2 = (ss*(cd-1)+1) 			; n2 = # sweeps averaged per measurement, either "cd" or 1
			dt = n2*4.d/nd				; dt = averaging time if  correct when data are averaged over multiple sweeps 
			tt7=tt

			tp1 = dblarr(1024,4) & tp1[*,0]=findgen(64)#replicate(1.,16) & tp1[*,1]=findgen(128)#replicate(1.,8) & tp1[*,2]=findgen(256)#replicate(1.,4)  & tp1[*,3]=findgen(1024)
			tp2 = dblarr(1024,4) & tp2[*,0]=replicate(1.,64)#findgen(16) & tp2[*,1]=replicate(1.,128)#findgen(8) & tp2[*,2]=replicate(1.,256)#findgen(4)


;			tt3 = reform((findgen(1024)+.5)#dt + tp2[*,g2]*(replicate(1.,1024)#cd) + replicate(1.,1024)#tt7,1024*nn)
			tt3 = reform(tp1[*,g2]*(replicate(1.,1024)#dt) + tp2[*,g2]*(replicate(1.,1024)#cd*4.d) + replicate(1.,1024)#tt7,1024*nn)

; old			tt3 = reform((findgen(1024)+.5)#dt + replicate(1.,1024)#tt7,1024*nn)
			da3 = reform(transpose(da),nn*1024l)
			in3 = where(da3 ne decomp19[255],ct3) 

		store_data,'mvn_sta_DA_R3_T',data={x:tt3[in3],y:da3[in3]}
			ylim,'mvn_sta_DA_R3_T',0,0,1
			options,'mvn_sta_DA_R3_T',datagap=64.
;			options,'mvn_sta_DA_R3_T',psym=1

;	this section makes energy sweeps out of DA data

		tm = total(nm)
		da2 = fltarr(tm,64) 					
		tt8 = dblarr(tm)					
		en2 = fltarr(tm,64)
		md1_2 = intarr(tm)
		md2_2 = intarr(tm)
		rt2_2 = intarr(tm)
		swp_ind_2 = intarr(tm)

		m=0l
		for i=0l,nn-1 do begin									; nn packets
			for j=0,nm[i]-1 do begin							; nm sweeps per packet
				jj=j*nd[i]								; jj index into da[0:nn-1,0:1024] array
				if da[i,jj] ne decomp19[255] then begin
					tmp      = total(reform(da[i,jj:jj+nd[i]-1],nd[i]/64,64),1)
					da2[m,*] = tmp
; old					tt8[m]   = tt[i] - 2.0d*n2[i]*(nm[i]-1) + j*4.d*n2[i]		
					tt8[m]   = tt[i] + 2.0d*n2[i]           + j*4.d*cd[i]		
					en2[m,*] = energy[i,*]
					md1_2[m] = md1[i]
					md2_2[m] = md2[i]
					rt2_2[m] = rt2[i]
					swp_ind_2[m] = swp_ind[i]
					m=m+1
				endif
			endfor
		endfor

;	correct DA mode transitions using C6 data if it is available

		if size(/type,md6) eq 8 then begin
			md2_2 = fix(round(interp(md6.y,md6.x,tt8)))
			rt2_2 = fix(round(interp(rt6.y,rt6.x,tt8)))
			md1_2 = rt2_2*16+md2_2	 
;			swp_ind_2 = conf2swp[fix(interp((config4.y and 255)*1.,config4.x,tt8)+.5),md2_2]					
			swp_ind_2 = conf2swp[fix(interp((config4.y and 511)*1.,config4.x,tt8)+.5),md2_2]					
			en2 = nrg[swp_ind_2,*]
		endif

		ind2 = where(tt8 gt 0, n) 

		store_data,'mvn_sta_DA_R3_E',data={x:tt8[0:n-1],y:da2[0:n-1,*],v:en2[0:n-1,*]}
			ylim,'mvn_sta_DA_R3_E',.4,40000,1
			zlim,'mvn_sta_DA_R3_E',10,1.e3,1
			options,'mvn_sta_DA_R3_E',datagap=64.
			options,'mvn_sta_DA_R3_E',spec=1

		store_data,'mvn_sta_DA_R3_tot',data={x:tt8[0:n-1],y:total(da2[0:n-1,*],2)}
			ylim,'mvn_sta_DA_R3_tot',0,0,1
			options,'mvn_sta_DA_R3_tot',datagap=64.
			options,'mvn_sta_DA_R3_tot',psym=-1

		store_data,'mvn_sta_DA_R3_mode',data={x:tt8[0:n-1],y:md2_2[0:n-1]}
			ylim,'mvn_sta_DA_R3_mode',-1,7,0

	endif


; Make DA common block

if size(/type,t) eq 8 and nn ge 1 then begin

;	this code assumes we never change the DA apid rate packets -- which is the current plan

	rate_channel = replicate(4,tm)					; this should be determined from header bits, but there are no plans to ever change it
	integ_time = (replicate(4.d,tm)/64.)*dt_cor			; if data rate for this apid ever changes, then determine integ_time from header
	rates = da2/(integ_time#replicate(1.,64))	
	rate_labels = ['R3_Time_A','R3_Time_B','R3_Time_C','R3_Time_D','R3_Time_RST','R3_Time_NoStart',$
		'R3_Time_Unqual','R3_Time_Qual','R3_Time_AnRej','R3_Time_MaRej','R3_Time_A&B','R3_Time_C&D']

	da_dat= {project_name:		'MAVEN',				$
		spacecraft:		'0', 					$
		data_name:		'da 1r64e', 				$
		apid:			'da',					$
;		units_name: 		'Hz', 					$
		valid: 			replicate(1,tm), 			$
		quality_flag: 		replicate(0,tm), 			$

		time:			tt8-2.,					$
		end_time:		tt8+2.,					$
		integ_t: 		integ_time,				$	

		eprom_ver:		eprom_ver,				$
		header:			header,					$
		mode:			md2_2,					$
		rate:			rt2_2,					$
		swp_ind:		swp_ind_2,				$

; note nswp is part of cdf support data but is not explicity in the common blocks - may need to add it to most common blocks
;		nswp:			n_swp,					$

		energy:			nrg,					$
		nrate:			1,					$
		rate_labels:		rate_labels,				$
		rate_channel:		rate_channel,				$

		rates: 			rates}

	common mvn_da,mvn_da_ind,mvn_da_dat & mvn_da_dat=da_dat & mvn_da_ind=0l

endif
endif


;***************************************************************************************************************
; APID DB


if keyword_set(apids) then test = fix((total(apids eq 'db') + total(apids eq 'DB')) < 1) else test=0
if not keyword_set(apids) or test then begin
print,'Processing apid db'

	nn=0
	get_data,'mvn_STA_DB_DATA',data=t
	if size(/type,t) eq 8 then begin
		npts=1024									; 1024M
		ind = where(t.x gt 0, nn)
		tt=t.x[0:nn-1]
	if nn ge 2 then begin

		get_data,'mvn_STA_DB_DIAG',data=diag
		get_data,'mvn_STA_DB_ATTEN',data=catt						; attenuator state

		get_data,'mvn_STA_DB_MODE',data=md
			md1 = md.y[0:nn-1] and 127
			md2 = md.y[0:nn-1] and 15
			rt2 = (md.y[0:nn-1] and 112)/16

		get_data,'mvn_STA_DB_AVG',data=cavg
		avg = cavg.y and replicate(7,nn)
		sum = (cavg.y and replicate(8,nn))/8
			avg2 = sum*avg > 1

		comp = (cavg.y and replicate(192,nn))/128

;	correct DB mode transitions using C6 data if it is available
		get_data,'mvn_sta_C6_mode',data=md6
		if size(/type,md6) eq 8 then begin
			get_data,'mvn_sta_C6_rate',data=rt6
			md2 = fix(round(interp(md6.y,md6.x,tt)))
			rt2 = fix(round(interp(rt6.y,rt6.x,tt)))
		endif
		md1 = rt2*16+md2	 

		tt1 = tt - 2.*avg2 	
		tt2 = tt + 2.*avg2 

		header = 256l^3*md.y[0:nn-1] + 256l^2*cavg.y[0:nn-1] + 256l*catt.y[0:nn-1] + diag.y[0:nn-1]

		store_data,'mvn_sta_DB_mode',data={x:tt,y:md2}
			ylim,'mvn_sta_DB_mode',-1,7,0

;		swp_ind = conf2swp[fix(interp((config4.y and 255)*1.,config4.x,tt)+.5),md2]					
		swp_ind = conf2swp[fix(interp((config4.y and 511)*1.,config4.x,tt)+.5),md2]					
			eprom_ver = fix(interp((config4.y and 255)*1.,config4.x,tt)+.5)
			if tt[0] lt time_double('2014-10-1/0') then eprom_ver[*]=0

		store_data,'mvn_sta_DB_DATA',data={x:tt,y:t.y[0:nn-1,*],v:findgen(1024)}

		tmp=decomp19[t.y[0:nn-1,*]]							; [time,ma]

			aa = fltarr(nn,64)
			ind1=indgen(8) & ind2=indgen(16) & ind3=indgen(32)
			for i=0l,nn-1 do begin 
				for j=0,31 do aa(i,j) = total(tmp[i,j*8+ind1],2)
				for j=32,47 do aa(i,j) = total(tmp[i,(j-16)*16+ind2],2)
				for j=48,63 do aa(i,j) = total(tmp[i,(j-32)*32+ind3],2)
			endfor

		store_data,'mvn_sta_DB_MH_M',data={x:tt,y:tmp,v:findgen(1024)}
		store_data,'mvn_sta_DB_MH_M64',data={x:tt,y:aa,v:indgen(64)}
		store_data,'mvn_sta_DB_MH_tot',data={x:tt,y:total(tmp,2)}

		ylim,'mvn_sta_DB_DATA',0,0,1
		ylim,'mvn_sta_DB_MH_tot',0,0,1
		ylim,'mvn_sta_DB_MH_M',0,1024,0
		ylim,'mvn_sta_DB_MH_M64',0,64,0
		zlim,'mvn_sta_DB_MH_M',1,1.e6,1
		zlim,'mvn_sta_DB_MH_M64',1,1.e6,1
		datagap=512.
		options,'mvn_sta_DB_DATA',datagap=datagap
		options,'mvn_sta_DB_MH_M',datagap=datagap
		options,'mvn_sta_DB_MH_M64',datagap=datagap
		options,'mvn_sta_DB_MH_tot',datagap=datagap
		options,'mvn_sta_DB_MH_M','spec',1
		options,'mvn_sta_DB_MH_M64','spec',1
		options,'mvn_sta_DB_MH_M',ytitle='sta!CMHist-DB!C!CMass!Cbin'
		options,'mvn_sta_DB_MH_M64',ytitle='sta!CMHist-DB!C!CMass!Cbin'

		; zero common then load the data
;			common mvn_sta_mh_raw,mvn_sta_mh_ind,mvn_sta_mh_dat & mvn_sta_mh_dat=0 & mvn_sta_mh_ind=-1l


	endif
	endif


; Make DB common block

   if size(/type,t) eq 8 and nn ge 2 then begin

	db_dat= {project_name:		'MAVEN',				$
		spacecraft:		'0', 					$
		data_name:		'db 1024m', 				$
		apid:			'db',					$
;		units_name: 		'counts', 				$
		valid: 			replicate(1,nn), 			$
		quality_flag: 		replicate(0,nn), 			$

		time:			tt1,					$
		end_time:		tt2,					$
		integ_t: 		(tt2-tt1)*dt_cor,			$	

; note nswp and ntof are part of cdf support data but are not explicity in the common blocks - may need to add it to most common blocks
;		nswp:			n_swp,					$
;		ntof:			1024,					$

		eprom_ver:		eprom_ver,				$
		header:			header,					$
		mode:			md2,					$
		rate:			rt2,					$
		swp_ind:		swp_ind,				$

		energy: 		nrg, 					$

		tof: 			mhist_tof, 				$

		data: 			tmp}

	common mvn_db,mvn_db_ind,mvn_db_dat & mvn_db_dat=db_dat & mvn_db_ind=0l

   endif
endif

; this program modifies the geometric factor values in the comment blocks - modified 20191028

mvn_sta_l2_gf_update

;***************************************************************************************************************
;***************************************************************************************************************

; form combined plots

;   Mixed product plots

	tt1=0 & tt2=0 & tt3=0
	get_data,'mvn_sta_CA_P3_A',data=t1
	get_data,'mvn_sta_D4_P4E_A',data=t2
	get_data,'mvn_sta_D2_P4D_A',data=t3
	if size(/type,t1) eq 8 then tt1=1
	if size(/type,t2) eq 8 then tt2=1
	if size(/type,t3) eq 8 then tt3=1
	if (tt1) then store_data,'mvn_sta_A',data=['mvn_sta_CA_P3_A'] 
	if (tt2) then store_data,'mvn_sta_A',data=['mvn_sta_D4_P4E_A']
	if (tt3) then store_data,'mvn_sta_A',data=['mvn_sta_D2_P4D_A'] 
	if (tt1 and tt2) then store_data,'mvn_sta_A',data=['mvn_sta_CA_P3_A','mvn_sta_D4_P4E_A']
	if (tt1 and tt3) then store_data,'mvn_sta_A',data=['mvn_sta_CA_P3_A','mvn_sta_D2_P4D_A']
	if (tt2 and tt3) then store_data,'mvn_sta_A',data=['mvn_sta_D4_P4E_A','mvn_sta_D2_P4D_A']
	if (tt1 and tt2 and tt3) then store_data,'mvn_sta_A',data=['mvn_sta_CA_P3_A','mvn_sta_D4_P4E_A','mvn_sta_D2_P4D_A']
		ylim,'mvn_sta_A',-180,200,0
		zlim,'mvn_sta_A',1,1.e4,1
		options,'mvn_sta_A','spec',1
		options,'mvn_sta_A',ytitle='sta!C!CAnode!Cphi'

	tt1=0 & tt2=0 
	get_data,'mvn_sta_C8_P2_D',data=t1
	get_data,'mvn_sta_D4_P4E_D',data=t2
	if size(/type,t1) eq 8 then tt1=1
	if size(/type,t2) eq 8 then tt2=1
	if (tt1) then store_data,'mvn_sta_D',data=['mvn_sta_C8_P2_D']
	if (tt2) then store_data,'mvn_sta_D',data=['mvn_sta_D4_P4E_D']
	if (tt1 and tt2) then store_data,'mvn_sta_D',data=['mvn_sta_D4_P4E_D','mvn_sta_C8_P2_D']
		ylim,'mvn_sta_D',-45,45,0
		zlim,'mvn_sta_D',1,1.e4,1
		options,'mvn_sta_D','spec',1
		options,'mvn_sta_D',ytitle='sta!C!CDef!Ctheta'

;    P4 Survey combined plots

	tt1=0 & tt2=0 & tt3=0 & tt4=0
	get_data,'mvn_sta_CC_P4A_E',data=t1
	get_data,'mvn_sta_CE_P4B_E',data=t2
	get_data,'mvn_sta_D0_P4C_E',data=t3
	get_data,'mvn_sta_D2_P4D_E',data=t4
	if size(/type,t1) eq 8 then tt1=1
	if size(/type,t2) eq 8 then tt2=1
	if size(/type,t3) eq 8 then tt3=1
	if size(/type,t4) eq 8 then tt4=1
	if tt1 or tt2 or tt3 or tt4 then begin
		store_data,'mvn_sta_P4_E',data=['mvn_sta_CC_P4A_E','mvn_sta_CE_P4B_E','mvn_sta_D0_P4C_E','mvn_sta_D2_P4D_E']
		ylim,'mvn_sta_P4_E',.1,40000.,1
		zlim,'mvn_sta_P4_E',1,1.e5,1
		options,'mvn_sta_P4_E',ytitle='sta!CP4 !CEnergy!CeV'
	endif

	tt1=0 & tt2=0 & tt3=0 & tt4=0
	get_data,'mvn_sta_CC_P4A_M',data=t1
	get_data,'mvn_sta_CE_P4B_M',data=t2
	get_data,'mvn_sta_D0_P4C_M',data=t3
	get_data,'mvn_sta_D2_P4D_M',data=t4
	if size(/type,t1) eq 8 then tt1=1
	if size(/type,t2) eq 8 then tt2=1
	if size(/type,t3) eq 8 then tt3=1
	if size(/type,t4) eq 8 then tt4=1
	if tt1 or tt2 or tt3 or tt4 then begin
		store_data,'mvn_sta_P4_M',data=['mvn_sta_CC_P4A_M','mvn_sta_CE_P4B_M','mvn_sta_D0_P4C_M','mvn_sta_D2_P4D_M']
		ylim,'mvn_sta_P4_M',.5,100,1
		zlim,'mvn_sta_P4_M',1,1.e5,1
		options,'mvn_sta_P4_M',ytitle='sta!CP4 !CMass!Camu'
	endif


	tt1=0 & tt2=0 & tt3=0 
	get_data,'mvn_sta_CC_P4A_D',data=t1
	get_data,'mvn_sta_CE_P4B_D',data=t2
	get_data,'mvn_sta_D0_P4C_D',data=t3
	if size(/type,t1) eq 8 then tt1=1
	if size(/type,t2) eq 8 then tt2=1
	if size(/type,t3) eq 8 then tt3=1
	if tt1 or tt2 or tt3 then begin
		store_data,'mvn_sta_P4_D',data=['mvn_sta_CC_P4A_D','mvn_sta_CE_P4B_D','mvn_sta_D0_P4C_D']
		ylim,'mvn_sta_P4_D',-45,45,0
		zlim,'mvn_sta_P4_D',1,1.e5,1
		options,'mvn_sta_P4_D',ytitle='sta!CP4 !CDef!Ctheta'
	endif


	tt2=0 & tt3=0 & tt4=0
	get_data,'mvn_sta_CE_P4B_A',data=t2
	get_data,'mvn_sta_D0_P4C_A',data=t3
	get_data,'mvn_sta_D2_P4D_A',data=t4
	if size(/type,t2) eq 8 then tt2=1
	if size(/type,t3) eq 8 then tt3=1
	if size(/type,t4) eq 8 then tt4=1
	if tt2 or tt3 or tt4 then begin
		store_data,'mvn_sta_P4_A',data=['mvn_sta_CE_P4B_A','mvn_sta_D0_P4C_A','mvn_sta_D2_P4D_A']
		ylim,'mvn_sta_P4_A',-180,200,0
		zlim,'mvn_sta_P4_A',1,1.e5,1
		options,'mvn_sta_P4_A',ytitle='sta!CP4 !CAnode!Cphi'
	endif

;   P4 Archive combined plots

	tt1=0 & tt2=0 & tt3=0 & tt4=0
	get_data,'mvn_sta_CD_P4A_E',data=t1
	get_data,'mvn_sta_CF_P4B_E',data=t2
	get_data,'mvn_sta_D1_P4C_E',data=t3
	get_data,'mvn_sta_D3_P4D_E',data=t4
	if size(/type,t1) eq 8 then tt1=1
	if size(/type,t2) eq 8 then tt2=1
	if size(/type,t3) eq 8 then tt3=1
	if size(/type,t4) eq 8 then tt4=1
	if tt1 or tt2 or tt3 or tt4 then begin
		store_data,'mvn_sta_P4_arc_E',data=['mvn_sta_CD_P4A_E','mvn_sta_CF_P4B_E','mvn_sta_D1_P4C_E','mvn_sta_D3_P4D_E']
		ylim,'mvn_sta_P4_arc_E',.4,40000.,1
		ylim,'mvn_sta_P4_arc_E',.1,1.e4,1
		options,'mvn_sta_P4_arc_E',ytitle='sta!CP4 arc !CEnergy!CeV'
	endif

	tt1=0 & tt2=0 & tt3=0 & tt4=0
	get_data,'mvn_sta_CD_P4A_M',data=t1
	get_data,'mvn_sta_CF_P4B_M',data=t2
	get_data,'mvn_sta_D1_P4C_M',data=t3
	get_data,'mvn_sta_D3_P4D_M',data=t4
	if size(/type,t1) eq 8 then tt1=1
	if size(/type,t2) eq 8 then tt2=1
	if size(/type,t3) eq 8 then tt3=1
	if size(/type,t4) eq 8 then tt4=1
	if tt1 or tt2 or tt3 or tt4 then begin
		store_data,'mvn_sta_P4_arc_M',data=['mvn_sta_CD_P4A_M','mvn_sta_CF_P4B_M','mvn_sta_D1_P4C_M','mvn_sta_D3_P4D_M']
		ylim,'mvn_sta_P4_arc_M',.5,100,1
		zlim,'mvn_sta_P4_arc_M',1,1.e4,1
		options,'mvn_sta_P4_arc_M',ytitle='sta!CP4 arc !CMass!Camu'
	endif


	tt1=0 & tt2=0 & tt3=0 
	get_data,'mvn_sta_CD_P4A_D',data=t1
	get_data,'mvn_sta_CF_P4B_D',data=t2
	get_data,'mvn_sta_D1_P4C_D',data=t3
	if size(/type,t1) eq 8 then tt1=1
	if size(/type,t2) eq 8 then tt2=1
	if size(/type,t3) eq 8 then tt3=1
	if tt1 or tt2 or tt3 then begin
		store_data,'mvn_sta_P4_arc_D',data=['mvn_sta_CD_P4A_D','mvn_sta_CF_P4B_D','mvn_sta_D1_P4C_D']
		ylim,'mvn_sta_P4_arc_D',-45,45,0
		zlim,'mvn_sta_P4_arc_D',1,1.e5,1
		options,'mvn_sta_P4_arc_D',ytitle='sta!CP4 arc!CDef!Ctheta'
	endif


	tt2=0 & tt3=0 & tt4=0
	get_data,'mvn_sta_CF_P4B_A',data=t2
	get_data,'mvn_sta_D1_P4C_A',data=t3
	get_data,'mvn_sta_D3_P4D_A',data=t4
	if size(/type,t2) eq 8 then tt2=1
	if size(/type,t3) eq 8 then tt3=1
	if size(/type,t4) eq 8 then tt4=1
	if tt2 or tt3 or tt4 then begin
		store_data,'mvn_sta_P4_arc_A',data=['mvn_sta_CF_P4B_A','mvn_sta_D1_P4C_A','mvn_sta_D3_P4D_A']
		ylim,'mvn_sta_P4_arc_A',-180,200,0
		options,'mvn_sta_P4_arc_A',ytitle='sta!CP4 arc !CAnode!Cphi'
	endif

	options,'mvn_sta_*','x_no_interp',1
	options,'mvn_sta_*','y_no_interp',1

;   Combined mode data

	tt1=0 & tt2=0 & tt3=0 & tt4=0
	get_data,'mvn_sta_CD_mode',data=t1
	get_data,'mvn_sta_CF_mode',data=t2
	get_data,'mvn_sta_D1_mode',data=t3
	get_data,'mvn_sta_D3_mode',data=t4
	if size(/type,t1) eq 8 then tt1=1
	if size(/type,t2) eq 8 then tt2=1
	if size(/type,t3) eq 8 then tt3=1
	if size(/type,t4) eq 8 then tt4=1
	if tt1 or tt2 or tt3 or tt4 then begin
		store_data,'mvn_sta_P4_arc_mode',data=['mvn_sta_CD_mode','mvn_sta_CF_mode','mvn_sta_D1_mode','mvn_sta_D3_mode']
			ylim,'mvn_sta_P4_arc_mode',-1,7
			options,'mvn_sta_P4_arc_mode',ytitle='sta!CP4 arc!C!Cmode'
			options,'mvn_sta_CD_mode',colors=cols.black
			options,'mvn_sta_CF_mode',colors=cols.red
			options,'mvn_sta_D1_mode',colors=cols.green
			options,'mvn_sta_D3_mode',colors=cols.blue
			options,'mvn_sta_CD_mode',psym=1
			options,'mvn_sta_CF_mode',psym=1
			options,'mvn_sta_D1_mode',psym=1
			options,'mvn_sta_D3_mode',psym=1
	endif

	tt1=0 & tt2=0 & tt3=0 & tt4=0
	get_data,'mvn_sta_C0_mode',data=t1
	get_data,'mvn_sta_C2_mode',data=t2
	get_data,'mvn_sta_C4_mode',data=t3
	get_data,'mvn_sta_C6_mode',data=t4
	get_data,'mvn_sta_C8_mode',data=t5
	get_data,'mvn_sta_CA_mode',data=t6
	if size(/type,t1) eq 8 then tt1=1 else tt1=0
	if size(/type,t2) eq 8 then tt2=1 else tt2=0
	if size(/type,t3) eq 8 then tt3=1 else tt3=0
	if size(/type,t4) eq 8 then tt4=1 else tt4=0
	if size(/type,t5) eq 8 then tt5=1 else tt5=0
	if size(/type,t6) eq 8 then tt6=1 else tt6=0
	if tt1 or tt2 or tt3 or tt4 or tt5 or tt6 then begin
		store_data,'mvn_sta_mode',data=['mvn_sta_C0_mode','mvn_sta_C2_mode','mvn_sta_C4_mode','mvn_sta_C6_mode','mvn_sta_C8_mode','mvn_sta_CA_mode']
			ylim,'mvn_sta_mode',-1,7,0
			options,'mvn_sta_mode',ytitle='sta!Cmode'
			options,'mvn_sta_C0_mode',colors=cols.black
			options,'mvn_sta_C2_mode',colors=cols.red
			options,'mvn_sta_C4_mode',colors=cols.green
			options,'mvn_sta_C6_mode',colors=cols.blue
			options,'mvn_sta_C8_mode',colors=cols.cyan
			options,'mvn_sta_CA_mode',colors=cols.magenta
			options,'mvn_sta_C0_mode',psym=1
			options,'mvn_sta_C2_mode',psym=1
			options,'mvn_sta_C4_mode',psym=1
			options,'mvn_sta_C6_mode',psym=1
			options,'mvn_sta_C8_mode',psym=1
			options,'mvn_sta_CA_mode',psym=1
	endif


; get rid of raw data tplot structures

if not keyword_set(all) then begin
		store_data,delete='mvn_STA_*'
endif

	if c6_jitter_flag then print,'Error: C6 time jitter correction failed!!!!
	if c6_cnt8 ne 0 then print,'C6 .5 sec time jitter corrections = ',c6_cnt8,c6_cnt9,c6_cnt10
	if c0_jitter_flag then print,'Error: C0 time jitter correction failed!!!!
	if c0_cnt8 ne 0 then print,'C0 .5 sec time jitter corrections = ',c0_cnt8,c0_cnt9,c0_cnt10
	if c8_jitter_flag then print,'Error: C8 time jitter correction failed!!!!
	if c8_cnt8 ne 0 then print,'C8 .5 sec time jitter corrections = ',c8_cnt8,c8_cnt9,c8_cnt10
	if ca_jitter_flag then print,'Error: CA time jitter correction failed!!!!
	if ca_cnt8 ne 0 then print,'CA .5 sec time jitter corrections = ',ca_cnt8,ca_cnt9,ca_cnt10
	if d8_jitter_flag then print,'Error: D8 time jitter correction failed!!!!
	if d8_cnt8 ne 0 then print,'D8 .5 sec time jitter corrections = ',d8_cnt8,d8_cnt9,d8_cnt10
	if da_jitter_flag then print,'Error: DA time jitter correction failed!!!!
	if da_cnt8 ne 0 then print,'DA .5 sec time jitter corrections = ',da_cnt8,da_cnt9,da_cnt10

end

