;+
; Project     : SOHO-CDS
;
; Name        : FIND_CAMPAIGN
;
; Purpose     : Shell around LIST_CAMPAIGN to fix the annoying
;               problem caused by LIST_CAMPAIGN often not returning
;               valid campaign entries that have start/stop times on
;               day boundaries.
;
; Category    : planning
;
; Syntax      : FIND_CAMPAIGN,CMP,
;
; Inputs      : TSTART/TSTOP = start/stop times to search, any format
;
; Opt. Inputs : None
;
; Outputs     : CAMPAIGNS = campaign structure array
;               NFOUND = number of campaigns found
;
; History     : Written 20 May 1997, D. Zarro, ARC/GSFC
;               Modified 14 April 2004, Zarro (L-3Com/GSFC) - filter out
;               blank observers
;
; Contact     : dzarro@solar.stanford.edu
;-

pro find_campaign,tstart,tstop,campaigns,nfound,err=err

err='' & nfound=0
delvarx,campaigns

dstart=anytim2utc(tstart,err=err)
if err ne '' then begin
 message,err,/cont & return
endif

dstop=anytim2utc(tstop,err=err)
if err ne '' then begin
 message,err,/cont & return
endif

;-- strip off useless time part and search +/- day to ensure
;   finding all pertinent campaigns.

dstart.time=0 & dstop.time=0
single_day=0
if dstop.mjd le dstart.mjd then begin
 dstop.mjd=dstart.mjd+1
 single_day=1
endif

estart=anytim2tai(dstart)
estop=anytim2tai(dstop) 
one_minute=60l
if single_day then estop=estop-one_minute

dstart.mjd=dstart.mjd-1
dstop.mjd=dstop.mjd+1

list_campaign,dstart,dstop,dcamp,dfound,err=err

if err ne '' then begin
 message,err,/cont & return
endif

if dfound eq 0 then begin
 nfound=0 & return
endif

;-- now extract and sort

cstart=dcamp.date_obs
cstop=dcamp.date_end

clook=where( ((cstart ge estart) and (cstart le estop)) or $
             ((cstop ge estart) and (cstop le estop)) or $
             ((cstart le estart) and (cstop ge estop)), nfound)

if nfound gt 0 then begin
 campaigns=dcamp(clook)
 cmp_no=campaigns.cmp_no
 sorder = uniq([cmp_no],sort([cmp_no]))
 campaigns=campaigns(sorder)
 nfound=n_elements(campaigns)

;-- filter out blank observers
 
 chk=where( strtrim(campaigns.observer,2) ne '',bfound)
 if (bfound gt 0) then begin
  if (bfound ne nfound) then begin
   campaigns=campaigns[chk]
   nfound=bfound
  endif
 endif else begin
  nfound=0 & delvarx,campaigns
 endelse

endif


return & end
