; Copyright (c) 1998-2018 A.P. Hitchcock  All rights reserved
;+
;NAME: AX_STACK_EXPAND
;
;
;LAST CHANGED: ----------------------------------- 	01 Jun 2018

; PURPOSE:
;	This procedure reads a stack, generates a user-defined canvas larger than the stack
; places the stack in the canvas, and writes out the expanded stack.
;
; CATEGORY:
;	    Runs stand alone or inside aXis2000.
;
; CALLING SEQUENCE:  	AX_STACK_EXPAND, GROUP = GROUP
;
; INPUTS:NONE
;
; KEYWORDS:
;	GROUP - group_ID if called from another program  (AXIS_ID)
;
; OUTPUTS:
;	*.(dat,ncb) written with original stack centered in expanded canvas
;
; COMMON BLOCKS:
; AXIS_COM    standard set of common blocks
; bsif_com
; stack_process_com
; COMMON volume_data, image_stack
;
; MODIFICATION HISTORY:
; (01-Jul-18 aph) first version
;-

PRO AX_STACK_EXPAND, group = group
@axis_com
@bsif_com
@stack_process_com
COMMON volume_data, image_stack
on_error,2

;  --------- read in stack

file = pickfile2(/READ, FILTER='*.ncb', /LPATH, DEFPATH=defpath)
stack_rb, file

t =  size(image_stack)
n_cols = t(1)
n_rows = t(2)
n_ev = t(3)

; -----------  generate expanded canvas
n_x_pixel = (x_stop - x_start)/n_cols
n_y_pixel = (y_stop - y_start)/n_rows			; work in pixel not um units
print, 'Pixel sizes - X: ', n_x_pixel, '   Y: ', n_y_pixel

axis_log, 'Define size of expanded canvas'					; if different pixel sizes in X and Y, use stacks~change mesh

exp_fac = 1		; expansion distance - default to 1 um larger

if keyword_set(group) then begin
	x_min = get_num(prompt='Expand: X-min (-1)',val=x_start - exp_fac, group = axis_id)
	x_max = get_num(prompt='Expand: X-max (+1)',val=x_stop  + exp_fac, group = axis_id)
	y_min = get_num(prompt='Expand: Y-min (-1)',val=y_start - exp_fac, group = axis_id)
	y_max = get_num(prompt='Expand: Y-max (+1)',val=y_stop  + exp_fac, group = axis_id)
endif else begin
	x_min = get_num(prompt='Expand: X-min (-1)',val=x_start - exp_fac)
	x_max = get_num(prompt='Expand: X-max (+1)',val=x_stop  + exp_fac)
	y_min = get_num(prompt='Expand: Y-min (-1)',val=y_start - exp_fac)
	y_max = get_num(prompt='Expand: Y-max (+1)',val=y_stop  + exp_fac)
endelse
; print, 'expanded X-range: ', x_min,' to ', x_max
; print, 'expanded Y-range: ', y_min,' to ', y_max

; ---------------  construct new image_stack array
nx = fix((x_max - x_min)/n_x_pixel)
ny = fix((y_max - y_min)/n_y_pixel)
base = min(image_stack)
; print, nx, ny, n_ev

expand_stack = fltarr(nx,ny,n_ev)
for i = 0, n_ev-1 do begin
	expand_stack(*,*,i) = min(image_stack(*,*,i))
endfor

; -------- identify starting pixel indices
nxs = fix((x_start - x_min)/n_x_pixel)
nys = fix((y_start - y_min)/n_y_pixel)

expand_stack(nxs:nxs+n_cols-1, nys:nys+n_rows-1,*) = image_stack

image_stack  = expand_stack
; ---------- write expanded stack ----------------
t = ax_name(file)
ex_file = t(0) + t(1) + 'e'
stack_wb,ex_file

RETURN
END
