; Copyright (c) 1998-2016  A.P. Hitchcock  All rights reserved
;+
;NAME:
;  STACK_ADD
;
;LAST CHANGED: ----------------------------------- 09 Mar 2016
;
; PURPOSE:
;	This procedure adds two stacks presumed to be on same E and spatial scales
;
; CATEGORY:
;	stack processing; stand alone operation
;
; CALLING SEQUENCE:
;	STACK_ADD, FILE
;
; INPUTS:
; 	FILE	name of the output file
;
; KEYWORDS: none
;
; OUTPUTS: 	writes summed stack as *.ncb
;
; COMMON BLOCKS:
; AXIS_COM	standard set of common blocks
; stack_process_com
; BSIF_com
; volume_data, image_stack
;
; SIDE EFFECTS:
;
; RESTRICTIONS: none
;
; MODIFICATION HISTORY:
; (29-Aug-04 aph) first version
; (17-oct-04 aph) provide weighting coefficients
; (17-Sep-08 aph) replace analcom with stack_process_com
; (21-Aug-21 aph) check for different numbers of images (energies) ==> possible erros (esp. XMCD !)
; (09 Mar 16 aph) add Ratio to another stack
;-

PRO stack_add, ratio=ratio
@axis_com
@stack_process_com
COMMON volume_data, image_stack
@bsif_com

on_error,2

fltr = '*.ncb'

file1 = pickfile2(/READ, TITLE = 'STACK 1', FILTER=fltr, /LPATH, DEFPATH=defpath)
if strlen(file1) LE 0 THEN return  ; bail-out if no filename

stack_rb, file1
stack1 = image_stack
t1 = size(image_stack)
axis_log, 'stack-1: x,y ' + string(t1(1))+' '+ string(t1(2)) + ' #-images = ' + string(t1(3))

file2 = pickfile2(/READ, TITLE = 'STACK 2', FILTER=fltr, /LPATH, DEFPATH=defpath)
if strlen(file2) LE 0 THEN return  ; bail-out if no filename

stack_rb, file2
; check dimensions - if not the same, flag and abort
t2 = size(image_stack)
axis_log, 'stack-2: x,y ' + string(t2(1))+' '+ string(t2(2)) + ' #-images = ' + string(t2(3))
if t1(3) NE t2(3) then begin
	test=dialog_message('Different numbers of images, Do  you want to continue  ? ',/question, /cancel)
	if test EQ 'Cancel' OR test EQ 'No' then return
endif
if t1(1) EQ t2(1) AND t1(2) EQ t2(2) then begin

; ---------------- RATIO stacks
	if keyword_set(ratio) then 	begin
		image_stack =   stack1 / image_stack

; ---------------- ADD stacks
   	endif else begin
   		if widget_info(/active) EQ 1 then $		; assume if a widget is going, it is axis
	   		weight = get_num(Prompt = 'scale for second stack (-1 = subtract)', val = 1.0, group=AXIS_ID) $
	   			else weight = get_num(Prompt = 'scale for second stack (-1 = subtract)', val = 1.0)
   		image_stack =   stack1 + weight * image_stack
   	endelse

	file = pickfile2(/READ, TITLE = 'Output Stack name', FILTER=fltr, /LPATH, DEFPATH=defpath)
	if strlen(file) NE 0 then begin
		t = ax_name(file)
		filename = string(t(0)) + string(t(1)) + '.ncb'
		stack_wb, filename
	endif
endif else begin
	axis_log, 'Stacks have different (x,y) dimensions. Procedure aborted'
	widget_control, Bad_ID=Bad_ID, Uprompt, SET_VALUE=text
	ax_wait,/off		; turn off hourglass (sometimes sticks on)
	return
endelse
ax_wait,/off		; turn off hourglass (sometimes sticks on)
return
end

