/* Scan config.sys for a string and replace it with another one */

call RxFuncAdd 'SysLoadFuncs', 'RexxUtil', 'SysLoadFuncs'
call SysLoadFuncs

Parse Arg Input_Parameters
Test=Words(Input_Parameters)
Select
   when Test<2 then Do
      Say ""
      Say "You must enter a target and a replacement string."
      Say ""
      Exit
   end /* do */
   when Test>2 then Do
      Parse Var Input_Parameters '"' Target '"' '"' Replacement '"'
   end /* do */
   otherwise /* If it falls through to here, we must have 2 input strings */
      Parse Var Input_Parameters Target Replacement .
end  /* select */

Say "TARGET:" Target
Say "REPLACEMENT:" Replacement

Target_Length=Length(Target)
Target_Uppercase=Translate(Target)

/* Copy CONFIG.SYS to CONFIG.TST for safety
   Assumes that CONFIG.SYS is in the root directory of the C: drive
   change as appropriate
*/
"copy c:\config.sys config.tst"

/* Exit if we can't find the file */
if rc<>0 then Do
   Say " "
   Say "Could not find CONFIG.SYS!"
   Exit
end /* do */

/* Now search the file for the target string */
rc=SysFileDelete("CONFIG.NEW")
Current_Line_Number=0
Do While Lines("CONFIG.TST")
   a_line=Linein("CONFIG.TST")
   Current_Line_Number=Current_Line_Number+1
   Test_Line=Translate(a_line)
   Found=Pos(Target_Uppercase,Test_Line)
   If Found<>0 then Do
      Say ""
      Say "Found target in line" Current_Line_Number 
      Say a_line
      Call Replace
      Say "The above line was replaced by:"
      Say a_line
   end /* do */
   /* Now we write out a_line to CONFIG.NEW */
   rc=Lineout("CONFIG.NEW",a_line)
end /* do */
rc=Stream("CONFIG.TST","C","Close")
rc=Stream("CONFIG.NEW","C","Close")
Exit

Replace:
/* Replaces all occurences of the target string in a_line */
Do While Found<>0
   /* Get the part of the string up to the target */
   First_Part=SubStr(a_line,1,Found-1)
   /* 
      Now get the part after the target, the beginning of
      the part of the string after the target is located
      at POS(target,a_line) plus LENGTH(target)
   */
   Last_Location=Found+Target_Length
   Last_Part=SubStr(a_line,Last_Location)
   /* Now put the replacement string in between them */
   a_line=First_Part||Replacement||Last_Part
   /* Now look for the target string again to make sure we get all of them */
   Test_Line=Translate(a_line)
   Found=Pos(Target_Uppercase,Test_Line)
end /* do */
Return
