;+
; Project     : SOHO-CDS
;
; Name        : CHECK_KAP
;
; Purpose     : Check validity of campaign numbers in IAP file
;
; Category    : planning
;
; Explanation :
;
; Syntax      : CHECK_KAP,FILE
;
; Examples    :
;
; Inputs      : FILE = IAP (or KAP) file to check
;
; Opt. Inputs : None
;
; Outputs     : None
;
; Opt. Outputs:
;
; Keywords    : ALERT = set to send e-mail to instrument planners about 
;                       invalid or missing campaign numbers
;               MISSING = set to alert planners if they forgot to submit IAP
;               NOICAL  = set to not check for Intercalibrations
;
; Common      : None
;
; Restrictions: None
;
; Side effects: None
;
; History     : Written 20 November 1996, D. Zarro, ARC/GSFC
;
; Contact     : dzarro@solar.stanford.edu
;-

pro check_kap,file,err=err,alert=alert,_extra=extra,$
              wmess=wmess,missing=missing,noical=noical

err=''
screen=1
if datatype(wmess) eq 'STR' then begin
 if trim(wmess(0)) eq '' then screen=0
endif

;-- error checks

if datatype(file) ne 'STR' then begin
 message,'syntax: CHECK_KAP,FILE',/cont
 return
endif

chk=loc_file(file,count=count,err=err)
if count eq 0 then goto,quit

;-- look for ZDBASE

if which_inst() eq 'C' then begin
 call_procedure,'find_zdbase',cur_db_type,status=status,/res
 if not status then begin
  err='Campaign database files not found'
  goto,quit
 endif
endif

;-- read IAP/KAP file

error=0
cont=rd_ascii(file,error=error)
if error then begin
 err='Error reading IAP/KAP file'
 goto,quit
endif

;-- user can select to skip particular plan type (e.g. SCI) by setting 
;   /nosci on command line.

if get_caller() eq 'UPDATE_KAP' then message,'checking KAP...',/cont
skip_sci=0 & skip_pro=0
if datatype(extra) eq 'STC' then begin
 skip_keys=strupcase(tag_names(extra))
 find_sci=where(strpos(skip_keys,'NOS') gt -1,pcount)
 skip_sci=(pcount gt 0)
 find_pro=where(strpos(skip_keys,'NOP') gt -1,pcount)
 skip_pro=(pcount gt 0)
endif
if skip_pro and skip_sci then begin
 err='Cannot skip both plan types'
 goto,quit
endif

;-- convert contents to structure

stc=iap2stc(cont,err=err)
scount=n_elements(stc)
if err ne '' then begin
 err='No valid IAP/KAP entries found'
 goto,quit
endif

if skip_pro then keep=where(strpos(stc.type,'SCIPLAN_') gt -1,scount) else $
 if skip_sci then keep=where(strpos(stc.type,'PROGRAM_') gt -1,scount)
if scount eq 0 then begin
 if skip_pro then err='No valid SCIPLAN entries found' else $
  err='No valid PROGRAM entries found' 
 goto,quit
endif
if exist(keep) then stc=stc(keep)

;-- list campaigns relevant to this file

tstart=anytim2utc(stc(0).startime)
tend=anytim2utc(stc(scount-1).endtime)
find_campaign,tstart,tend,cmp,ncmp

if ncmp eq 0 then begin
 err='No campaigns scheduled during IAP/KAP file period'
 goto,quit
endif

;-- pull out participating instruments for each campaign

partic=strarr(ncmp)
for i=0,ncmp-1 do begin
 err=''
 get_campaign,cmp(i).cmp_no,def,err=err
 if err eq '' then begin
  if tag_exist(def,'INSTITUTES') then begin
   if tag_exist(def.institutes,'INSTITUT') then begin
    is_ical=strpos(strupcase(def.cmp_type),'INTERCAL') gt -1
    dont_include=keyword_set(noical) and is_ical
    if (not dont_include) and (def.date_obs gt 0.) then begin
     ilist=strmid(trim(def.institutes.institut),0,3)
     if not exist(clist) then clist=ilist else clist=[clist,ilist]
     partic(i)=trim(arr2str(trim(def.institutes.institut),delim=' '))
    endif
   endif
  endif
 endif
endfor
partic=strupcase(partic)
if exist(clist) then clist=strupcase(clist)

;-- pull out entries for each instrument
;-- user can select to skip particular instrument (e.g. MDI) by setting 
;   /nomdi on command line.
;-- Bail out if instrument is not participating in any campaigns for
;   given day 

do_inst=strupcase(['cds','sumer','mdi','eit','uvcs','lasco','trace'])
nmail=n_elements(do_inst)
zmail='zarro@smmdac.nascom.nasa.gov'
mail_inst=['planner@cds8.nascom.nasa.gov','planner@sumop1.nascom.nasa.gov',$
           'mdiops@mdisas.nascom.nasa.gov','eit@xanado.nascom.nasa.gov',$
           'planner@uvcs14.nascom.nasa.gov','planner@lasco10.nascom.nasa.gov']

ninst=n_elements(do_inst)
today=anytim2utc(stc(0).startime,/date,/vms,/ecs)
fcount=0
if keyword_set(alert) then get_latest_iap,today,files=files,count=fcount,out_dir='/tmp'

blank=strpad('',22,/after)
line='-------------------------------------------------------------------------------'
tail=''
tail=[tail,'','If a plan entry is not supporting a Campaign then enter:']
tail=[tail,'','CMP_NO = 0 for the entry in the IAP file. ']
tail=[tail,'','If unsure about which Campaign number to use, visit: ']
tail=[tail,'','---> http://sohodb.nascom.nasa.gov/cgi-bin/soho_campaign_search']
tail=[tail,'','or contact: zarro@smmdac.nascom.nasa.gov']
tail=[tail,line]


for i=0,ninst-1 do begin
 inst=do_inst(i) & delvarx,wmess,pmess

;-- skip this instrument?

 skip_inst=0
 if exist(skip_keys) then begin
  find_skip=where(strpos(skip_keys,strmid(inst,0,3)) gt -1,scount)
  skip_inst=(scount gt 0)
 endif
 if not skip_inst then begin
  pcheck=where(strpos(partic,inst) gt -1,pcount)
  if pcount gt 0 then begin
   pmess=['','Note that '+inst+$
          ' is participating in the following Campaigns for '+today,$
          '','CMP_NO TYPE           NAME','']
   icmp=cmp(pcheck) & ipartic=partic(pcheck)
   for k=0,pcount-1 do begin
    if trim(ipartic(k)) ne '' then parti='('+ipartic(k)+')' else parti=''
    pmess=[pmess,string(long(icmp(k).cmp_no),'(i4)')+'   '+$
     strpad(trim(icmp(k).cmp_type),12,/after)+'   '+trim(icmp(k).cmp_name)]
    if trim(parti) ne '' then pmess=[pmess,blank+parti,''] else pmess=[pmess,'']
   endfor
  endif

  icheck=where( strpos(stc.instrume,inst) gt -1,icount)
  if icount gt 0 then begin

;-- is instrument participating in campaign?

   if pcount gt 0 then begin

;-- now check for missing or invalid CMP_NO's

    head=[line,'Examination of the most recent '+inst+' IAP file for '+today,'']
    istc=stc(icheck)
    nstc=n_elements(istc)
    for k=0,nstc-1 do begin
     if (long(istc(k).cmp_no) ne 0) and (long(istc(k).cmp_no) ne 1) then begin
      clook=where(long(istc(k).cmp_no) eq long(cmp.cmp_no),count)
      if count eq 0 then begin
       warn=strpad(istc(k).type,20,/after)+' at '+istc(k).startime+' : '
       send_warn=1
       if long(istc(k).cmp_no) eq -1 then begin
        if exist(clist) then begin
         ilook=where(inst eq clist,icount)
         send_warn=(icount gt 0)
         warn2='No Campaign Number' 
        endif
       endif else begin
        warn2='Invalid Campaign Number - '+string(long(istc(k).cmp_no),'(i4)')

;-- check if Campaign # is just stale

        tback=tstart
        tback.mjd=tback.mjd-14
        tahead=tend
        tahead.mjd=tahead.mjd+14
        find_campaign,tback,tahead,cmp,ncmp
        if ncmp gt 0 then begin
         back_cmp=cmp.cmp_no
         ocheck=where(istc(k).cmp_no eq back_cmp,ocount)
         if ocount gt 0 then begin
          message,'Stale Campaign Number - '+string(long(istc(k).cmp_no),'(i4)'),/cont
          send_warn=0
         endif
        endif
       endelse
       if send_warn then begin
        warn=warn+warn2
        if not exist(wmess) then begin
         wmess=[head,'indicates the following omissions:','',warn]
        endif else wmess=[wmess,warn]
       endif
      endif
     endif
    endfor

;-- check if user forgot to participate in scheduled campaign
;   (only do this if planner didn't bother entering any CMP_NO)

    if not exist(wmess) then begin
     no_cmp=where(istc.cmp_no eq -1,ncount)
     if ncount eq n_elements(istc) then begin
      wmess=[head,'indicates missing Campaign numbers.',' ']
     endif
    endif
   endif
  endif else begin
 
;-- No IAP was submitted, but still send message if participating on this day

   get_utc,cur_day,/date,/ecs,/vms
   if (pcount gt 0) and (keyword_set(missing)) and (cur_day eq today) then begin
    item=''
    if skip_pro then item=' with SCI_PLAN entries ' else $
     if skip_sci then item=' with PROGRAM entries '
    wmess=[line,inst+ ' did not submit an IAP file'+item+' for '+today]
   endif
  endelse
 endif

;-- send output

 if exist(wmess) and exist(pmess) and keyword_set(alert) then begin
  wmess=[wmess,pmess,tail] 
  if keyword_set(alert) then begin
   mlook=where(inst eq do_inst,ic)
   if ic gt 0 then begin
    padd=mail_inst(mlook(0))

;-- get planner's e-mail from latest IAP

    padd2=''
    if (fcount gt 0) then begin
     iap=where(strpos(files,inst) gt -1,icount)
     if icount gt 0 then begin
      espawn,'grep -i orig_id '+files(iap(0)),out,/noshell
      out=out(0)
      if strpos(strupcase(out),'ORIG_ID') gt -1 then begin
       peq=strpos(out,'=')
       if peq gt -1 then padd2=trim(strmid(out,peq+1,strlen(out)))
      endif
     endif
    endif
    send_mail,array=wmess,add=padd
    if (padd2 ne padd) and (padd2 ne '') and (strpos(padd2,'@') gt -1) then $
     send_mail,array=wmess,add=padd2 
    send_mail,array=wmess,add=zmail
   endif
  endif else if screen then print,wmess
 endif

endfor

quit: 
if err ne '' then message,err,/cont
rm_file,files

return & end
 

