pro rd_bsd_data,lun_filename,dset_arr,header,rdmap,index,data,channel, $
	nodata=nodata
;+
; NAME:			rd_bsd_data v0.97
;
; PURPOSE:		read bsd data block + return in structure
;
; CALLING SEQUENCE:     rd_bsd_header
;			rd_bsd_rdmap
;			rd_bsd_data
;
; INPUTS:		lun_filename - Lun/or filename.
;			header - header structure - see rd_bsd_header
;			rdmap  - roadmap structure - see rd_bsd_rdmap
;			dset_arr - dataset array. 
;
; OPTIONAL INPUTS:	channels - array of channel numbers (*) default.
;			/nodata  - if this flag then do not extract data
;				(useful if you only want the index struct).
;
; OUTPUTS:		index  - data index structure.
;			data   - data structure. 
;			 For structure definitions see file bsd_struct.pro
;
; OPTIONAL OUTPUTS:  	none
;
; RESTRICTIONS:		Filename must match that in calls to rd_bsd_header
;			and rd_bsd_rdmap
;
; PROCEDURE:		read record at a time, insert into structure, create
;			wavelength array.
;
; MODIFICATION HISTORY: v0.0  written atp 5/92 from jtm's rd_bsd.pro
;			v0.03 modified to account for uncertainties/internal 
;				time errors atp may92 
;			v0.9  clean up, minor bug fixes (7/7/92)     
;			v0.95 Lun_fixed and nodata keyword atp
;			v0.97 fixed bug with nodata keyword.
;-
bsd_struct
;
siz = size(lun_filename)
vtyp = siz(siz(0) + 1)
;
if (vtyp eq 7) then begin	;passed file name
	get_lun, lun
	openr, lun, lun_filename, /block
endif else begin
	lun = lun_filename
endelse
;
if (n_elements(channel) eq 0) then channel = [1,2,3,4];

nchan = n_elements(channel);

nset  = n_elements(dset_arr);
npts  = header.numchn(channel-1);
npts  = max(npts);
numdat = min(nset,npts);
index = replicate({bsd_r_h},nchan,numdat);
if (not keyword_set(nodata)) then data  = replicate({bsd_data},nchan,numdat);
;/* agreed order was - chan,idset */
temph = {bsd_r_h};

for j=0,nchan-1 do begin
 ichan = channel(j) -1; 
 for i=0, numdat-1 do begin
  idset = dset_arr(i) - 1;
  if (rdmap(idset).exist(ichan) eq 1) then begin 
   point_lun,lun, (rdmap(idset).offset(ichan) - 1) *64L;
   readu,lun,temph;
   index(j,i) = temph;
   if (not keyword_set(nodata)) then begin
    nrec = ((index(j,i).nbinssp/16)+((index(j,i).nbinssp mod 16) gt 0))
    tdat = fltarr((nrec)*16);
    readu, lun, tdat;
    data(j,i).bins = tdat(0:(index(j,i).nbinssp-1));
    readu, lun, tdat;
    data(j,i).counts = tdat(0:(index(j,i).nbinssp-1));
    ;
    ; if index.istat is 1 then read the uncertainties
    ;
    if (index(j,i).istat eq 1) then begin
      readu, lun, tdat;
      data(j,i).error = tdat(0:(index(j,i).nbinssp-1));
      endif
    ;
    ; generate wavelengths
    ;
    data(j,i).wave = data(j,i).bins*index(j,i).dw + $
                               index(j,i).wo;
    endif
   endif
  endfor
endfor
;
; subtract 1900 from time arrays if in that format.
;
if (index(0,0).time(6) gt 1000) then index(*,*).time(6) = index(*,*).time(6)-1900
;
;
;
if (vtyp eq 7) then begin
	close,lun
	free_lun, lun
	endif	

end
