; Copyright (c) 2004-2016 A.P. Hitchcock  All rights reserved
;+
;NAME:
;	TIF_TO_NCB
;
;LAST CHANGED: ----------------------------------- 21-Dec-2016
;
; PURPOSE:
;	This procedure converts a series of 16-bit unsigned tif files (*.tif) image files
; into a binary stack file. If the images have different sizes (as occurs in ptyhogrphy reconstructions)
; the output is truncated to the size of the smallest image
;
; CATEGORY:
;	AXIS: stack analysis
;
; CALLING SEQUENCE:
;	RESULT = TIF_TO_NCB(group_leader=axis_ID)
;
; INPUTS:
;	none
;
; KEYWORD PARAMETERS:
;	FILE	- path & file to define folder where tif files are located
;			- NB still have to select all tif files
;	GROUP_LEADER - identification of caller for modal control
;
; OUTPUTS:
;    FILE.NCB - stack binary file
;
; COMMON BLOCKS:
;   @AXIS_COM - set of common blocks for AXIS
;	stack_process_com
;	bsif_com
;	volume_data
;
; RESTRICTIONS:
;	caveat emptor
;
; MODIFICATION HISTORY:
; (02-May-14 aph) first developed (adapted from JPG_TO_NCB)
; (30-Jun-14 aph) correct header
; (29-May-16 aph) add sort to multiple file list to compensate for Windows error
;                 which places the last name in a filename list first (biblical ?)
; (21-Dec-16 aph) reduce all images to size of smallest image
;-

function tif_to_ncb, file=file, group_leader=group_leader
@stack_process_com
@axis_com
@bsif_com
COMMON volume_data, image_stack

on_error,2

; -------- start with list of files ------
; listfile = PICKFILE2(/Read, FILTER='*.sl', $
;     title = 'Select JPG stack list file', /LPATH, DEFPATH=defpath)
; stack_readlist, listfile, filename_list
; -------- use GET_PATH to establish correct file names
; -------- check if file exists - this handles subdirectory changes
;file1 = filename_list(0)
;New_Path = get_path(file1)
;if New_Path EQ '' then return,0	; let user cancel
;n_files = n_elements(filename_list)
;for i = 0, n_files-1 do begin
;	t = ax_name(strtrim(filename_list(i),2))
;	filename_list(i) = New_Path + t(1) + '.' + t(2)
;endfor
; ------ read all filenames in a folder

if keyword_Set(file) then begin
	t = ax_name(file)
	cd, t(0)
endif
tmpf = DIALOG_PICKFILE(/Read, FILTER='*.tif',/multiple, $
     title = 'Select tif files in the stack') ; , /LPATH, DEFPATH=defpath)
filename_list = tmpf(sort(tmpf))
n_files = n_elements(filename_list)
if tmpf(0) NE filename_list(0) then begin
	axis_log, 'Filename list sorted'
;	for i = 0, n_files-1 do print, filename_list(i)
endif

; - set defpath to same folder that tif files came from
t = ax_name(tmpf(0))
DefPath = t(0)
cd, DefPath
; ---- get energies ---
energy =fltarr(n_files)
energy_list_file = PICKFILE2(/Read, FILTER='*.txt', title = 'Select file with energy list', DEFPATH=defpath)
if strlen(energy_list_file) EQ 0 then begin
	axis_log, 'no energy file - use index integer'
endif else begin
; -------- read in energies:  format % Energies  & 825  &834.5  &   1550
	energy=text_read(energy_list_file)
endelse

; --------- read each tif file and generate a stack
print, 'First file to process is ',filename_list(0)
; --- read first file to define stack dimensions
tmp = img_load(file = filename_list(0),/tif, /values, /silent)
nx = n_elements(tmp.x)
ny = n_elements(tmp.y)
npts = n_files
; print, npts, nx, ny
x = tmp.x
y = tmp.y
image_stack = fltarr(nx,ny,npts)
filename_ev_msec_list = strarr(npts)

; -------- read in images of stack and store in volume_data array
widget_control,hourglass=1
FOR i = 0,n_files-1 DO BEGIN
	tmp = img_load(file = filename_list(i),/tif, /values, /silent)

; suggest to resize image_stack whenever del_x or del_y is < 0 - ie size to the smallest tif
		t = ax_name(filename_list(i))
		fileshort = t(1)
		axis_log, fileshort + '   nx = '+ strtrim(string(n_elements(tmp.x))) + '    ny ' +   strtrim(string(n_elements(tmp.y)))
; ------ check that size is identical or larger; if not reduce nx, or ny
	if n_elements(tmp.x) NE nx OR n_elements(tmp.y) NE ny then begin
		del_x = n_elements(tmp.x) - nx
		del_y =  n_elements(tmp.y) - ny
;		print, fileshort,' differs in size by (del-X, del-Y) ', del_x,'  ',del_y
		if del_x LT 0 then nx = n_elements(tmp.x)
		if del_y LT 0 then ny = n_elements(tmp.y)
; ----- reduce size of image_stack
	t_stack = image_stack(0:nx-1, 0:ny-1, *)
	image_stack = t_stack
;	help, image_stack
	endif

GOTO, skip_complex
; ---- this is way too complicated !! - too many conditionals, can never be sure if all 8 cases work
;      and I want in the end to truncate to the minimum in any case
; ------ STRATEGY HERE: check that size is identical; if not pad or truncate to original size
	if n_elements(tmp.x) NE nx OR n_elements(tmp.y) NE ny then begin
		t = ax_name(filename_list(i))
		del_x = n_elements(tmp.x) - nx
		del_y =  n_elements(tmp.y) - ny
		print, t(1),' differs in size by (del-X, del-Y) ', del_x,'  ',del_y
		t_a = fltarr(nx, ny)
		print, 'size of t_a ', nx, ny
		if  del_x GT 0 then begin		; strip off excess columns
			if del_y GE 0 then t_a = tmp.d(0:nx-1, 0:ny-1) else begin
				t_a(0:nx-1,0:n_elements(tmp.y)-1) = tmp.d
				for i = n_elements(tmp.y), n_elements(tmp.y)+del_y do t_a(*,i) = 0.
			endelse
			tmp={t:'2d', x:x, y:y, d:t_a, xl:tmp.xl, dl: tmp.dl, e:tmp.e}
		endif else begin
			if del_x LT 0 then begin	; pad with 0's
				if del_y GE 0 then t_a(0:n_elements(tmp.x)-1,0:ny-1) = tmp.d else begin
					t_a(0:nx-1,0:n_elements(tmp.y)-1) = tmp.d
					for i = n_elements(tmp.y), n_elements(tmp.y)+del_y do t_a(*,i) = 0
				endelse
			for i = n_elements(tmp.x), n_elements(tmp.x)+del_x do t_a(i,*) = 0.
			tmp={t:'2d', x:x, y:y, d:t_a, xl:tmp.xl, dl: tmp.dl, e:tmp.e}
			endif
		endelse
		if  del_y GT 0 then begin		; strip off excess rows
			if del_x GE 0 then t_a = tmp.d(0:nx-1,0:ny-1)  else begin
				t_a(0:n_elements(tmp.x)-1,0:ny-1) = tmp.d
				for i = n_elements(tmp.x), nx-1 do t_a(*,i) = 0.
			endelse
			tmp={t:'2d', x:x, y:y, d:t_a, xl:tmp.xl, dl: tmp.dl, e:tmp.e}
		endif else begin
			if del_y LT 0 then begin	; pad with 0's
				if del_x GE 0 then t_a(0:nx-1,0:n_elements(tmp.y)-1) = tmp.d else begin
					t_a(0:n_elements(tmp.x)-1,0:n_elements(tmp.y)-1) = tmp.d
					for i = n_elements(tmp.x), nx-1 do t_a(*,i) = 0.
				endelse
				for i = n_elements(tmp.y), n_elements(tmp.y)+del_y do t_a(*,i) = 0.
				tmp={t:'2d', x:x, y:y, d:t_a, xl:tmp.xl, dl: tmp.dl, e:tmp.e}
			endif
		endelse
	endif

skip_complex:

	if  n_tags(tmp) NE 0 THEN BEGIN
		tmp.e = energy(i)
;		splot2d, tmp
		image_stack(*,*,i) = tmp.d(0:nx-1, 0:ny-1)
		dwell = sd.dwell_time
		filename_ev_msec_list(i) = 'tif ' + $
			    string(energy(i), format = '(F7.2)') + '  ' +  string(dwell, format='(F5.2)')
		t = ax_name(filename_list(i))
		axis_log, t(1)
	endif
ENDFOR

filename = pickfile2(filter = '*.ncb', title = 'binary stack file')
if strlen(filename) GT 0 then begin
	t = ax_name(filename)
	filename = t(0) + t(1) +'.ncb'
endif else return, filename

widget_control,hourglass=1
; define parameters needed for stack write out
x_start = x(0) & x_stop = x(nx-1)
y_start = y(0) & y_stop = y(ny-1)
ev = energy
stack_wb, filename
widget_control,hourglass=0
t = ax_name(filename)
; axis_log, 'Binary stack of tif files written as ' + t(1)
return, filename

END


