;+
; Project     : SOHO-CDS
;
; Name        : UPDATE_IAP
;
; Purpose     : Update Databases from latest IAP files from SOC
;
; Category    : planning
;
; Explanation :
;
; Syntax      : update,date
;
; Examples    :
;
; Inputs      : DATE = date to update [def=current]
;
; Opt. Inputs : None
;
; Outputs     : None
;
; Opt. Outputs:
;
; Keywords    : VERBOSE = print some info
;             : IGNORE = ignore a particular instrument
;             : NOPURGE = don't purge DB's after update
;             : ERR = error messages 
;             : DELETE = delete local IAP files when done
;             : FORWARD = days ahead to update
;             : BACKWARD = days backward to update
;               SOHO     = force SOHO DB to be updated
;
; Common      : None
;
; Restrictions: Unix only (with FTP access to SOC, and write access to DB)
;
; Side effects: None
;
; History     : Written 9 January 1997, D. Zarro, ARC/GSFC
;
; Contact     : dzarro@solar.stanford.edu
;-

pro update_iap,date,verbose=verbose,err=err,$
              nopurge=nopurge,ignore=ignore,delete=delete,soho=soho,$
              _extra=extra,backward=backward,forward=forward,force=force

err=''

if n_elements(date) eq 0 then begin
 get_utc, date, /ecs,/date,/vms
 message,'Updating DB for '+date,/cont
endif
sdate = anytim2utc(date, err=err)
if err ne '' then begin
 message, err, /cont
 return
endif

if keyword_set(soho) then begin
 status=fix_zdbase(/soho,err=err)
 if not status then begin
  message,err,/cont
  return
 endif
endif

;-- lock database to prevent simultaneous updating by other runs

lock_zdbase,'update_iap_lock',/resource,status=status,expire=3600.,$
               lock_file=lock_file,err=err,over=force

if not status then begin
 print,'--> try again later'
 goto,quit
endif


;-- get IAP files

sdate.time=0
if not exist(forward) then forward=0
if not exist(backward) then backward=0

!priv=3
rdate=sdate & count=0
for k=sdate.mjd-long(backward),sdate.mjd+long(forward) do begin
 rdate.mjd=k
 get_latest_iap,rdate,files=files,_extra=extra,verbose=verbose,err=err,count=count,$
         out_dir='/tmp'
 count=n_elements(files)

;-- process each instrument

 if count gt 0 then begin
  for i=0,count-1 do begin
   err=''
   s=read_kap(files(i),err=err,/nopurge,ignore=ignore,/noset,/nores)
  endfor
 endif
 if keyword_set(delete) then rm_file,files
endfor

;-- purge? 

if (1-keyword_set(nopurge)) then begin
 message,'purging DB',/cont
 s=prg_plan() & s=prg_soho_det()
endif

unlock_zdbase,lock_file

quit: if keyword_set(soho) then s=fix_zdbase(/original)

return & end


