; Copyright (c) 1998-2015 A.P. Hitchcock  All rights reserved
;+
;NAME:
;  STACK_SPLIT
;
;LAST CHANGED: ----------------------------------- 26-Aug-15 (aph)
;
; PURPOSE:
;	This procedure split one stack into several stacks
;
; CATEGORY:
;	stack processing; stand alone operation or from axis2000
;
; CALLING SEQUENCE:
;	STACK_SPLIT, NUMBER=NUMBER
;
; INPUTS: none required
;
; KEYWORDS:
;	NUMBER the number of images in each sub-stack
;
; OUTPUTS:
; 	2 files (*.dat, *.ncb) are written for each sub-stack
;
; COMMON BLOCKS:
; AXIS_COM	standard set of common blocks
; stack_process_com
; BSIF_com
; volume_data, image_stack
;
; RESTRICTIONS: none
;
; MODIFICATION HISTORY:
; (26-Aug-15  jw) first written
; (27-Aug-15 aph) corrected

;-

PRO stack_split, number=number
@axis_com
@stack_process_com
COMMON volume_data, image_stack
@bsif_com

on_error,2

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

file0 = pickfile2(/READ, TITLE = 'STACK', FILTER='*.ncb', /LPATH, DEFPATH=defpath)
if strlen(file0) LE 0 THEN return  ; bail-out if no filename

stack_rb, file0
stack0 = image_stack
t0 = size(image_stack)
axis_log, 'number of images in the input stack = ' + strtrim(string(t0(3)),2)
ev0=ev
filename_list0=filename_list(0:t0(3)-1)
filename_ev_msec_list0 = filename_ev_msec_list(0:t0(3)-1)


; ---------- set the number of images for each stack (Assumed to be EQUAL)

if not keyword_Set(number) then begin

	if widget_info(/active) EQ 0 then $
		stack_images_n = Get_text(PROMPT = 'number of images in each sub-stack', val = stack_images_n) $
			else stack_images_n = Get_text(PROMPT = 'number of images in each sub-stack', $
			                         val = stack_images_n, group = axis_ID)
;get the number of  sub-stacks to extract
	    n_sub = fix(t0(3)/stack_images_n)
endif  else n_sub = number

a = fix(t0(3)/n_sub)

;set the save file path, and give a prefix name for the split stacks

file = pickfile2(/WRITE,LFILE=file0, TITLE = 'Extracted stack filename', FILTER='*.ncb', /LPATH, DEFPATH=defpath)
if strlen(file) EQ 0 then return; bail-out if no filename

  for i = 0, n_sub-1  do begin

	    b= a*i                    ;start image number of stack_i
	    c = a + a*i -1            ;end image number of stack_i

	    print, 'Indices for sub-stack ', strtrim(string(i),2),' ', b, c

	    image_stack = stack0(*,*,b:c)
;		  ta = size(image_stack)
;		  print, 'dimensions of appended stacks: ', ta

	    ev= fltarr(a)
	    ev= ev0(b:c)
	    filename_list = strarr(a)
	    filename_list = filename_list0(b:c)
	    filename_ev_msec_list = strarr(a)
	    filename_ev_msec_list =filename_ev_msec_list0(b:c)

	    ;print, ev
	    ;print, filename_list
	    ;print, filename_ev_msec_list
	    ;print, i

	    ; ---------------- write out stack_i

	    t = ax_name(file)

	    filename = string(t(0)) + string(t(1)) + '_' + strtrim(string(i),2) + '.ncb'
	    stack_wb, filename
		axis_log, 'sub-stack ' + strtrim(string(i),2) + ' saved to ' + filename

    endfor

end

