; Copyright (c) 1995, ALS SpectroMicroscopy Facility, er, jdd
;
;file: spectra.pro
;
;+
;   fct SPECTRA, struc[ , /INFO, /NORM, LABELS=[xlabel, ylabel'], _extra=e]
;       -- extract spectral data into 1D structure {d:, dn:, x:, xl:, dl:} or
;          2D structure {d:, dn:, x:, y:, xl:, yl:, dl:, dnl:}
;          normalization subfield (dn:) is created unless no I0 exists or
;          /NORM option is invoked
;-

function SPECTRA, s, INFO=info, NORM=norm, LABELS=lbl, _extra=e
;===========================================
; extract spectral data from labview data file structure
; return 1D or 2D structure: {d:, x:, dl:, xl:} or {d:, x:, y:, dl;, xl:, yl:}
on_error,2
nv=s.summary(3)		;# independent variables 
;nd=s.summary(4) 	;# data columns
;nn=s.summary(5) 	;# norm columns
nc=s.summary(1)		;# cycles
nr=s.summary(6)          ;# spectral regions

if nr eq 0 then begin
   if keyword_set(info) then print, 'No spectral regions'
   return, 0
endif
xlabel='x'
dlabel=s.fname
if keyword_set(lbl) then begin
   xlabel=lbl(0)
endif
xarr=s.x
data=s.y

;normalization
if not keyword_set(norm) then norm=0 
hasvf=(s.PhiDescr(5) eq 2)
;norm=1
;if keyword_set(non) then norm=0
;if n_elements(s.yn) eq 0 then norm=0
if hasvf eq 0 then norm=-1
if norm ge 0 then begin
   nonzero=where( s.yn ne 0. )
   numzero=n_elements(s.yn)-n_elements(nonzero)
   if numzero gt 0 then print, numzero,' zero normalization values'
   if nonzero(0) eq -1 then begin
      print, 'normalization bypassed; all zeroes'
      norm=-1 
   endif
   if norm then begin
      data(nonzero)=data(nonzero)/s.yn(nonzero)
      dlabel=dlabel+'-norm'
      print, 'normalization performed.'
   endif
endif

;2D y-array
sz=size(s.y)
if sz(0) eq 2 then begin	;2-D
   yarr=reform( s.indvars(0,*) )	;hv	
   ylabel=s.indnames(0)
   if keyword_set(lbl) then ylabel=lbl(1)
   if norm eq 0 then $
      spec={d:data, dn:s.yn, x:xarr, y:yarr, $
            dl:dlabel, dnl:'i0', xl:xlabel, yl:ylabel }$
   else $
      spec={d:data, x:xarr, y:yarr, dl:dlabel, xl:xlabel, yl:ylabel }
endif else begin	;1-D
   if norm eq 0 then $
      spec={d:data, dn:s.yn, x:xarr, $
            dl:dlabel, dnl:'i0', xl:xlabel } $
   else $
       spec={d:data, x:xarr, dl:dlabel, xl:xlabel }
endelse

if keyword_set(info) then helps, spec
return, spec
end
