; Copyright (c) 1998-2005 A.P. Hitchcock  All rights reserved
;+
;NAME:
;		PEM_LOAD
;
;LAST CHANGED: ----------------------------------- 28-May-05 (aph)
;
; PURPOSE:
;	This function reads an ALS-PEEM 2 NEXAFS format file
; It assumes col(1) = Energy (eV)  and col(3) = signal
;
; CATEGORY: spectral input
; called from AXIS~READ~ALS-PEEM
;
; CALLING SEQUENCE:
;	Result = PEM_LOAD(file=file, filter=filter, NOF=nof, print_source = print_source, $
;             ring_normalize=ring_normalize,  _extra=e)
;
; INPUTS:
;	All input parameters are passed as keywords.
;
; KEYWORDS:
;	FILE:	filename
;	FILTER:	optional user selectable filter (default = '*.'
;	NOF:	no filter (*.*)
;	PRINT_SOURCE:	if set to 1; print input file as it is read
;   RING_NORMALIZE  divide by the ring current if it exists
;	_EXTRA_E:	forward other parameters
;
; OUTPUTS: none
;
; COMMON BLOCKS:
;	AXIS_COM	standard set of common blocks
;
; COMMENTS:
;	In Dec-04 found prob lems with 'apparent non-linearity' in ALS PEEM energy scales
;   In May-05 realized there had been a file format change sometime in fall 2003
;   which removed the header line from the *.dat files written by PEEM-2
;   This meant the energy assigned to the image file was one higher (i.e. the n+1 energy
;   was assigned to the n image). This, combined with use of non-linearly spaced energies,
;   is the likely cause of the  'apparent non-linearity'.

; MODIFICATION HISTORY:
; ( 9-aug-97 aph) broke out of spectral; TYPE defined
; (21-jan-98 aph) added s.dn component to 1d structure to be axis-compatible
; (20-feb-98 aph) set-up to read 2-col only data
; ( 6-mar-98 aph) read *.txt - 2 column ascii files
; ( 7-jun-98 aph) corrected read *.txt ('un' case) to get all data points
; (10-jul-98 aph) retired "*.spc" nomenclature - use *.txt extension
; (13-May-99 aph) set up for multicolumn, skip header reading
; (15-May-99 aph) adapt spc_load to get ALS-PEEM 2 format files
; (25-jun-99 aph) use only fileshort
; ( 7-jul-99 aph) FREE_LUN as well as close
; (29-dec-00 aph) set filter to '*.' ; standard header; add file
; (14-jan-01 aph) set filter to '*.*' since '*.' EXCLUDES files of *. character !!
; (12-aug-01 aph) add title to pickfile dialog
; (12-may-02 aph) correct header name format
; (28-may-05 aph) adapt to 3 different ALS PEEM spectral file formats
;                 add ring current normalization option
;-

Function pem_load, file=file, filter=filter, NOF=nof, print_source = print_source, $
                   ring_normalize=ring_normalize, _extra=e
 on_error,2
 @axis_com

if not keyword_set(file) then begin
	 fltr='*.*'
	 if keyword_set(nof) then fltr='*.*'
	 if keyword_set(filter) then fltr=filter
	 file = pickfile2(/READ, FILTER=fltr, /LPATH, DEFPATH=defpath, title = 'Select PEEM energy file')
endif
 if strlen(file) GT 0 THEN BEGIN  ; bail-out if no filename
	openr, iunit, file, /get_lun
	test = ''

; ------ Pre-2002 user-select options removed at some point ! ------------
;	wid_exist = WIDGET_INFO(/active)
;	print, 'Select: 0 to skip line, 1 to define columns'
;	if wid_exist EQ 1 then  WIDGET_CONTROL, Uprompt, SET_VALUE=test + ' Select: 0=skip line, 1=define columns'
;	t=get_num(Prompt='action',Val=1)
;	if t EQ 0 then goto, reread
;	print, 'Select columns for x, y'
;	cx = 1  & cy = 3
;		cx=get_num(Prompt='x-col',Val=cx)
;		cy=get_num(Prompt='y-col',Val=cy)
;	ncol = cy & if cx GT cy then ncol = cx


   if not keyword_set(ring_normalize) and dialog_message(/question,title = 'ALS PEEM2 spectral read-in' $
   	    ,  'Normalize to 400 mA ring current ?') EQ 'Yes' then ring_normalize = 1

	read_data:		; ------ ASSUMED DATA FILE FORMAT -----------------------
	cx = 1 			;  ALS PEEM-2  Energy in column 1
	cy = 3 			;  ALS PEEM-2  Signal in column 3
	cr = 4				;  ALS PEEM-2  Ring current in column 4
	ncol = 4		;  ALS PEEM-2  4 column file format
	data_line = fltarr(ncol)
	on_ioerror, end_of_file

	np = 0 & x=fltarr(1) & y=fltarr(1)
	ring_data = 'Yes'		; asume ring current data is in file; change if pre-2001
	WHILE NOT EOF(iunit) DO BEGIN
		readf, iunit, test		; check if the line starts with 'Energy' (identifies pre-01 files)
		if keyword_set(print_source) then print, test
		if test EQ '' then begin
			axis_log, '2002-03 era data: 1 blank line, 4 columns'
			goto, skip_a_line	; adapt for files with 1 blank line at top (2002, 2003)
		endif
		if strmid(test,0,6) NE 'Energy' then begin
			reads, test, data_line
			x(np) = data_line(cx-1)
			y(np) = data_line(cy-1)
			if keyword_set(ring_normalize) and ring_data EQ 'Yes' $
			    then y(np) = y(np)/(data_line(cr-1)/400.)	; normalize to 400 mA ring current
		 	x = [x,1]	&  y = [y,1]
		 	np = np + 1
		endif else begin
			axis_log, 'Pre-2001 data: ascii header, 3 columns (no ring current)'
			data_line = fltarr(3)
			ring_data = 'No'
		endelse
		skip_a_line:
	ENDWHILE
	x = x[0:np-1]
	y = y[0:np-1]

; --  finished reading file
	end_of_file:
	name_bits = ax_name(file)
	fileshort = name_bits(1)
	s={t:'1d', d: y, x: x, xl: 'Energy (eV)', dn:y, dl: fileshort}
    text = strtrim(string(np),2) + ' point ALS PEEM spectral file: ' + file
    axis_log, text
    if keyword_set(ring_normalize) and ring_data EQ 'Yes' then $
        axis_log, 'normalized to 400 mA ring current'
	close, iunit & free_lun, iunit
endif else begin 	; go here if user pushes 'cancel'
    axis_log, 'file name of zero length. Read aborted'
    s=0
endelse
return, s
end