pro wrtCBAMap, lun, fpoint, bytout, fhead, rsiz, init_fhead=init_fhead
;
;
;
ref_struct, ref, dpos1, dpos2, sxtos1, sxtos2, sxtos3, stat1
sxtos3 = sxtos3 - 16	;correct for already having removed 16 bytes of time
;
if (keyword_set(init_fhead)) then gen_struct, file_header=fhead
gen_struct, gen_index=gen_index
cba_struct, cba_data=cba, cba_roadmap=cba_roadmap, cba_version=cba_version
;
qdebug = 0
print, 'Now Inside WRTCBAMAP.PRO
;
rsiz = ref.CBA_Fil_Rec_Siz
maxsamps = 0
nDataSets = 0
;
ibyt_stop = bytout
fpoint.map_section = bytout
;
first_time = 0          ;TODO - should not be necessary
first_day = 0
last_time = 0
last_day = 0
;
ibyt = fpoint.data_section
while (ibyt lt ibyt_stop) do begin
    ibyt0 = ibyt
    if (qdebug) then print, 'Dset = ', ndatasets+1, '  ibyt = ', ibyt0

    rdwrt, 'R', lun, ibyt, rsiz, Gen_Index, 1
    rdwrt, 'R', lun, ibyt, rsiz, cba, 1

    cba_roadmap.byteSkip		= ibyt0
    cba_roadmap.time			= gen_index.time
    cba_roadmap.day			= gen_index.day
    cba_roadmap.dp_mode			= gen_index.dp_mode
    cba_roadmap.dp_rate			= gen_index.dp_rate

    cba_roadmap.sxt_ffi	= get_cba(cba,sxtos3, 16)*long(256*256.) + get_cba(cba,sxtos3, 32)*long(256) + get_cba(cba,sxtos3, 48)
    cba_roadmap.sxt_pfi	= get_cba(cba,sxtos3, 18)*long(256*256.) + get_cba(cba,sxtos3, 34)*long(256) + get_cba(cba,sxtos3, 50)

    cba_roadmap.sxt_pow_stat		= gen_index.sxt_pow_stat
    cba_roadmap.bcs_pow_stat		= gen_index.bcs_pow_stat
    cba_roadmap.wbs_pow_stat		= gen_index.wbs_pow_stat
    cba_roadmap.hxt_pow_stat		= gen_index.hxt_pow_stat

    rdwrt, 'W', lun, bytout, rsiz, cba_Roadmap, 1

    if (qdebug) then print, 'Time = ', gen_index.time
    if (qdebug) then print, 'GEN_Index.nIndexByte =', GEN_Index.nIndexByte

    ibyt = ibyt0 + GEN_Index.nIndexByte + Gen_Index.nDataByte
    nDataSets = nDataSets + 1

    day  = cba_roadmap.day
    time  = cba_roadmap.time
    if (nDataSets eq 1) then begin
	first_day  = day
	first_time = time
	last_day   = day
	last_time  = time
    end else begin
        s_day = 86400
        v = (day-first_day)*s_day + (time-first_time)/1000
        if (v lt 0) then begin  ;found an earlier start time/day
            first_day  = day
            first_time = time
        end
        v = (day-last_day)*s_day + (time-last_time)/1000
        if (v gt 0) then begin  ;found a later end time/day
            last_day  = day
            last_time = time
        end
    end

    maxsamps = max([maxSamps, gen_index.nDataByte])
end

fpoint.TotBytes		= bytout
fpoint.roadmap_version  = cba_version.roadmap

fhead.first_Time	= first_time
fhead.first_Day		= first_day
fhead.last_Time		= last_time
fhead.last_Day		= last_day

fhead.nDataSets		= nDataSets
fhead.maxSamps		= maxSamps

end
