; Copyright (c) 1998-2014 A.P. Hitchcock  All rights reserved
;+
;NAME:
;		SPECTRA.PRO
;
;LAST CHANGED: ----------------------------------- 	21 Jul 2014
;
; PURPOSE:
; This function extracts spectral data from LabView (SPEM ?)
;  into a 1D structure {d:, dn:, x:, xl:, dl:}
;  or into a 2D structure {d:, dn:, x:, y:, xl:, yl:, dl:, dnl:}
;  normalization subfield (dn:) is created unless no I0 exists or
;  /NORM option is invoked
;
; CATEGORY:
;	data I/O
;
; CALLING SEQUENCE:
;	Result = SPECTRA, struc[ , /INFO, /NORM, LABELS=[xlabel, ylabel'], _extra=e]
;
; INPUTS:
; This section is for POSITIONAL INPUTS only (not keywords)
;	All input parameters are passed as keywords.
;
; KEYWORDS:
;	INFO	use IDL help routine to display tags of the spec structure created
;	NORM	normalization value
;	LABELS	x, y labels (2-element array)
;	_extra	other parameters passed on
;
; OUTPUTS:
;	No explicit outputs.   A new window is created if necessary
;
; COMMON BLOCKS: none
;
; MODIFICATION HISTORY:
; (21-Dec-00 aph) from er, jdd Copyright (c) 1995, ALS SpectroMicroscopy Facility
; (21-Jul-14 aph) AXIS standard header added
;-

function SPECTRA, s, INFO=info, NORM=norm, LABELS=lbl, _extra=e
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
