# This Perl 5 script searches .cpp files for OLE interface implementations
# and adds a Borland C++ TRACE macro at the beginning of the function.
#
# George Cross, Borland C++ Developer Support, August 13 1997
#

print("\n".$0.":\n");

die "
usage: trace <option> 
options: -a     add traces
         -r     remove traces\n" if !@ARGV;

# Get a list of all .cpp files in this directory

use Cwd;
$homedir = cwd();
opendir(THISDIR,$homedir);
@filelist = grep(/\.cpp$/i,readdir(THISDIR));

if ($ARGV[0] =~ /-a/){

  # For each .cpp file, 
  #   1. create a new file with same name and .new extention
  #   2. iterate through each line copying it to the new file
  #   3. look for '^STDMETHOD ... ::' thus identifying a class method
  #   4. when such a line is found, insert a 'TRACE ' statement into the 
  #      new file.

  foreach $file (@filelist){
    $found = 0;
    open(INFILE,"<$file");

    $file = lc($file);
    $basefname = substr($file,0,rindex($file,"cpp"));
    $newfile = $basefname . "new";
    system("copy $file $newfile"); 
    open(OUTFILE, ">$newfile");

    foreach (<INFILE>){
      print OUTFILE $_;
      if ($found){
	if (/{/){
	  # print OUTFILE ("\t TRACE(\"$fnName\");\n");
	  print OUTFILE ("OutputDebugString(\"$fnName\");\n"); 
	  $found = 0;
	}
      }else{
	if (/^STDMETHOD.*::/){
          $beginpos = rindex($_," ",rindex($_,"::"));
          /(\(|$)/;
          $endpos = rindex($_,$1); 
	  $fnName = substr($_,$beginpos,$endpos - $beginpos);
          chop($fnName) unless $1 =~ /\(/;
	  $found = 1;
	}
      }
    }
    close(OUTFILE);
    close(INFILE);
  }
  print ("\n\tTraces added.");

} else { # ARGV[0] -r

  # For each .cpp file, 
  #   1. create a new file with same name and .new extention
  #   2. iterate through each line copying it to the new file
  #   3. look for any line containing '^\t\s*TRACE\s*\(.*\);$/' 
  #   4. when such a line is found, exclude it from output into new file 

  foreach $file (@filelist){
    open(INFILE,"<$file");

    $file =~ tr/A-Z/a-z/; 
    $basefname = substr($file,0,rindex($file,"cpp"));
    $newfile = $basefname . "new";
    system("copy $file $newfile"); 
    open(OUTFILE, ">$newfile");

    foreach (<INFILE>){
      print OUTFILE $_ unless (/^\t\s*TRACE\s*\(.*\);$/);
    }
    close(OUTFILE);
    close(INFILE);
  }
  print ("\n\tTraces removed.");
}


closedir(THISDIR);

system('ren *.cpp *.bak');
system('ren *.new *.cpp');
