; Copyright (c) 1998-2015 A.P. Hitchcock  All rights reserved
;+
;NAME:
;	AX_FIX_ROLLOVER
;
;LAST CHANGED: ----------------------------------- 04-jan-15
;
;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:
; for functions:
;	Result = AX_FIX_ROLLOVER()
;
;CALLED FROM AXIS:
;	->Images->Fix rollover

;INPUTS: none
;
;KEYWORDS:
;	ONE		array to which fix_rollover will be applied
;
;OUTPUTS:
;	repaired files are written to disk.
;
;COMMON BLOCKS:
;	@AXIS_COM	standard set of common blocks
;
;MODIFICATION HISTORY:
; (04-Jul-00 aph) first version
; (04-Jan-15 aph) add keyword, one, an option to process 1 file
;-
FUNCTION ax_fix_rollover, one=one

@axis_com
@bsif_com
on_error,2

IF keyword_set(one) then begin
	neg_ind = where(one LT 0, count)
	if count GT 0 then begin
       	one(neg_ind) = one(neg_ind)+ 65535.
	endif
	return, one
ENDIF ELSE BEGIN
; ----- original version (4-Jul-2000) which processed a set of *.nc files
	WIDGET_CONTROL, Uprompt, BAD_ID = BadID, SET_VALUE='pick first file of sequence'
	file1=PICKFILE2(/Read, FILTER='*.nc', /LPATH, DEFPATH=defpath)
	if strlen(file1) GT 0 THEN BEGIN
	 WIDGET_CONTROL, Uprompt, BAD_ID = BadID, SET_VALUE='pick last file of sequence'
	 file2=PICKFILE2(/Read, FILTER='*.nc', /LPATH, DEFPATH=defpath)
	 if strlen(file2) GT 0 THEN BEGIN
	; assumes last 3 numbers before the '.' are a sequence number
		dot = strpos(file1,'.')
		fileroot=strmid(file1, 0, dot-3)
		first = fix(strmid(file1,dot-3,3))
		last  = fix(strmid(file2,dot-3,3))
	; allow any extension by picking up ext from pickfile choice (aph 14-feb-98)
		t = ax_name(file1)
		ext = t(2)
		mask = 1000
		for i = first, last do begin
			WIDGET_CONTROL, /hourglass
			num = strmid(strtrim(string(1000+i),2),1,3)
			file = fileroot+num+'.'+ext
			tmp = read_bnl(file)
			neg_ind = where(tmp.d LT 0, count)
	 		if count GT 0 then begin
		       	tmp.d(neg_ind) = tmp.d(neg_ind)+ 65535.
		      	tmp.d(1,1) = tmp.d(1,1) +1e-6*tmp.d(1,1)   ; kluge to force REAL *,nc file !
	 			tf=sav_nsls(tmp, file=file)
	  			t=ax_name(tf)
	  			WIDGET_CONTROL, Uprompt, BAD_ID = BadID, $
	  			    SET_VALUE='Rollover fixed image written to '+string(t(1)+'.'+t(2))
	  		endif
		endfor
	endif
	endif
	return, 1
ENDELSE

end
