; Copyright (c) 1998-2022 A.P. Hitchcock  All rights reserved
;+
;NAME:
;	AX_FIX_ROLLOVER
;
;LAST CHANGED: ----------------------------------- 08 Jan-2022 (aph)
;
;PURPOSE:
;	This function modifies one or a sequence of *.nc image files
; to replace all values below 0 with (that value + 65,535.)
; This repairs a roll-over issue in conversion of some image files
; typically, those which are read as unsigned integers rather than signed ones
;
;CATEGORY:
;	AXIS: image analysis
;
;CALLING SEQUENCE:
;	Result = AX_FIX_ROLLOVER(ONE=ONE, USER=USER)
;
;CALLED FROM AXIS:
;	->Images->Fix rollover

;INPUTS: none
;
;KEYWORDS:
;	ONE		flag - process current image in aXis2000
;	USER	flag - user defines threshold and offset
;
;OUTPUTS:
;	modified files are written to buffer 0 if ONE or to disk if .NOT. ONE
;
;COMMON BLOCKS:
;	@AXIS_COM	standard set of common blocks
;	@BSIF_COM	for *.nc file read/write (no longer used)
;
;MODIFICATION HISTORY:
; (04-Jul-00 aph) first version
; (04-Jan-15 aph) add keyword, one, an option to process 1 file
; (24-Jun-21 aph) change to use *.axb files; allow user to select multiple files; adapt for roll over by 2pi (phase) - NOT COMPLETED
; (08-Jan-22 aph) allow user to define threshold and offset
;-
FUNCTION ax_fix_rollover, one=one, user=user

@axis_com
@bsif_com
on_error,2

s = 0	; default return ==> did
; --------- set up threshold and offset ---------
	if n_elements(stop1) GT 0 then threshold = stop1 else threshold = -200		; use TOF parameters to (re)-store threshod 7 offset
	if n_elements(stop2) GT 0 then    offset = stop2 else offset = 1256.
	IF keyword_set(user) then begin
	     threshold = get_num(Prompt = 'User defined threshold', Val=threshold, Title='Fix rollover - threshold', group = Axis_ID)
	     offset = get_num(Prompt = 'User defined offset', Val=offset, Title='Fix rollover - offset', group = Axis_ID)
	ENDIF ELSE BEGIN
		threshold = 0
		offset = 65535.
	ENDELSE
	stop1 = threshold
	stop2 = offset
; ----------- fix (2**16) OR user defined roll_over in current image displayed in aXis2000
IF keyword_set(one) then begin
	HANDLE_VALUE, Data(CurBuf), tmp
    IF n_tags(tmp) EQ 0 THEN RETURN, s
    IF tmp.t NE '2d' THEN RETURN, s
     neg_ind = where(tmp.d LT threshold, count)
     IF count GT 0 then begin
      	tmp.d(neg_ind) = tmp.d(neg_ind)+ offset
      	tmp.d(1,1) = tmp.d(1,1) + 1e-6* tmp.d(1,1)   ; kluge to force REAL data
        CurBuf = 0
	   	tmp.dl = tmp.dl + ' FR_U'
	   	Label(CurBuf) = tmp.dl
		HANDLE_VALUE, Data(CurBuf), tmp, /set
		PlotBuf,CurBuf
		s = 1
	 endif
	 if s eq 0 then print, 'Images~Fix rollover: nothing modified'
	 return, s
ENDIF ELSE BEGIN

; ---------------- apply fix rollover to a set of *.axb files, defined by a stack list (*.sl) file
; ----- read stack list
	WIDGET_CONTROL, Uprompt, SET_VALUE= 'Select file-list file'
	list_file = pickfile2(/READ, FILTER='*.sl',/LPATH, DEFPATH=defpath)
	Write_path = Lpath
	IF strlen(list_file) EQ 0 THEN return, s
; ------ read in the *.sl file
	stack_readlist,list_file, filename_list
	if n_elements(filename_list) LE 1 then begin
		axis_log, 'Could not read ' + list_file
		return, s 	; BAIL if no files
	endif
	filename_list_out = strarr(n_elements(filename_list))

	FOR i = 0, n_elements(filename_list)-1 do begin
		WIDGET_CONTROL, /hourglass
		tmp = axb_load(file=filename_list(i), /silent)
		IF n_tags(tmp) EQ 0 THEN RETURN, s
	    IF tmp.t NE '2d' THEN RETURN, s
	    neg_ind = where(tmp.d LT threshold, count)
	    IF count GT 0 then begin
	      	tmp.d(neg_ind) = tmp.d(neg_ind)+ offset
	      	tmp.d(1,1) = tmp.d(1,1) + 1e-6* tmp.d(1,1)   ; kluge to force REAL data
	        CurBuf = 0
		   	tmp.dl = tmp.dl + ' FR_U'
		   	Label(CurBuf) = tmp.dl
			s = 1
		 endif
		HANDLE_VALUE, Data(CurBuf), tmp, /set
		PlotBuf,CurBuf
		 t = ax_name(filename_list(i))
		 filefix= t(0) + 'm_' + t(1) + '.axb'
		 tf=axb_save(tmp, file=filefix, /silent)
		 t = ax_name(filefix)
		 filename_list_out(i)=t(1) + '.axb'
		 print, filename_list_out(i)
	ENDFOR
	; ------ write out stack list file of modified images ----------
	t = ax_name(list_file )
	out_list_file = t(0) + 'm_' + t(1) + '.' + t(2)
	openw,unit, out_list_file,/get_lun
	printf,unit,t(0)
	for i = 0, n_elements(filename_list_out)-1 do begin
		printf,unit, filename_list_out(i)
	endfor
	close,unit & free_lun, unit
	t = ax_name(out_list_file)
	print, 'Stack list file for modified images is ', out_list_file
ENDELSE
RETURN, s



; ------- developed June 2021 for 2pi roll over  but never completed; modified to user-defined  Jan 2022
	IF keyword_set(user) then begin			; user defined low_limit and roll_over increment
		low_limit = -3.124
		roll_over = 6.283 		; 2pi = 6.28318530718
	endif else begin
		low_limit = 0
		roll_over = 65535.
	endelse
	for i = 0, n_elements(filelist)-1 do begin
;		WIDGET_CONTROL, /hourglass
;		num = strmid(strtrim(string(1000+i),2),1,3)
;		file = fileroot+num+'.'+ext
;			tmp = read_bnl(file)		; changed to *.axb files
		tmp = axb_load(file=filelist(i), /silent)
		count = 1
		countall=0
 		WHILE count GT 0  DO begin				; multiple roll-overs can occur !
 			neg_ind = where(tmp.d LT low_limit, count)
 			if count GT 0 then begin
 				countall = countall + count
		       	tmp.d(neg_ind) = float(tmp.d(neg_ind)) + roll_over
;	 	     	tmp.d(1,1) = tmp.d(1,1) +1e-6*tmp.d(1,1)   ; kluge to force REAL *,nc file !
	 	    endif
  		ENDWHILE
  		print, filelist(i), ' fixed ', countall, ' roll overs'

		tf=axb_save(tmp, file=filelist(i), /silent, /overwrite)	; OVERWRITE input file
		t=ax_name(tf)
;		WIDGET_CONTROL, Uprompt, BAD_ID = BadID, $
;		    SET_VALUE='Rollover fixed image ' + string(t(1) + '.' + t(2))
	endfor
	return, s

END
