; Copyright (c) 2004-2009 A.P. Hitchcock  All rights reserved
;+
;NAME:
;	BMP_TO_NCB
;
;LAST CHANGED: ----------------------------------- 30-Jul-09
;
; PURPOSE:
;	This procedure converts a series of JPEG (*.jpg) image files
; into a binary stack file. The BMP files are those listed in a '*.sl' file
;
; CATEGORY:
;	AXIS: stack analysis
;
; CALLING SEQUENCE:
;	RESULT = JPG_TO_NCB(group_leader=axis_ID)
;
; INPUTS:
;	none
;
; KEYWORD PARAMETERS:
;	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:
; (26-Feb-06 aph) first developed (adapted from BMP_TO_NCB)
; (30-jul-09 aph) changed analcom to stack_process_com (update to stack_process)
;-

function jpg_to_ncb, group_leader=group_leader
@stack_process_com
@axis_com
@bsif_com
COMMON volume_data, image_stack

on_error,2

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
;
; -------------- check back for user to see if filename list is valid---------
print, 'First file to process is ',filename_list(0)
; --- read first file to define stack dimensions
tmp = img_load(file = filename_list(0),/jpg, /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)
energy = fltarr(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),/jpg, /values, /silent)
	if  n_tags(tmp) NE 0 THEN BEGIN
;		splot2d, tmp
		image_stack(*,*,i) = tmp.d
		energy(i) = tmp.e
		dwell = sd.dwell_time
		filename_ev_msec_list(i) = 'jpg ' + $
			    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
axis_log, 'Binary stack of JPG files written as ' + filename
return, filename

END
