;+
; $Id: getidlpid.pro,v 1.4 2008/03/24 17:59:01 nathan Exp $
; Project     : SOHO - LASCO/EIT
;
; Name        : GETIDLPID
;
; Purpose     : Returns IDL Process ID
;
; Use         : IDL>    result = GETIDLPID()
;
; Inputs      :
;
; Optional Inputs:
;
; Outputs     :
;
; Keywords    :
;
; Comments    :
;
; Side effects:
;
; Category    :
;
; Written     : Jake Wendt, NRL, April 10, 2002
;
; Version     :
;
; $Log: getidlpid.pro,v $
; Revision 1.4  2008/03/24 17:59:01  nathan
; output string not int to be compat with previous version
;
; Revision 1.3  2008/03/24 17:22:33  nathan
; fixed some bugs
;
; Revision 1.2  2008/03/20 22:16:59  nathan
; use get_pid.pro as template to avoid using binaries
;
; Revision 1.1  2008/03/20 22:02:26  nathan
; moved from lasco/idl/reduce
;
;   07/10/03 @(#)getidlpid.pro	1.4
;
;-

;-----------------------------------------------------------------------

FUNCTION GETIDLPID

process='idl'
all=0
err='' & count=0 & tty='' & pid=0

if os_family(/lower) eq 'vms' then begin
 espawn,'write sys$output f$getjpi(f$pid(pid), "terminal")',out,count=count
 if count eq 1 then tty=out[0] else return,pid
 espawn,'write sys$output f$getjpi(f$pid(pid), "pid")',out,count=count
 if count eq 1 then pid=out[0]
 return,pid
endif

espawn,'ps',out,count=count,/noshell,/cache
if count eq 0 then begin
 err='Cannot determine PID'
 message,err,/cont
 return,pid
endif

;-- filter out PROCESS from PS output

ppos=where(strpos(out,process) gt -1,count)
if count eq 0 then begin
 err='Cannot find process in PS output'
 message,err,/cont
 return,pid
endif

;-- get PID and TTY

out=out[ppos]
tpos=strpos(strlowcase(out),'tty')
ppos=strpos(strlowcase(out),process)
term=strarr(count) & pid=lonarr(count)
for i=0,count-1 do begin
 ps=out[i]
 pid[i]=strmid(ps,0,ppos[i])
 term[i]=strmid(ps,tpos[i],8)
endfor

if not all then begin
 espawn,'tty',out,count=count,/noshell,/cache
 if count eq 0 then begin
  err='Cannot determine terminal'
  message,err,/cont
 endif else begin
  var=grep(out(0),'/dev/'+term,index=tpos)
  if var[0] ne '' then begin
   tty=term(tpos)
   pid=pid(tpos)
  endif
 endelse
endif else tty=term

tty=trim2(tty)
count=n_elements(pid)
if count gt 1 then begin
 pid=pid[0] & tty=tty[0]
endif

return,trim(pid)


    ;SPAWN, "/bin/ps -ef | grep `echo $$` | grep sh | gawk '{print $3}' | grep -vs `echo $$`", result, /SH
    ;RETURN, result[0]

END;	FUNCTION GETIDLPID

