;+
; Project     : SDAC
;                   
; Name        : Pointing_Change
;               
; Purpose     : Finds changes in BATSE pointing.
;               
; Category    : CGRO, BATSE, EPHEMERIS
;               
; Explanation : The quicklook orbital files are examined around
;	the input dat  Times are cited for changes in spacecraft
;	position more than the input value given in degrees.  Default
;	is 2 degrees.
;               
; Use         : Pointing_change, out, test_row, first_valid 
;    
; Inputs      : Out- the Batse pointing info array, obtained from
;		the COSSC web pages, encoded as in GET_BATSE_POINTING.
;		Test_row - Out is a fltarr( 5, nrows ), 
;		test_row is the index into out.  Testing for orbits
;		where the cosines in the quick-look archive file
;		are consistent with this spacecraft orientation.
;               
; Opt. Inputs : None
;               
; Outputs     : First_Valid - first midnight of orbit that is consistent
;		with the spacecraft orientation, within 1 degree.  Expressed in
;		seconds from 1-jan-1979.
;
; Opt. Outputs: None
;               
; Keywords    : 
;		OFFSET- Tolerance of pointing error, default is 1 degree.
; Calls       : RESTORE_QLOOK, GRO_POINT
;
; Common      : None
;               
; Restrictions: 
;               
; Side effects: None.
;               
; Prev. Hist  :
;
; Modified    : 
;	Version 1, richard.schwartz@gsfc.nasa.gov, 29-oct-1997.
;	Version 2, richard.schwartz@gsfc.nasa.gov, adjusted search range 2-nov-1997.
;-            
;==============================================================================
pro pointing_change, out, test_row, first_valid, flare_num=flare_num, offset=offset, error=error

common restore_qlook, a1, norb, period, midnights, days, cosines, xrange, yrange, seconds, bytarrays
checkvar, offset, 1.0
error = 0
nout = n_elements(out(0,*))
wuse = test_row + indgen(2) > 0 < (nout-1)
wuse = wuse(uniqo(wuse))
times = long([out(0,wuse(0)),(out(0,wuse))(*)] / 86400.0 ) 
times = minmax( times ) ;first and last day from 1-jan-1979
times = 86400.0d0*(times(0) + indgen(times(1)-times(0) >1)+1)
first_valid = 0.0d0 ;default for failed search
flare_num   = 0L

for i=0,n_elements(times)-1 do begin 

	restore_qlook, time=times(i), orb=1, error=error
	if error then begin
		error = 1
		print,'Cannot find quick-look archive to check pointing for '+  $
		anytim(/yoh,out(0,test_row),/date) 
		
		endif else begin
	v3_true = fltarr( 3, n_elements(midnights))
	all_cos = fltarr(8, n_elements(midnights))
	for j=0,n_elements(midnights) -1 do begin
       		gro_point, out(1:4, test_row), solephut(midnights(j)), cosj
		all_cos(*, j) = cosj
		endfor	
;
; Form a 3 vector in the spacecraft coord system for the test aspect.
;
        v3 = [ total(all_cos([0,1,2,3],*),1), total(all_cos([0,1,4,5],*),1),total(all_cos([0,2,4,6],*),1)]
        v3 = transpose( reform(v3,n_elements(v3)/3,3))/sqrt(16/3.)
        v3_true = v3



;
; Compute the 3 vector obtained from the actual spacecraft pointing encoded
; in the quicklook save file.
;
	v3 = [ total(cosines([0,1,2,3],*),1), total(cosines([0,1,4,5],*),1),total(cosines([0,2,4,6],*),1)]
	v3 = transpose( reform(v3,n_elements(v3)/3,3))/sqrt(16/3.)
;
; Find the difference angle between the test pointing direction and the actual.
;
	diff_angle = !radeg *acos( total( v3 * v3_true,1)<1)

	print,atime(times(i))
	print,diff_angle
	valid = where( diff_angle le offset, nvalid)
 
	if nvalid ge 1 then begin	
		first_valid = days( valid(0))
		return
		endif
	endelse
	endfor
if first_valid eq 0 then begin
	
;
; Examine all pointing directions at interval start plus 1 day
;
	test_time = out(0, test_row) + 86400.0
	gro_point, out(1:4, *), solephut(test_time), all_cos
;
; Form a 3 vector in the spacecraft coord system for all of the test aspect.
;
	v3 = [ total(all_cos([0,1,2,3],*),1), total(all_cos([0,1,4,5],*),1),total(all_cos([0,2,4,6],*),1)]
	v3 = transpose( reform(v3,n_elements(v3)/3,3))/sqrt(16/3.)
	v3_all_pointings = v3

	try_again:
	restore_qlook, time=test_time, orb=1, error=error

;
; Compute the 3 vector obtained from the actual spacecraft pointing encoded
; in the quicklook save file.
;
	wuse = where( total(abs(cosines),1) gt 1, nuse)
	if nuse eq 0 then begin
		test_time = test_time + 86400.0
		goto, try_again
	endif
	cosines = reform(cosines(*,wuse(0)),8,1)
	v3 = [ total(cosines([0,1,2,3],*),1), total(cosines([0,1,4,5],*),1),total(cosines([0,2,4,6],*),1)]
	v3 = reform(v3,1,3)/sqrt(16/3.)
;
; Find the difference angle between the test pointing direction and the actual.
;
	diff_angle = !radeg *acos( ( v3 # v3_all_pointings) <1)
	best = min( diff_angle, imin )
	print,'Could not find a pointing match during interval ', test_row
	print,'Interval starts ~'+atime(/date,out(0,test_row)) +' Interval ends ~'+ $
		atime(/date, out(0,test_row+1))
	print,'Searching whole pointing file for a match.'
	print,'Best pointing match at interval ',imin,' at '+atime(out(0,imin),/date)
	print,'Difference angle in degrees: ',best
;
; Look for flare in time interval
;	
	batse_read_cat
@flare_catalog
	w = where( fldata.start_secs ge (out(0,test_row)+86400.) and $
		fldata.start_secs le (out(0,test_row+1) -86400.), nw)
	if nw < 1 then flare_num = fldata(fix(median(w))).flare_num
		
endif	


end
