; Copyright (c) 1998-2013 A.P. Hitchcock  All rights reserved
;+
;NAME:
;	READ_NSRRC_SPEM.PRO
;
;LAST CHANGED: ----------------------------------- 28-Jul-13
;
;PURPOSE:
;	This reads SPEM data from an NSRRC data file (extension: *,pic, *.ric)
; and returns it as an aXis2000 format structure
;
;CATEGORY:
;	STAND ALONE: utilities
;
;CALLING SEQUENCE:
;	Result = RD_SPEM(file, NOFILTER=nof, _extra=e )
;
;INPUTS:
;	FILE - SPEM data file
;
;KEYWORD PARAMETERS:
;	FILE	 file name
;	GROUP	 name o fgroup calling this program
;	NOFILTER - use *.* as filter
; 	VERBOSE - if set, print additional documentation
;	_EXTRA - pass on other call line parameters
;
; COMMON BLOCKS:
;   AXIS_COM 			set of common blocks for AXIS
;	BSIF_COMMON 		for output stack parameters
;	NSRRC_SPEM_COM   	parameters specific to NSRRC SPEM read-in
;	stack_process_com   for output stack parameters
;	VOLUME_DATA			output stack
;
;MODIFICATION HISTORY:
; (16-Jul-13 aph) first version (start from rd_spem.pro (ALS SPEM)
; (19-Jul-13 aph) write analyser data as a stack
; (22-Jul-13 aph) make work with read_nsrrc_spem_gui
; (28-Jul-13)  leave file name definition and checking for write_ncb
;-

function READ_NSRRC_SPEM, file=file, group=group, NOFILTER=nof, verbose = verbose,  _extra=e

on_error,2
@axis_com
@nsrrc_spem_com
@stack_process_com
COMMON volume_data, image_stack
@bsif_com

; information from Gung Chiang <gcyin@nsrrc.org.tw> on NSRRC SPEM format
; -------------
; in EACH file:   *.ric = stepper (rough)    *.pic = piezo  (fine)
; [SPEM_FILE]    (header, size of 96 bytes at 32 bit system)
; [BODY] 23 (layers)*pixel_num*sizeof(float) (4bytes)
;  1-16 Spectrum
; 17-23 Other layers (transmission, Sample current, Total Yeild, Back scattering, OSA, Time Base, Spare)

; in the header (*.ric) file , there is the following

; typedef struct SPEM_AXIS {
;	int axis_type;   //1:PZT_X,2:PZT_Y,3:STEP_X,4:STEP_Y,5:STEP_Z
;	int port;        //1:PZT_X,2:PZT_Y,1:STEP_X,2:STEP_Y,3:STEP_Z
;	long home_pos;   //unit: nm
;	long cur_pos;    //current position
;	long n_pixel;    //number of pixel in this axis
;	long pixel_size; //unit nm
;	long dwtime;     //unit ms, dwelling time
; }SPEM_AXIS;

; typedef struct SPEM_AXIS_INFO {
;	SPEM_AXIS x_axis, y_axis, z_axis;
;	int  scan_mode; //R_SACN_MODE or P_SCAN_MODE
;	int  scan_type; //AXIS_XY,AXIX_YX,AXIS_XZ,AXIS_YZ
;	int  level_num;
; }SPEM_AXIS_INFO;

if n_elements(file) eq 0 then begin  ;popup file dialog box
   filter ='*.ric; *.pic'
   if keyword_set(nof) then filter='*'
   file=PICKFILE2(/Read, FILTER=filter, /LPATH, DEFPATH=defpath)
endif

s = 0
IF strlen(file) LE 0 THEN return, s
; --------- get header info ----------  SHOULD READ USING IDL's binary file reader
test = 'Yes'
openr,unit,file,/get_lun
axis_type=lonarr(3)
port=lonarr(3)
home_pos = lonarr(3)
cur_pos = lonarr(3)
n_pixel = lonarr(3)
pixel_size = lonarr(3)
dwtime = lonarr(3)
a = long(0) & b = a & c = a & d = a & e = a & f = a & g=a
if keyword_set(verbose) then print, "axis_type, port, home_pos, cur_pos, n_pixel, pixel_size, dwtime"
for i = 0, 2 do begin
	readu,unit,	a, b, c, d, e, f, g
	axis_type(i) = a
	port(i) = b
	home_pos(i) = c
	cur_pos(i) = d
	n_pixel(i) = e
	pixel_size(i) = f
	dwtime(i) = g
	if keyword_set(verbose) then begin
		if i EQ 0 then print, 'X-axis'
		if i EQ 1 then print, 'Y-axis'
		if i EQ 2 then print, 'Z-axis'
		print, axis_type(i), port(i), home_pos(i), cur_pos(i), $
		       n_pixel(i), pixel_size(i), dwtime(i)
	endif
endfor
Scan_mode = long(0)
Scan_type = long(0)
Level_num = long(0)
readu, unit, Scan_mode, Scan_type, Level_num
if keyword_set(verbose) then print, 'Scan mode = ',scan_mode,' Scan type = ', Scan_type, $
       '  Level_num = ', Level_num

; ---------- get the set of images --------
t=ax_name(file) & fileshort = t(1)
print, 'reading NSRRC SPEM image file ' + fileshort
nx = n_pixel(0)
ny = n_pixel(1)
image = fltarr(23, nx, ny)
img = fltarr(nx, ny)
zero = img
s=img

n_img = 16		; 16-channel analyser
image_stack = fltarr(nx,ny,n_img)

for i = 0, 22 do begin
	readu, unit, img
	image(i,*,*) = img
	s = s + img
endfor
close, unit, /all


; -----  prepare and write stack of analyser data
for i = 0, 15 do begin
	img = reform(image(i,*,*))
	image_Stack(*,*, i) = rotate(img,7)
endfor

; -- prepare energy (ev) arrays
ev=findgen(16)
if size(SPEM_ch_0,/type) EQ 0 then begin
	SPEM_ch_0 = 100.
	if size(axis_ID,/type) EQ 0 then $
		SPEM_ch_0 = get_num(prompt='energy of channel 0 (eV) ', val =SPEM_ch_0) $
	else SPEM_ch_0 = get_num(prompt='energy of channel 0 (eV) ', val =SPEM_ch_0, group = axis_ID)
endif
if size(SPEM_KE_step,/type) EQ 0 then begin
	SPEM_KE_step = 0.5
	if size(axis_ID,/type) EQ 0 then $
		SPEM_KE_step = get_num(prompt='step energy (eV) ', val =SPEM_KE_step) $
	else SPEM_KE_step = get_num(prompt='step energy (eV) ', val =SPEM_KE_step, group = axis_ID)
endif

for i =0, 15 do ev(i) = SPEM_ch_0 + eV(i)*SPEM_KE_step
; ----- convert to BE if user selected this option
if size(SPEM_BE,/type) NE 0 then begin
	if SPEM_BE EQ 1 then begin
		for i =0, 15 do begin
			tmp = ev
			ev(i) = SPEM_photon_energy - tmp(i)
		endfor
	endif
endif

; -- prepare arrays for filename_ev_ms list
filename_list = strarr(16)
filename_ev_list = strarr(16)
for i =0, 15 do begin
	filename_list(i) = string(FORMAT="(A,'_',i3)",fileshort,0)
	filename_ev_list(i)=string(FORMAT="(A,'_',i3,' ',F8.3,'  ',F6.2)", fileshort,i, ev(i), dwtime(0))
endfor
filename_ev_msec_list = filename_ev_list

; define parameters needed for stack write out

x=findgen(nx) & y=findgen(ny)
x = x*pixel_size(0)*0.001
y = y*pixel_size(1)*0.001

n_cols = nx  & n_rows = ny
svec = size(image_stack)
x_start = x(0)
x_stop = x(nx-1)
y_start = y(0)
y_stop = y(ny-1)
xstep = (x_stop - x_start)/n_cols
ystep = (y_stop - y_start)/n_rows


;----- write stack as aXis format binary (*.ncb)
; --------- NB error is generated here when run stand alone and use PICKFILE2 and file exists already
;WIDGET_BASE: MODAL top level bases must have a group leader specified.
;Execution halted at:  FILE_OVERWRITE     87 C:\aXis2000\file_overwrite.pro
;                      PICKFILE2          84 C:\aXis2000\pickfile2.pro
;                      READ_NSRRC_SPEM   200 C:\aXis2000\read_nsrrc_spem.pro
;                      BUT_SPEM_OK       181 C:\aXis2000\read_nsrrc_spem_gui.pro
;                      WID_BASE_0_EVENT  232 C:\aXis2000\read_nsrrc_spem_gui.pro
;                      XMANAGER_EVLOOP_STANDARD  478 C:\RSI\IDL63\lib\xmanager.pro
;                      XMANAGER          708 C:\RSI\IDL63\lib\xmanager.pro
;                      BASE_NSRRC_SPEM   356 C:\aXis2000\read_nsrrc_spem_gui.pro
;                      READ_NSRRC_SPEM_GUI  375 C:\aXis2000\read_nsrrc_spem_gui.pro
t=ax_name(file)
outfile=t(0) + ax_sep() + fileshort+'_' + t(2) + '.ncb'
print, 'sending data to write_sb. name ', outfile
; outfile =  pickfile2(file=outfile, /WRITE, FILTER='*.ncb', /LPATH, DEFPATH=defpath)
stack_wb, outfile

; convert sample current image to axis format 2d data structure

xl = 'X (um)  dwell (ms) = ' + string(dwtime(0), format='(F5.1)')
yl = 'NSRRC SPEM sample_current   Y (um)'

channel = 18
; channel = get_num(prompt='return channel # ', val = channel, , group = axis_ID)
s = {t:'2d', x:x, y:y, d: rotate(reform(image(channel,*,*)),7), $
         e: SPEM_photon_energy, xl: xl, yl:yl, dl: fileshort}

return, s

end
