;+
; NAME:
;	MK_BSC_DATA
; PURPOSE:
;	to produce a BSC data structure from BDA data given control information
;       in the variable BSC_INDEX
; CALLING SEQUENCE:
;	MK_BSC_DATA,BDA_INDEX,BDA_DATA,BSC_INDEX,BSC_DATA,DP_SYNC=DP_SYNC
; INPUTS:
;       BDA_INDEX    - BDA index structure
;	BDA_DATA     - BDA data in [4,*] array (counts)
;       BSC_INDEX    - BSC_INDEX created by MKBSA
;       
; OUTPUTS:
;       BSC_DATA     - BSC data structure 
;       BSC_INDEX    - updated BSC_INDEX
; KEYWORDS:
;       DP_SYNC      - input DP_SYNC array needed for dead-time correction
;       ERRCAL       - compute data uncertainties
;       NOVALID      - don't extract out valid bins (i.e. sin(theta) ne 0)
; PROCEDURE:
;                      Uses information in BSC_INDEX to determine
;                      how BDA spectral data will be processed.
; RESTRICTIONS:
;                      It is assumed that the user has already read the
;                      BDA data into main memory 
;                      (e.g. with YODAT)
; HISTORY:
;                    Written Sept. 1992 by D. Zarro (Applied Research Corp).
;                    Modified Dec'92, modified for new BSC data structures
;                    Modif Apr'93, added check that DP_SYNC and data times overlap
;-

pro mk_bsc_data,bda_index,bda_data,bsc_index,bsc_data,$
          dp_sync=dp_sync,errcal=errcal,novalid=novalid

on_error,1

;
;-- Check problem inputs
;

if (n_elements(bda_index) eq 0) or (n_elements(bda_data) eq 0) then begin
 message,'usage --> MK_BSC_DATA,BDA_INDEX,BDA_DATA,BSC_INDEX,BSC_DATA,[DP_SYNC=DP_SYNC]'
endif
ndsets=(size(bda_data))(2)
if ndsets ne (size(bda_index))(1) then message,'incompatible BDA index and data array sizes'

;
;-- User forgot to run MKBSA
;

if (not bsc_check(bsc_index)) then message,'run MKBSA first'

;
;-- If deadtime correction requested, then compute the correction factors
;   now for all channels. Use same method for each channel.
;

check=where(bsc_index.bsc.deadtime_ans gt 0,count)
if (count gt 0) then begin
 dtype=bsc_index(check(0)).bsc.deadtime_ans
 dt_interp=bsc_index(check(0)).bsc.dp_sync_dpf
 dt_fac=bcs_dtfac(bda_index,dp_sync,dtype,interp=dt_interp) 
endif

;
;-- Accumulate spectra
;

bcs_accum,bda_index,bda_data,bsc_index,bsc_data,dt_fac=dt_fac

;
;-- Curvature correction
;

bsc_xcorr,bsc_index,bsc_data

;
;-- Flux calibration
;

bsc_fluxcal,bsc_index,bsc_data

;
;-- Wavelength calibration
;

bsc_wavecal,bsc_index,bsc_data

;
;-- Uncertainty calculation
;

if keyword_set(errcal) then bsc_errcal,bsc_index,bsc_data

;
;-- extract valid wavelength bins
;

if not keyword_set(novalid) then begin
 bsc_valid,bsc_index,bsc_data,nindex,ndata,novalid=novalid
 bsc_index=nindex
 bsc_data=ndata
endif

return & end

 
