;+
; UVSPTIME.PRO
;
; 1. May have multiple detectors
; 2. Must be 1 x 1 in X and Y dimensions
; 3. Must have more than one data point in repeats (only in this dimension).
;
; T_SEC converts file times into a floating point array of times in
; seconds. Zero times (missing data) are interpolated.
;
; FILE 		: V + exp num + .ext
;		  between header start and end times.
; ERROR 	: 0 if sucessful, 1 if had a problem
;
;
; Detector timing:
;
; Two data channels each w/ two opportunities to send output 
; per minor frame (64 msec).
; 
;-

function uvsptime, file=file, error=error

 ;
 ; Look for the file everywhere.  Another keyword DISK will add to the
 ; search path.
 ;

 opdev = uvspdevck(file=file, error=error)  
 if error then return,0

 error=1					; assume it will fail

 tim = reform(uvsprd(opdev+file, ht)) 		; read in the timing file
 if n_elements(tim) eq 1 then return,0	 	; no good

 if ht(82) gt 1 then return,0			; NX * NY,  1 x 1 only

 sz = size(tim)  &  n_dim = sz(0) 

 if (n_dim gt 2) then return,0			   ; only allowed det + repeats

 ; if two dets then one must be det and the other repeats
 if (n_dim eq 2) and ((ht(60) eq 1) or (ht(81) eq 1)) then return, 0 

 n_pnt = sz(n_dim + 2)				   ; total data points

 ;
 ; Get the number of detectors in each interval
 ;

 twoin_interval1 = ht(51) eq 2         			; det in intvl 1
 twoin_interval2 = ht(52) eq 2         			; det in intvl 2

 ;
 ; If there is some missing data: interpolate from previous 2 values.
 ; First two data points must be non-zero.
 ;

 for i = 0, ht(60)-1 do begin 
    w_miss = where(tim(*,i) eq 0., n_miss) 		; find the missing data
    if n_miss gt 0 then if w_miss(0) eq 0 then return,0 
    if n_miss gt 1 then if w_miss(1) eq 0 then return,0 
   
    if n_miss gt 0 then $				; have some missing
	for i = 0, n_miss-1 do $ 		; for each missing data point
      		tim(w_miss(i),i) = 2*tim(w_miss(i)-1, i) - tim(w_miss(i)-2, i)
 endfor
                  
 for n = 0, ht(60)-1 do begin
   t0 = tim(*,n)   			; one detector at a time.
   t1 = shift(t0,1)                     ; 
   t1(0) = t0(0)
 
   w_over = where((t1-t0) gt 65000L, n_over)  ;6/93 &  n_over = !err
   if n_over gt 0 then begin
      for i_over = 0, n_over-1 do begin
         i = w_over(i_over)    
         t0 = [t0(0:i-1), t0(i:*)+65536L]
      endfor
   endif                                   

   Tim(0,n) = 0.016 * (t0 - t0(0))

 endfor


error=0

return,tim 
end


