; Copyright (c) 1998-2010 A.P. Hitchcock  All rights reserved
;+
;NAME:
;		READ_CLS_SGM_XRF.PRO
;
;LAST CHANGED: ----------------------------------- 	21-Jun-2010
;
; PURPOSE:
;	This function reads CLS SGM XRF-excitation maps from ascii files
;
; CATEGORY:
;	stand alone - . can execute outside of aXis2000
;	data read in from aXis200 as read~XRF~(APS, CLS-SGM)
;
; CALLING SEQUENCE:
;	Result = READ_CLS_SGM_XRF(file=file, filter=filter, map_num=map_num, normalize=normalize, $
;                      group=group, store=store, silent=silent, verbose = verbose, $
;                      type = type, XRF_max=XRF_max, XRF_bin = XRF_bin)
;
; KEYWORDS:
;	FILE:  name of file (*.pgm)
;	FILTER: extension (default is '*.pgm')
;	GROUP: group_ID of parent
;	NORMALIZE: if set, modify intensities to standard ring current (value of normalize parameter
;	SILENT: if set, do not print tracking comments
;	STORE: if set, write *.axb (aXis2000 format) binary file of image
;	VERBOSE:  if set print all of the header
;	XRF_bin:  factor to bin XRF spectra
;	XRF_max:  upper energy of XRf spectrum to keep
;
; OUTPUTS:
;	returns maps as a standard aXis2000 2d array with defined x, and y axes, etc
;
; COMMON BLOCKS:
;	AXIS_COM	standard set of common blocks
;
; MODIFICATION HISTORY:
; (21-Jun-10 aph) first version
;-

function READ_CLS_SGM_XRF, file=file, filter=filter, map_num=map_num, normalize=normalize, $
                      group=group, store=store, silent=silent, verbose = verbose, $
                      XRF_max=XRF_max, XRF_bin = XRF_bin
@axis_com
on_error,2
if n_elements(file) eq 0 then begin  ;popup file dialog box
   if not keyword_set(filter) then filter='*_spectra.dat'
   file=PICKFILE2(/Read, FILTER=filter, /LPATH, DEFPATH=defpath)
endif

;	strip out name of excitation energy file
pos = strpos(file,'_spectra')
file2 = strmid(file,0,pos)
file = file2+'.dat'
t = ax_name(file)
fileshort = t(1)
if not keyword_set(silent) then  axis_log, 'Reading CLS SGM XRF map ' + fileshort

;read data
;let user choose options for storage and/or display of 1 or more maps
; transfer to files and/or aXis2000  buffers

; ----------------- read CLS SGM XRF maps  -----------


openr, unit, file, /get_lun
; read parameter file --------
a='#'
; ------ skip to start of excitation energy list
while strmid(a,0,1) EQ '#' DO BEGIN
	readf, unit, a
	if keyword_set(verbose) then axis_log, 'header: ' + a
endwhile
npts=0
cls_E = fltarr(1)
while NOT EOF(unit)DO BEGIN
	readf, unit,a
	cls_E(npts) = strmid(a,3,12)
	cls_E=[cls_E,0.]
	npts=npts+1
endwhile
cls_E=cls_E[0:n_elements(cls_E)-2]
npts = n_elements(cls_E)
if not keyword_set(silent) then axis_log,' # of CLS photon energies = ' + string(npts)

; --------- change name to that of the set of XRF spectra ----------
t = ax_name(file)
file2=  t(0) + t(1) + '_spectra.' + t(2)
; ---- read array of XRF spectra
openr, unit, file2, /get_lun
; ---------- skip header
a='#'
while strmid(a,0,1) EQ '#' DO BEGIN
	readf, unit, a
	if keyword_set(verbose) then axis_log, 'header: ' + a
endwhile

; ---------- set upper energy of XRF spectrum--------------------------------
xrf_len = 4096			; change if bin XRF spectra
xrf_step = 1.67			; ste size of XRF spectrum for 4095 points (CLS-SGM)

if not keyword_set(XRF_max) then XRF_max = xrf_len*xrf_step
if keyword_set(group) then $
	xrf_max = get_num(prompt='maximum XRF energy (eV) ? ', val = XRF_max, group = aXis_ID) $
else $
	xrf_max = get_num(prompt='maximum XRF energy (eV) ? ', val = XRF_max)
XRF_len = XRF_max/xrf_step
spec = intarr(npts, XRF_len)
on_ioerror, continue
ax_wait
for i = 0, npts-1 do begin
	if not keyword_set(silent) then $
	     axis_log, 'XRF spectrum at ' + string(cls_E(i),format='(F7.2," eV")')
	readf, unit,a
	for j = 0, xrf_len-1 do begin
		comma = strpos(a,',')
		spec(i,j)=fix(strmid(a,0,comma))
		a = strmid(a,comma+1)
	endfor
endfor
continue:
ax_wait, /off
close,unit & free_lun, unit

; ------- optional binnig of the XRF spectra
if not keyword_set(XRF_bin) then XRF_bin = 2
if keyword_set(group) then $
	XRF_bin = get_num(prompt='bin XRF spectra by ', val = XRF_bin, group = aXis_ID) $
else $
	XRF_bin = get_num(prompt='bin XRF spectra by  ', val = XRF_bin)
if XRF_bin GT 1 then begin
	XRF_bin = fix(XRF_bin)
; ---- determine closest integer multiple of XRF_bin that is smaller than existing XRF_len
	xrf_len2 = fix(xrf_len/XRF_bin)
; --- truncate spec so integer rebin will work
	spec = spec(*,0:XRF_bin*xrf_len2-1)
; --- bin using IDL rebin function
	spec = rebin(spec,npts, xrf_len2)
	xrf_len=xrf_len2
endif
; ---------- set up for writing axis2000 format file
n_cols = npts
n_rows = xrf_len
image_data = float(spec)
; -------- turn off scale bar
scale_bar = 0

; -----------------  generate an axis2000 format structure from header & image
x_step = CLS_E(1)-CLS_E(0)  & x_start = CLS_E(0)		; assumes equal spaced
y_step = 1.67*XRF_bin  & y_start = 0.
x = findgen(n_cols)  & y = findgen(n_rows)
x = CLS_E
y = y_start + y*y_step
energy = 0.
dwell = 1000.
xl = string(FORMAT='("x (pixels)     E = ",f8.3," eV     dwell = ",f6.1," ms")', $
  energy,  dwell)
yl = 'CLS XRF excitation map'
dl = fileshort + ' bin ' + strtrim(string(fix(XRF_bin)),2)


; ------------
s={t:'2d', d:image_data, x:x, y:y, e: energy, xl:xl, yl: yl, dl:dl}

if not keyword_set(silent) then axis_log, 'read CLS XRF excitation map from ' + fileshort

if keyword_set(store) then begin
	t=axb_save(s)

endif
return, s
end