pro monitor_scratch, nomail=nomail, nomove=nomove, agelimit=agelimit
;
;+
;   Name: monitor_scratch
;
;   Purpose: monitor scratch areas; optionally move old files to designated area
;
;   History:
;      13-May-1994 (SLF) Written
;
;   Restrictions:
;      user must have rsh priviledge to software account
;-
if not keyword_set(agelimit) then agelimit=2	; 2 days old

scratch=['$DIR_REFORMAT_SC',		$	; areas to monitor
	 '$DIR_GBO_SC']

movepre=[['g6d','DIR_GEN_G6D'],	$	; add to this list for 
	 ['g7d','DIR_GEN_G7D'],	$	; additional moves
	 ['sxl','DIR_SXT_SXL'],	$       ; ** codify after testing **
	 ['sxc','DIR_SXT_SXC'],	$	; ie, env=get_logenv(*prefix*)
	 ['nts','DIR_GEN_NTS']]

mess=['------- MONITOR_SCRATCH run at:' + systime() + ' --------','', $
      'Looking for files older than: ' + strtrim(agelimit,2) + ' days old']

moving=''
mcmds=0
someold=0
for i=0,n_elements(scratch)-1 do begin
   sscnt=0
   oldfiles=dir_since(scratch(i),agelimit)
   if oldfiles(0) eq '' then begin
      mess=[mess,"No old files in: " + scratch(i)]
   endif else begin
      someold=1
      mess=[mess,'','Found: ' + strtrim(n_elements(oldfiles),2) + ' Old files in: ' + scratch(i)]
      message,mess(0),/info
      mess=[mess,oldfiles]
      for j=0,n_elements(movepre(0,*))-1 do begin
         mpre=where(strpos(oldfiles,movepre(0,j)) ne -1, precnt)
         if precnt gt 0 and not keyword_set(nomove) then begin
            if mcmds eq 0 then $
               mess=[mess,'',"Attempting the following commands... (rsh via software)",'']
            mcmds=mcmds+precnt
            outdir=get_logenv(movepre(1,j))
            for m=0,precnt-1 do begin
               mvcmd='/bin/cp -fp ' + oldfiles(mpre(m)) + ' ' + outdir
               rsh,'isass0',mvcmd,status,user='software',ocommand=ocommand
               message,/info,ocommand(0)
               mess=[mess,mvcmd]            
;              verify copy before deleting
               if file_stat(oldfiles(mpre(m)),/size) eq $
                  file_stat(concat_dir(outdir,$
	              strsplit(oldfiles(mpre(m)),'/',/tail)),/size) then begin
	             file_delete,oldfiles(mpre(m))
               endif
            endfor
         endif
      endfor         
   endelse
   still=file_stat(oldfiles,/exist)
   ss=where(still,sscnt)
   if sscnt gt 0 then begin
      mess=[mess,"Did not or could not move from: " + scratch(i),oldfiles(ss)]
   endif

endfor

if not keyword_set(nomail) and someold then begin
   mess=mess(1:*)
   mail,mess,subj='MONITOR_SCRATCH: Old files found'
endif

return
end
