;+
; NAME:
;       ADJUST_DATE_OBS
;
; PURPOSE:
;       This function returns a structure of two string elements containing the
;       adjusted date-obs and time-obs for a given C1, C2, or C3 image header.
;       c2_time_offsets.dat file is used to get the time offset using first 
;       value extend, interpolation, or last value extend. It then calculates
;       the corrected date-obs and time-obs and returns them.
;
; CATEGORY:
;       LASCO DATA_ANAL
;
; CALLING SEQUENCE:
;       adj = adjust_date_obs(hdr) 
;
; INPUTS:
;       hdr: A C1, C2, or C3 image header
;
; OPTIONAL INPUTS:
;       verbose: print diagnostic messages.
;                adj = adjust_date_obs(hdr,/verbose)
;
; OUTPUTS:
;      A two element structure of DATE and TIME containing the adjusted
;      DATE_OBS and TIME_OBS.
;
; Example:
;     hdr.DATE_OBS = '1998/01/01'
;     hdr.TIME_OBS = '00:10:11.181'
;
;     adj = adjust_date_obs(hdr)
;
;     adj.DATE =     '1998/01/01'
;     adj.TIME =     '00:13:06.590'
;     
;
; MODIFICATION HISTORY:
;       Written by:     Ed Esfandiari, Feb 1999
;	 7/24/00, nbr - Add SCCS version, reduce_history commmon block
;	11. 6.01, nbr - Use OPENR instead of OPENU
;	11.30.01, nbr - Change fnm for windows SSW compatibility
;	 7. 5.02, nbr - Fix SCCS version syntax
;       09/22/05  Ed Esfandiari -  Check hhdr and if time_obs='' assume level-1
;                                  file and do not adjust date_time (already adjusted). 
;
;
;	@(#)adjust_date_obs.pro	1.9, 09/13/10 - NRL LASCO IDL LIBRARY
;
;-

function get_offset,utime,verbose

  ;fnm= 'c2_time_offsets.dat'
  ;fnm= GETENV('NRL_LIB')+'/lasco/data_anal/data/'+'c2_time_offsets.dat'
  fnm= GETENV('NRL_LIB')+'/idl/data_anal/data/'+'c2_time_offsets.dat'

  OPENR,lu,fnm,/GET_LUN
  mjd=0L
  time=0L
  xpos= 0.0
  moved= 0.0
  offset= 0.0
  tmp= ''

  sutime= strtrim(string(utime.mjd)+string(utime.time,'(i8.8)'),2)
  found= -1

  READF,lu,tmp
  READF,lu,tmp
  READF,lu,mjd,time,xpos,moved,offset
  mjd1= mjd & time1= time & offset1= offset
  smjd= strtrim(string(mjd)+string(time,'(i8.8)'),2)
  if(smjd ge sutime) then found= -2 
  if(found eq -2) then begin
    mjd2=mjd1 & time2=time1 & offset2= offset1
    offset= offset2
    READF,lu,mjd1,time1,xpos,moved,offset1
  end

  while (not eof(lu) and found eq -1) do begin
    READF,lu,mjd,time,xpos,moved,offset 
    mjd2=mjd1 & time2=time1 & offset2= offset1
    mjd1= mjd & time1= time & offset1= offset 
    smjd= strtrim(string(mjd)+string(time,'(i8.8)'),2)
    if(smjd ge sutime) then found= 1 
  end

  CLOSE,lu
  FREE_LUN,lu

  if(KEYWORD_SET(verbose)) then begin
    print,''
    print,'Calculate offset for: ',utime.mjd,utime.time
    print,'Following times and offsets will be used:'
    print,mjd2,time2,offset2
    print,mjd1,time1,offset1
    print,''
  end

  if(found lt 0) then begin
    if(found eq -2) then begin
      if(KEYWORD_SET(verbose)) then begin
        print,'Header date is earlier than c2_time_offset.dat dates. Will use the'
        print,'first offset from c2_time_offset.dat instead of extrapolating.'
      end
    endif else begin
      if(KEYWORD_SET(verbose)) then begin
        print,'Header date is beyond c2_time_offset.dat dates. Will use the last'
        print,'offset from c2_time_offset.dat instead of extrapolating.'
      end
    endelse
  endif else begin
    if(offset1 ne offset2) then begin
      ;interpolate
      if(KEYWORD_SET(verbose)) then print,'interpolating ...'
      days= mjd1 - mjd2
      x2= long(time2)
      x1= long(days*86400000L + time1)
      s= double((offset1 - offset2)/(x1 - x2))
      days1= utime.mjd - mjd2
      x= long(days1*86400000L + utime.time)
      offset= s * (x - x2) + offset2
    end
  endelse

  if(KEYWORD_SET(verbose)) then  print,'Calculated offset (sec)= ',offset

  return,offset

end



function adjust_date_obs,hdr,verbose=verbose

COMMON reduce_history, cmnver, prev_a, prev_hdr, zblocks0

version= '@(#)adjust_date_obs.pro	1.9, 09/13/10' ; LASCO IDL LIBRARY
;

cmnver = strmid(version,4,strlen(version))

  adj= {date:'', time:''}

; Note: the CRPIX1 should be overwritten by the x_val (i.e. 512.28 for C2)??

  shdr= hdr
  IF (DATATYPE(shdr) NE 'STC') THEN shdr=LASCO_FITSHDR2STRUCT(hdr) 
  tel= strupcase(STRTRIM(shdr.detector,2))
  date= shdr.date_obs
  time= STRTRIM(shdr.time_obs,2)

  ; Level-1 headers (and higher) are already adjusted for date and time. For these files,
  ; Unlike level-0.5 files, shdr.date_obs is set to 'yyyy-mm-ddThh:mm:ss.msc' and shdr.date 
  ; is set to ''. So check the shdr.time and if it is blank assume it is a level-1 hdr which
  ; does not need time correction:


  IF (time EQ '') THEN BEGIN
    adj.date= STRMID(date,0,4)+'/'+STRMID(date,5,2)+'/'+STRMID(date,8,2) ;=>yyyy/mm/dd
    adj.time= STRMID(date,11,12)
    IF (KEYWORD_SET(verbose)) THEN PRINT,'level-1 hdr input: '+date +' not adjusted' 
    return, adj    
  ENDIF


  ; Get number of sec/pix for this image to calculate the offset from
  ; the orbit files (xx= ~60 arcmin):
  ;xx= ......
  ;spp= 86400.0 / (xx * 5) 
  ;Assume sun moves by 1 degree (60 arcmin) per day, for now, so xx= 60:
  ;spp= 86400.0 / (60.0 * 5)
  ;offset= (sun_cen.xcen - x_val) * spp  ; offset in seconds

  utctime= STR2UTC(date+' '+time)
  offset= get_offset(utctime,verbose)

  ; Subtrct the offset (changed to msec) from the date/time_obs after
  ; converting them to utc format:

  utctime.time= utctime.time - (offset*1000.0)
  if(utctime.time lt 0L) then begin
    utctime.mjd= utctime.mjd - 1L
    utctime.time= utctime.time + 86400000L
  end
  if(utctime.time ge 86400000L) then begin
    utctime.mjd= utctime.mjd + 1L
    utctime.time= utctime.time - 86400000L
  end


  ; Change from utc format to string of form "yyyy-mm-ddThh:mm:ss.mmmZ"
  ; and pick up new date/time:

  stime= utc2str(utctime)
  new_date= strmid(stime,0,4)+'/'+strmid(stime,5,2)+'/'+strmid(stime,8,2)
  new_time= strmid(stime,11,12)

  if(KEYWORD_SET(verbose)) then begin
    print,''
    print,'Camera= ',tel
    print,'Original date/time: ',shdr.date_obs,' ',shdr.time_obs 
    print,'Adjusted date/time: ',new_date,' ',new_time
    print,''
  end

  adj.date= new_date
  adj.time= new_time 

  return,adj

end
