; Copyright (c) 2007-2008 A.P. Hitchcock  All rights reserved
;+
;NAME:
;	READ_PEEM3
;
;LAST CHANGED: ----------------------------------- 07-Aug-08 (aph)
;
;PURPOSE:
;	This function reads in ALS PEEM3 format image and stores in
; an axis 2d structre
;
;CATEGORY:
;	STAND ALONE: utility
;
;CALLING SEQUENCE:
;	Result = READ_PEEM3([file=file, nof=nof,bin=bin, scale=scale, _extra=e])
;
;CALLED FROM AXIS:
;	Read->Images->AXIS (and in many analysis routines)
;
;INPUTS: none. All input parameters are passed as keywords.
;
;KEYWORDS:
;	FILE 	- filename to read
;	NOF   	- no nme filter
;	BIN		- factor to bin by
;	SCALE	- scale in nm/pixel prior to binning
;	_EXTRA - passed on parameters
;
;OUTPUTS:
;	RESULT = AXIS 2d structure
;
;COMMON BLOCKS:
;	@AXIS_COM	standard set of common blocks
;
;
;MODIFICATION HISTORY:
; (21-Jan-07 aph) first version
; (10-mar-07 sgu) modify for change in ring current key word (beamcurrent => ringcurrent)
; (12-mar-07 aph) generalize to either key word
; (12-sep-07 aph) allow stand alone operation; change to use Scholl faster approach (single read of image)
; (07-Aug-08 aph) remove ring current normalization if ring current less than 1 mA or absent
;-

Function READ_PEEM3,  file=file, bin=bin, scale=scale, group=group, NOF=NOF, _extra=e
@axis_com
on_error,2

IF NOT keyword_set(file) then begin
	fltr='*.P3B'
	if keyword_set(nof) then fltr='*'
	file = pickfile2(/READ,  title= 'ALS PEEM-3 image', FILTER=fltr, /LPATH, DEFPATH=defpath)
ENDIF

s = ''
if file EQ '' THEN RETURN, s  ; bail-out if no filename
check = findfile(file)		 ; bail-out if non-existent file
if strlen(check(0)) EQ 0 then begin
	axis_log, 'Cannot find ' + file
	return, s
endif

; Time the read-in process - evalaute Scholl improvements
;time1 = systime(/seconds)

tmp_data = Read_P3B(file, tags=tags, dimx=nx, dimy=ny)

;help, tags,/struct

; ------ kluge to remve crap from left side of image -- used from Jan-07 to Sep-07  ---------------
;if tags.dimx GT 1000 then begin
;	orig_dimx = tags.dimx
;	n_skip=3
;	tags.dimx = orig_dimx - n_skip+1
;	tmp_data = tmp_data(n_skip-1:orig_dimx-1,*)
;endif

; ------ use Scholl ax_cimage procedure to remve crap from left side of image -  from Sep-07  ---
tmp_data = ax_cimage(tmp_data)


if NOT keyword_set(scale) then begin		; explicit keyword overrides use of pix_size (axis_com) to store pixel size
	if keyword_set(pix_siz) EQ 0 then begin
		if not keyword_set(group) then scale = get_num(prompt='image scale (um/pixel)', val=pix_siz) else $
				scale = get_num(prompt='image scale (um/pixel)', val=pix_siz, group = group)
	endif
	scale = pix_siz
	if scale EQ 0 then scale = 1.0
endif
x= scale*findgen(nx)
y= scale*findgen(ny)
energy = tags.xvalue			; changed from monoenegy on advice of Scholl Sep-07
tag_list = tag_names(tags)

yl = 'y'
norm = 1.
; ---------------------- normalize to the ring current if selected & possible
if norm_flag EQ 1 then begin
	i_ring = 0.
	for i = 1, n_elements(tag_list)-1 do begin
	;	print, tag_list(i)
		if tag_list(i) EQ 'RINGCURRENT' then i_ring = tags.ringcurrent
		if tag_list(i) EQ 'BEAMCURRENT' then i_ring = tags.beamcurrent
	endfor
	if i_ring GT 1.0 then begin
		norm = 400./i_ring
		yl = 'y     N-400 uA'
	endif
endif


t = ax_name(file)
dl = 'P3B '+ t(1)
xl = 'x  E = '+ string(energy, format="(f8.3)")+' dwell = ' $
       + string(tags.exposuretime, format="(i5)") + ' (ms)'
tmp = {t:'2d', x: x, y:y, d:tmp_data*norm, xl:xl, E:energy, yl:yl, dl:dl}

if keyword_set(bin) then begin
	n_cols=n_elements(tmp.x)  &  n_rows=n_elements(tmp.y)
	x_start = tmp.x(0)  &  x_stop = tmp.x(n_elements(tmp.x)-1)
	y_start = tmp.y(0)  &  y_stop = tmp.y(n_elements(tmp.y)-1)
	image_data = tmp.d
    if (float(n_cols)/float(bin))-fix(n_cols/bin) GT 0 $
		OR (float(n_rows)/float(bin))-fix(n_rows/bin) then begin
        nct =fix(n_cols/bin)*bin  &  nrt = fix(n_rows/bin)*bin
        xtra_c = n_cols - nct + 1
        xtra_r = n_rows - nrt + 1
	    x_stop = x_stop*float(nct)/float(n_cols)  ; correct axis length for truncation
        y_stop = y_stop*float(nrt)/float(n_rows)
;        print, 'truncate image to ', fix(nct), fix(nrt)
        tmp2 = tmp.d                      ;force size to integer mutiple of bin
        image_data = intarr(nct,nrt)
		image_data = tmp2(0:n_cols-xtra_c,0:n_rows-xtra_r)
    endif
    n_cols = fix(n_cols/bin)
    n_rows = fix(n_rows/bin)
 ;   print, 'bin image ', fix(bin), ' times,  to ',n_cols,'  x', n_rows
    bin_data = fltarr(n_cols,n_rows)
    bin_data = rebin(image_data,n_cols,n_rows)
    x = fltarr(n_cols)  & y = fltarr(n_rows)
    x = x_start + findgen(n_cols)/(x_stop - x_start)
    y = y_start + findgen(n_rows)/(y_stop - y_start)
	dl = tmp.dl + ' bin' + STRCOMPRESS(string(fix(bin)))
	tmp = {t:'2d', d: bin_data, E: tmp.E, x: x, y: y, xl: tmp.xl, yl: tmp.yl, dl: dl}
endif

; time2 = systime(/seconds)
; print, 'elapsed time (s) = ', time2-time1

return, tmp
end