;+
; Project     : SOHO - CDS
;
; Name        : GET_CDS_PLAN
;
; Purpose     : Get nearest CDS detailed plan given a TIME, STUDY_ID, 
;               STUDYVAR and (optional) PROG_NUM.
;
; Category    : planning
;
; Explanation : 
;
; Syntax      : IDL>plan=get_cds_plan(time,study_id,studvar,prog_num=prog_num)
;
; Inputs      : TIME = plan start time
;               STUDY_ID, STUDYVAR = usual suspects
;
; Opt. Inputs : None
;
; Outputs     : PLAN = sought after plan
;               ERR = error string
;
; Opt. Outputs: None
;
; Keywords    : PROG_NUM = program number. If given, will search on this first
;               SEARCH_WINDOW= search window in seconds [def = 2hr]
;
; Common      : None
;
; Restrictions: None
;
; Side effects: None
;
; History     : Version 1,  4-Aug-1997,  D.M. Zarro.  Written
;
; Contact     : DZARRO@SOLAR.STANFORD.EDU
;-

function get_cds_plan,time,study_id,studyvar,prog_num=prog_num,$
         search_window=search_window,err=err

err=''
serr='Syntax --> plan=get_cds_plan(time,study_id,studyvar,[prog_num=prog_num]'
perr='No matching plans found'

;-- check inputs

stime=anytim2tai(time,err=err)
if err ne '' then begin
 message,serr,/cont
 return,-1
endif

if (not exist(study_id)) or (not exist(studyvar)) then begin
 err='Undefined STUDY_ID/STUDYVAR'
 message,serr,/cont
 return,-1
endif

;-- now search

day_sec=3600.d*2.d
if not exist(search_window) then swidth=day_sec else swidth=double(search_window)
list_detail,stime-swidth,stime+swidth,plans,nobs,err=err
if nobs eq 0 then begin
 err=perr 
 message,err,/cont
 return,-1
endif

;-- start with PROG_NUM

if exist(prog_num) and tag_exist(plans,'PROG_NUM') then begin
 if prog_num gt 0 then begin
  clook=where(prog_num eq plans.prog_num,count)
  if count eq 1 then return,plans(clook)
 endif
endif

;-- next check closest matching STUDY_ID/STUDYVAR

err=''
study=get_cds_study(study_id,studyvar,err=err)
if err ne '' then begin
 message,err,/cont
 return,-1
endif

clook=where((study_id eq plans.study_id) and (studyvar eq plans.studyvar),count)
if count gt 0 then begin
 eplans=plans(clook)
 ediff=(stime-eplans.date_obs)
 elook=where(ediff eq min(ediff),ecount)
 return,eplans(elook)
endif

err=perr
message,err,/cont
return,-1

end


