;+
;NAME:
;	go_mon_sci5k
;PURPOSE:
;	To see if the mon_sci5k process is running and to start it up if needed
;HISTORY:
;	12-May-99 (CED) - Removed /disp_loi from the mon_sci5k call
;	11-May-99 (CED) - Added /daily flag to the mon_sci5k call
;	21-Apr-99 (CED) - Fixed bug that caused infinite loop (hence runaway
;			  CPU hogging) if the last file in /md80/log/mon5k was 
;			  not owned by mdi.  Used GSE_MON5K_DIR environment
;			  variable instead of hardwired location.
;	 2-Dec-97 (CED) - Modified error code to send message to idl-cron 
;			  instead of to morrison
;	30-Aug-96 (MDM) - Modified to call "pkt_time" to find out the time of
;			  the newest packet and to not re-start if it's hung
;			  because of no telemetry
;	 8-Jul-96 (MDM) - Revised to kill the children processes too 
;	24-Jul-96 (MDM) - Removed the mail message sending (since dynamics ended)
;	 6-Jun-96 (MDM) - Added /FILE switch to the mon_sci5k call
;	30-May-96 (MDM) - Added call to "track_proc" to kill any earlier runs which
;			  are hanging around or waiting for telemetry
;	29-May-96 (MDM) - Added call to get_dpc_info before mon_sci5k to avoid hangs
;	Written 29-May-96 by M.Morrison
;-
;
dir = getenv('GSE_MON5K_DIR')
if(dir eq '') then message,'No GSE_MON5K_DIR defined!'

ff = file_list(dir, '*', /cd, /bydate)
n = n_elements(ff)
qok = 0
i = n-1

;; Removed bad code... [CED]
;while (not qok) do begin		;look for latest file owned by mdi
;    nn = file_info2( ff(i), finfo)
;    qok = (finfo.owner eq 'mdi')
;end

; Look for latest .mon file owned by mdi
while(not qok) and i gt 0 do begin
	if(strpos(ff(i),'.mon')) eq strlen(ff(i)) - 4 then begin ; look for .mon files
		nn = file_info2(ff(i),finfo)
		qok = (finfo.owner eq 'mdi')
	end
	i=i-1
end

qrestart = 1

if(qok) then begin
	dt = int2secarr(!stime, finfo)		;number of seconds ago that it was written to
	if (dt lt 300) then begin
	    print, 'Log file: ' + ff(i) + ' written to ', long(dt), ' seconds ago'
	    qrestart = 0
	end
end
;
spawn, '$MDI_TASK_DIR/pkt_time hk1', result
dt = long(result(0)) - int2secarr(ut_time(), '1-jan-70')
if (dt lt -120) then begin
    print, 'No telemetry comming in at this time.  DT = ', dt
    qrestart = 0
end
;
if (qrestart) then begin
    mail, ['Starting up mon_sci5k'], users='idl-cron', subj='MON_SCI5K startup'
    ;
    ;;pids = track_proc('mdi', 'mdi_sci', 'bin.sgi/idl', /kill)
    pids = track_proc('mdi', 'mdi_sci', term='?', /kill)
    ;
    get_dpc_info,0			;force the slow compile/read to happen
    set_plot, 'z'
    wdef, 0, 640, 512
    mon_sci5k, /log, /file, /daily
end
;
end