pro wrt1bda, irec, rec1, lun, bytout, bcs_fixext, dp_clock_ref, bcs_clock_ref, $
			data, mheader, mblock, qMissModeId, qdiscon, grpplan, modeid_arr, qfast, qproblem
;
;
;INPUT:
;	qproblem- needed to mark cases where #Extracted is greater than #Expected.  There is
;		  usually a good mode ID associated with these so the ".length" field was
;		  not being set properly.  Now "blockid" will be set to 4 for those cases.
;HISTORY:
;	 2-Mar-92 (MDM) - Added qproblem parameter (see above explanation)
;	 4-Mar-92 (MDM) - in addition to marking blockid=4 for "qproblem" sets, 
;			  also set the length in roadmap to be the actual length 
;			  of data.
;	21-Mar-92 (MDM) - Added marking data which have 'F9'x values (fill data)
;			  in the roadmap as BLOCKID = 5
;	24-Mar-92 (MDM) - Added marking data which have 'AA'x values (S/C fill data)
;			  in the roadmap as BLOCKID = 5
;	 6-Aug-92 (MDM) - Added writing information to DP_FLAGS field for blockIDs
;			  greater than 1 since that value comes out of the 
;			  mode header and for fixed extraction, that information is
;			  not available.
;	 6-May-94 (MDM) - Corrected for the case where one of the channels has no
;			  datapoints in the spectra
;	27-Oct-95 (MDM) - Corrected for case where modeID is equal to 190.
;
;
common blk_wrt1bda, phac_1ago, phac_2ago	;used because channel number for
						;cal data is out of phase by
						;1.5 major frames
;
if (n_elements(qproblem) eq 0) then qproblem = 0
;
qdebug = 1
;
if ((n_elements(phac_1ago) eq 0)  or (qdiscon)) then begin
    if (qdebug) then print, 'Resetting PHA control buffer'
    phac_1ago = intarr(2)
    phac_2ago = intarr(2)
end
;
ref_struct, ref, dpos1, dpos2, sxtos1, sxtos2, sxtos3, stat1
rsiz = ref.BCS_Fil_Rec_Siz
bcs_struct, bcs_index = bcs_index
;
get1gen, rec1, dp_clock_ref, gen_index	;TODO - rec1 should be an earlier record!?!!?!?
;
;-------------------- BCS_Index Info
;
bcs_index.dp_time_out		= gen_index.dp_time	;current MF is the time the data was read out
;
qdefined = 0
if (bcs_fixext eq 0) then begin
    ;;bcs_grp_plan, mheader(8), nGroup, Group, nSampPChan, qdefined	;temporary routine to define the plans
    modeid = mheader(8)
    qdefined = 0
    ;if (modeid le 190) then if (grpplan(modeid).planid ne -1) then begin
    if (modeid lt n_elements(grpplan)) then if (grpplan(modeid).planid ne -1) then begin
	qdefined = 1
	ngroup = grpplan(modeid).ngrp
	group  = grpplan(modeid).grps
	nSampPChan = intarr(4)
	for ichan=0,3 do begin
	    n = 0
	    for j=0,nGroup(ichan)-1 do n = n + group(j*2, ichan)
	    nSampPChan(ichan) = n
	end
    end
    ;
    if (qdefined) then begin
	;Check to see if the mode header was corrupted (trouble in beginning of mission)
	;Check by comparing to the mode header expected # of bytes to the grouper plan expected #
        n_expect = (mheader(11) and 3)*long(256) + mheader(10) + 1
	if (n_expect ne total(nSampPChan)) then begin
	    err_log, 'STR', 'ERR/BCS: #Expected NE grouper plan - saving as mode 255'
	    qdefined = 0
	end
    end

    if (qdefined) then begin
	if (qfast) then blockID = 1 else blockID = 0
	ss = where(data eq 'F9'x, count)
	if (count ne 0) then blockID = 5
	ss = where(data eq 'AA'x, count)
	if (count gt 5) then blockID = 5	;added 24-Mar-92

	bcs_index.blockID		= blockID
	bcs_index.ModeID		= mheader(8)
	bcs_index.ModeRepNum		= mheader(6)
	bcs_index.ControlTally		= mheader(7)
	bcs_index.ControlByte		= mheader(12)
	bcs_index.dgi			= mheader(9)
	bcs_index.dp_flags		= mheader(4)
	bcs_index.bcs_status		= mheader(5)

	bcs_index.nSampPChan		= nSampPChan

	bcs_index.length		= total(nSampPChan)

	;Overwrite time info with the time that the DATA was taken
	;
	bcs_clock			= mheader(3)*long(256) + mheader(2)
	msod = bcs_clock_ref.msod + (bcs_clock - bcs_clock_ref.bcs)*125		;0.125 sec per clock "tick"
	ds79 = bcs_clock_ref.ds79
        check_time, msod, ds79

	;----- Check for case where BCS Clock has rolled over, but the data being saved now is from before the BCS clock
	;      rolled over (saved in the queue and dumped when Flare occurred or BCS-OUT).  Assume that the BCS queue 
	;      gets reset once an orbit (at start of day?) and therefore the data should not be more than 90 minutes out of
	;      the current time.
	diff = (ds79 - gen_index.day)*86400 + (msod - gen_index.time)/1000.		;how long ago data was taken from
											;the downlink time
	if (diff gt 2) then begin	;data cannot be taken after current time
					;should use "gt 0" condition, but there are problems?  11-Oct-91
					;changed to be "gt 2" on 24-Oct-91 (2 seconds for 1 frame at high rate)
	    msod = msod - long(8192)*8*125		;back the clock up  one complete cycle
	    err_log, 'STR', 'WRT/BCS: BCS Clock rolled over before dumping queue data - CORRECTED' + string(diff) + ' sec'
	end

	check_time, msod, ds79
	gen_index.time			= msod
	gen_index.day			= ds79

	err_log, 'STR', 'INF/BCS: Saving spectral data taken at: ' + fmt_tim(gen_index)

	if (n_elements(modeid_arr) eq 0) then begin
	    modeid_arr = bcs_index.modeid
	end else begin
	    modeid_arr = [modeid_arr, bcs_index.modeid]
	end
    end else begin
	err_log, 'STR', 'ERR/BCS: Undefined Mode.  Mode Header = ' + string(mheader, format='(13i4)')

	bcs_index.blockID		= 4
	bcs_index.ModeID		= 255

	data = [mheader, data]					;put the header out with the data
	bcs_index.length		= n_elements(data)
    end
end
if (qproblem) then begin
    bcs_index.blockID	= 4
    bcs_index.length		= n_elements(data)
end
if (bcs_fixext eq 2) then begin         ;fixed extraction - memory dump
    bcs_index.blockID                   = 2
    bcs_index.length			= n_elements(data)
end
if (bcs_fixext eq 3) then begin		;fixed extraction - stim/cal data
    chan_1st_half = phac_2ago(1)
    chan_2nd_half = phac_1ago(0)
    ;if (qdebug) then print, 'Chans ', chan_1st_half, chan_2nd_half
    bcs_index.blockID			= 3
    bcs_index.dgi			= rec1(16+49, 22)	;TODO - delayed ??
    bcs_index.modeID			= chan_1st_half + chan_2nd_half*16
    phac_2ago = phac_1ago
    phac_1ago = rec1(16+49, [18,18+32])/64 + 1
    bcs_index.length			= n_elements(data)
end

if (bcs_index.blockID ge 2) then begin
    dpmode      = mask(rec1(dpos1,  2), 0, 4) 
    dprate      = mask(rec1(stat1, 15), 5, 3) 
    case dpmode of
	 9: bcs_index.dp_flags = 2		;flare
	13: bcs_index.dp_flags = 0		;quiet
	 6: bcs_index.dp_flags = 4		;BCSmem
	11: bcs_index.dp_flags = 128		;BCS-Out
	else:
    endcase
    case dprate of
	1: bcs_index.dp_flags = bcs_index.dp_flags + 0	;low rate
	2: bcs_index.dp_flags = bcs_index.dp_flags + 8	;med rate
	3: bcs_index.dp_flags = bcs_index.dp_flags + 24	;hi rate
	else:
    endcase
end

bcs_index.MissBasicData		= 0			;TODO?
bcs_index.MissModeID		= qMissModeID
;
;-------------------- Gen_Index Info
;
ext1pntg, gen_index		;get processed pointing information
gen_index.nIndexByte            = get_nbytes(gen_index) + get_nbytes(bcs_index)
n = n_elements(data)
if ((n mod rsiz) ne 0) then begin
    n = (long(n/rsiz)+1)*rsiz
    data = [data, bytarr(n-n_elements(data))]
    err_log, 'STR', 'WRN/BCS: Had to put buffer space in Data section to end on a record boundary
end
gen_index.nDataByte             = n
;
;-------------------- Get total counts for the Data 
;
if ((bcs_fixext eq 0) and (qdefined)) then begin
    ;; bcs_pad_data, irec, nGroup, Group, nSampPChan, data	;put spectral simulation data into file

    if (total(nSampPChan) eq n_elements(data)) then begin
	ist = 0
	for i=0,3 do begin
	    nsamp = bcs_index.nSampPChan(i)
	    ien = ist + nsamp-1 -1	;also drop the last bin - it has the invalid energy counts

	    if (ien ge ist) then begin	;case when NSAMP=0 - modified 6-May-94
		temp = data(ist:ien)
		ss = where(temp eq 170)	;check for S/C dummy data
		if (n_elements(ss) lt 10) then begin
		    temp = bcs_decomp(temp)	;decompress data
		    bcs_index.total_cnts(i) = total(temp)/10.	;TODO - OK?
		end
	    end

	    ist = ist + nsamp
	end
    end
end
if (bcs_fixext eq 3) then begin
    tot1 = total(data(2:255))/10.	;skip first two bytes - they are FFFF
    tot2 = total(data(258:511))/10.
    if ((chan_1st_half ge 1) and (chan_1st_half le 4)) then bcs_index.total_cnts(chan_1st_half-1) = tot1
    if ((chan_2nd_half ge 1) and (chan_2nd_half le 4)) then bcs_index.total_cnts(chan_2nd_half-1) = tot2
    ;if chan_1st_half = chan_2nd_half, the value is overwritten
end
;
;-------------------- Write Index and Data 
;
rdwrt, 'W', lun, bytout, rsiz, gen_index, 1
rdwrt, 'W', lun, bytout, rsiz, bcs_index, 1
rdwrt, 'W', lun, bytout, rsiz, data, 1
;
end
