pro wrt1orbit, infil, prefix, instr, dir_out, fileid_out, dset_str, dp_arr, dp_sync, $
			progname, prog2verno, roadmap, ss_dset_arr, hxa_scan, $
			orbit_times=orbit_times
;
;+
;NAME:
;	wrt1orbit
;PURPOSE:
;	Procedure that writes part of a 24 hour file into a 
;	single orbit file.
;INPUT:
;	infil	- the input file name
;	prefix	- the file prefix (ie: bda, sfr, ...)
;	instr	- the instrument (ie: bcs, sxt, ...)
;	dir_out	- the output directory array - need to match the input file (.ifil) with the proper output directory
;	fileid_out- the fileid for the output file
;	dset_str- a list of data set #'s which satisfy the time range requirement
;	dp_arr	- a list of dp_sync record #'s which satisfy the time range requirement
;	progname- the program name (for file header)
;	roadmap	- the roadmap for "infil" (passed so that each time RD_ROADMAP and RD_XDA is called it does not re-read the
;		  roadmap
;	orbit_times- a structure holding the starting/ending orbit times for this file
;	overwrite- If set, clobber the existing file if it exists.
;HISTORY:
;	Written Fall '91 by M.Morrison
;	 9-Mar-92 (MDM) Various changes to get it working for the 
;			first "official" data tape distribution
;	17-Apr-92 (MDM) Significant re-organization of the code
;			Arranged so that duplicate images are combined
;			together (there can be images that are split because
;			of 24 hr boundary on the raw telemetry files, or because
;			of anomalous triggers during reformatting)
;	17-Apr-92 (MDM) Changed so that RD_XDA is not called for each dataset
;			(it was too slow, even with the mods to RD_XDA to only
;			re-read the roadmap when necessary).  It reads all
;			datasets once except for the FFI case.
;	24-Apr-92 (MDM) - Updated so that duplicate FFI images only are
;			  added for where there is new data (used to add to
;			  complete images because SIRIUS gave overlaps in data).
;	24-Jun-92 (MDM) - Adjusted to not write out duplicate copies of datasets
;			  which was happening because SIRIUS was giving 
;			  duplicate overlap stuff.  WBS required some special
;			  modifications too
;	12-Apr-95 (MDM) - Modified to not count the fill data ("AA" hex) when
;			  calculating the percentage of the image when recombining
;			  two SXT images.
;-
;
dset_arr = dset_str.dset		;the dataset # WITHIN THE FILES
ifil_arr = dset_str.ifil
ifil_uniq = ifil_arr( uniq(ifil_arr) )
ifil = dset_str(0).ifil			;file with the first dataset to be extracted
;
if ((dset_arr(0) eq -99) and (dp_arr(0) eq -1)) then return	;no data in that orbit
;
rd_pointer, infil(ifil), fpoint
rd_fheader, infil(ifil), fhead
rsiz = fpoint(0).vms_rec_size
progverno = fhead(0).progverno	;use REFORMAT version number
;
rd_qs, infil(ifil), qs			;only looks at first file since RD_QS can only hand one file
;TODO - just grab relevant qs to be copied (time wise)
;
if (strupcase(strmid(prefix,0,1)) eq 'B') then begin
    if (dp_arr(0) ne -1) then begin
	dp_sync_out = dp_sync(dp_arr)
	ndp_sync_out = n_elements(dp_sync_out)
    end else begin
	ndp_sync_out = 0
    end
end
;
outfil = concat_dir(dir_out(ifil), prefix + fileid_out)
;
get_lun, lun
print, 'Opening a new file: ', outfil
open_da_file, lun, dir_out(ifil), prefix, fileid_out, rsiz, bytout, fpoint, qs
;
ndset_arr = n_elements(dset_arr)
if (dset_arr(0) ge 0) then begin	;need to check for case where no BDA spec data, but DP_SYNC data
    idset_infil = 0			;dataset # from input file that is being saved
    idset = 0				;dataset # of portion that was extracted that is being saved (because of FFI problem)

    if (strupcase(prefix) ne 'SFR') then rd_xda, infil, dset_str, index, data, roadmap		;read all data

    repeat begin			;do them one dataset at a time to avoid FFI memory problems
	idset = idset_infil

	if (strupcase(prefix) eq 'SFR') then begin
	    dset_str0 = dset_str(idset_infil)
	    rd_xda, infil, dset_str0, index, data, roadmap
	    idset = 0			;only extracting one dataset at a time
	end

	index(idset).gen.nIndexByte = get_nbytes(index(idset))	;needed because RD routine sometimes expands on the structure - SHIT

	case strupcase(strmid(prefix,0,1)) of
          'B': begin
		n = index(idset).bcs.length
		nn = index(idset).gen.ndatabyte		;case where there is padded data to be able to 
							;stop on a 16 byte boundary
		data0 = data(0:n-1, idset)
		if (n ne nn) then data0 = [data0, bytarr(nn-n)]
		rdwrt, 'W', lun, bytout, rsiz, index(idset), 1
		rdwrt, 'W', lun, bytout, rsiz, data0, 1
	     end
          'H': begin
		rdwrt, 'W', lun, bytout, rsiz, index(idset), 1
		;---- only write out if in flare mode
		if (index(idset).gen.ndatabyte ne 0) then rdwrt, 'W', lun, bytout, rsiz, data(*,*,*,idset), 1
	     end
          'S': begin
		nx = index(idset).sxt.shape_sav(0)
		ny = index(idset).sxt.shape_sav(1)
		data0 = data(0:nx-1,0:ny-1,idset)

		if (idset_infil+1 le ndset_arr-1) then begin
		    del = int2secarr(roadmap(ss_dset_arr(idset_infil+1)), roadmap(ss_dset_arr(idset_infil)))
		    if (del le 0.1) then begin			;the image is for the same time and should be re-combined
								;this only handles the case of a breakup into TWO parts, not
								;more than two parts.
			rd_xda, infil, dset_str(idset_infil+1), index2, data2, roadmap
			p1 = index(idset).sxt.percentd 
			p2 = index2.sxt.percentd
			print, 'WRT1ORBIT - FFI or PFI being pieced together', fmt_tim(index(idset))
			if (p1 eq 255) then begin
			    print, 'WRT1ORBIT - Not doing it'
			end else begin
			    ssss = where(data0 eq 0)
			    data0(ssss) = data2(ssss)	;only update the portions where there is potentially new data
			    ;;sssss = where(data2(ssss) ne 0)	;only update the percentage for pixels that are non-zero
			    ;only update the percentage for pixels that are non-zezo and non fill
			    sssss = where((data2(ssss) ne 0) and (data2(ssss) ne "AA"x))
			    p2 = (n_elements(sssss) * 255) / n_elements(data0)	;percent of data appended
			    index(idset).sxt.percentd = (p1 + p2 + 1)<255	;+1 because of round off errors
			end
			idset_infil = idset_infil + 1			;skip the next image
		    end
		end
		rdwrt, 'W', lun, bytout, rsiz, index(idset), 1
		rdwrt, 'W', lun, bytout, rsiz, data0, 1
	     end
	  'W': begin
		if (int2secarr(index(idset).gen2, index(idset).gen) ge 0) then begin	;second half of dataset should be greater than (or equal for case where there is only one half present)
		    rdwrt, 'W', lun, bytout, rsiz, index(idset), 1
		    rdwrt, 'W', lun, bytout, rsiz, data(idset), 1
		end else begin
		    roadmap(ss_dset_arr(idset_infil)).day = 4600	;do this so that the check below for duplicate dataset times is fooled and the second copy 
		end							;is written out
	     end
          'C': begin
		rdwrt, 'W', lun, bytout, rsiz, index(idset), 1
		rdwrt, 'W', lun, bytout, rsiz, data(idset), 1
		;;rdwrt, 'W', lun, bytout, rsiz, data2(*,*), 1
	     end
          'A': begin
		rdwrt, 'W', lun, bytout, rsiz, index(idset), 1
		rdwrt, 'W', lun, bytout, rsiz, data(idset), 1
	     end
	endcase

	idset_infil = idset_infil + 1
	if (idset_infil le ndset_arr-1) then begin
	    del = int2secarr(roadmap(ss_dset_arr(idset_infil)), roadmap(ss_dset_arr(idset_infil-1)))	;compare next time with time just written out
	    if (del le 0.1) then idset_infil = idset_infil + 1	;same times - skip that one
	end
    end until (idset_infil ge ndset_arr)
end
;
ihxa_scan = 0
if (get_nbytes(hxa_scan) gt 10) then begin
    dorbit = (orbit_times.orb_en_day - orbit_times.orb_st_day)*86400 + $
                                (orbit_times.orb_en_time - orbit_times.orb_st_time)/1000.
    ;
    tvec = int2secarr(hxa_scan, [orbit_times.orb_st_time, orbit_times.orb_st_day])
    ss = where((tvec ge 0) and (tvec lt dorbit))
    ;
    ihxa_scan = 0
    if (ss(0) ne -1) then begin
	ihxa_scan = n_elements(ss)
	hxa_scan0 = hxa_scan(ss)
    end
end
;
case strupcase(strmid(prefix,0,1)) of
    'B': wrtBCSMap, lun, fpoint, bytout, fhead, rsiz, dp_sync_out, ndp_sync_out
    'H': wrtHXTMap, lun, fpoint, bytout, fhead, rsiz  
    'S': wrtSXTMap, lun, fpoint, bytout, fhead, rsiz
    'W': wrtWBSMap, lun, fpoint, bytout, fhead, rsiz  
    'C': wrtCBAMap, lun, fpoint, bytout, fhead, rsiz
    'A': wrtATTMap, lun, fpoint, bytout, fhead, rsiz, hxa_scan0, ihxa_scan
endcase
;
if (keyword_set(orbit_times)) then begin
    fhead.orb_st_time = orbit_times.orb_st_time
    fhead.orb_st_day  = orbit_times.orb_st_day
    fhead.orb_en_time = orbit_times.orb_en_time
    fhead.orb_en_day  = orbit_times.orb_en_day
end
fhead.refverno = progverno
fhead.ref2verno = prog2verno
wrt1p_fh, lun, fpoint, fhead, rsiz, progName, progVerNo, fileid_out, prefix, instr
;
free_lun, lun
end
