"*************************************************************************"
"updateprocpars(directory,macro) - does a search and replace of text in   "
"                      the procpar files of all parameter sets and data   " 
"                      in the specified directory. The first argument is  "
"                      the directory. Argument 2 is the text to be        "
"                      replaced and Argument 3 is the replacement text.   "
"                                                                         "
"                      This macro is used to directly change parameter    "
"                      attributes in multiple parameter and data sets.    "
"                                                                         "
"          Example:    updateprocpars('~/vnmrsys/parlib','pwX90','pwC90') "
"                                                                         "
"          Related:    macroupdatepars updates by loading parameters,     "  
"                      executing a macro in the workspace and resaving    "
"                      them.                   .                          "
"*************************************************************************"

exists($1,'directory'):$e
if ($e < 0.5) then
   write('error','Directory %s does not exist',$1)
   abort
endif

$inText =''
if (typeof('$2') > 0.5) then 
   $inText = $2
else
  write('error','Format: Argument 2 must be a string type')
  abort
endif

$outText =''
if (typeof('$3') > 0.5) then 
   $outText = $3  
else
   write('error','Format: Argument 3 must be a string type')
   abort
endif

getfile($1):$entrys
write('alpha','directory %s has %d entries',$1,$entrys)
$inode = 0
$filename = ''
$ext = ''
while ($inode < $entrys) do
   $inode = $inode + 1
   getfile($1,$inode):$filename,$ext
   if (($ext = 'fid') or ($ext = 'par')) then
      $path = $1 + '/' + $filename + '.' + $ext + '/procpar'
      exists($path,'file'):$e
   else
      $e = 0
   endif
   if ($e > 0.5) then
      write('alpha','  Entry %d: Update %s.%s',$inode,$filename,$ext)
      $e1=0
      $tempfile = $1 + '/' + $filename + '.' + $ext + '/updateout'
//    write('alpha','$tempfile = %s\n',$tempfile)
      exists($tempfile,'file'):$e1
      if ($e1 > 0.5) then 
         rm($tempfile):$dum
      endif
      $cmd='sed -i -e \'s/'+$inText+'/'+$outText+'/w ' +$tempfile+ '\' '+$path
//    write('alpha','$cmd = %s\n',$cmd)
      shell($cmd):$dum
      $e1=0
//    write('alpha','$tempfile = %s\n',$tempfile)
      exists($tempfile,'file'):$e1
      if ($e1 > 0.5) then
         cat($tempfile)
         rm($tempfile):$dum
      else
         write('error', 'Abort: Bad search string')
         abort
      endif
   else
      $notpar = $filename
      if ($ext <> '') then
         $notpar = $filename + '.' + $ext
      endif
      write('alpha','  Entry %d:  %s is not a parameter file',$inode,$notpar)
   endif
endwhile
