pro killold, testing=testing, noconfirm=noconfirm, mail=mail, all=all, $
	user=user, hours=hours
;+
;   Name: killold
;
;   Purpose: kill old jobs (PIDs)
;
;   Keyword Parameters:
;      noconfirm - switch, if set, do not prompt before each kill
;      testing   - switch, if set, just show what WOULD happen (no spawn)      
;      hours     - age to kill (default is 24-48 hours)
;      all       - kill all jobs (older than 10 minutes - dont kill THIS JOB)
;
;   Calling Sequence:
;      killold [,/noconfirm, /testing]
;
;   Restrictions:
;      Unix alpha-osf only (or others with identical "ps auxw" format)
;
;   History:
;      21-Dec-1995 (S.L.Freeland)
;       5-jan-1996 (S.L.Freeland) - add MAIL keyword
;      10-jan-1996 (S.L.Freeland) - use prstr instead of more
;      11-jan-1996 (S.L.Freeland) - only mail if jobs killed 
;       4-feb-1996 (S.L.Freeland) - add HOURS keyword and logic
;-
;
if n_elements(user) eq 0 then user=get_user()
spawn,'ps auxw | grep ' + user,psout

; ** note - I will absorb the "software" messages... (Sam Freeland)
;muser=([user,"freeland@isass0.solar.isas.ac.jp"])(user eq "software")
muser=user
pscol=str2cols(psout)
pids=strtrim(reform(pscol(1,*)),2)
dates=strupcase(strtrim(strmid(psout,49,11),2))

month=(str2arr(gt_day(!stime,/string),'-'))(1)
lastmonth=(str2arr(gt_day(timegrid(!stime,week=-4,/string),/string),'-'))(1)

old=where(strpos(dates,month) ne -1 or strpos(dates,lastmonth) ne -1,ocnt)

all=keyword_set(all) or keyword_set(hours)		; check times


if all then begin
   ok=where(strlen(dates) eq 8 and strpos(dates,':') ne -1,okcnt)
   if not keyword_set(hours)  then hours=.2	; dont kiil this job!
   if okcnt gt 0 then begin
      dates(ok)=fmt_tim( gt_day(!stime,/string) + ' ' + dates(ok))
      delta=int2secarr(anytim2ints(dates(ok)))
      oldd=where(abs(delta) gt hours*3600. , ocnt2)
      case 1 of 
         ocnt gt 0 and ocnt2 gt 0: old=[old, ok(oldd)]
	 ocnt2 gt 0: old=ok(oldd)
         else:
      endcase
      ocnt=ocnt+ocnt2
   endif
endif

resp=''
noconf=keyword_set(noconfirm)
confirm=1-keyword_set(noconfirm)

resp=(['',"Y"])(noconf)
testing=keyword_set(testing)

mess="Number of old jobs: " + strtrim(ocnt,2)
message,/info,mess

pr_status,txt

mail_mess=[txt,'',strjustify(mess,/box)]

mailit=keyword_set(mail) and ocnt gt 0  

for i=0,ocnt-1 do begin
   this_mess=strmid(psout(old(i)),0,78)
   prstr,this_mess
   if confirm then $
      read,"*** >>> kill this PID? ",resp
   cmd="kill -9 " + pids(old(i))
   killit=strupcase(strmid(resp,0,1)) eq 'Y' 
   case 1 of 
      testing: kmess="Testing: " + cmd
      killit: begin
         kmess="Spawning: " + cmd
         spawn,cmd
      endcase
      else: kmess="No action..."
   endcase
   message,/info,kmess
   mail_mess=[mail_mess,'',this_mess,kmess]
endfor

if mailit then mail,mail_mess,user=muser, $
   /no_defsub, subj="KILLOLD - #PIDs killed: " + strtrim(ocnt,2)

return
end
