#!/usr/bin/perl 

# Script to modify the PD source files 
# and rename the help patches
# with a "help-" prefix or a "-help" suffix.
# It tries to move all help patches from a library
# into a a correspondant help subfolder
# Marc Lavallée, 16/09/2003

$source_home = "."; # where is the source? (recursive search)
$help_home = "./help"; # where to move the help patches?

$help_format = 1; # 0 for prefix, 1 for suffix


# Don't change anything below this line

$prefix = "help-"; # usual prefix for help files
$suffix = "-help"; # usual suffix for help files

`rm -rf $help_home`; `mkdir $help_home`; 
`find . -name "*.tmp" | xargs rm -f`;


@cfiles = split("\n", `find . -name "*.c*"`);
for (@cfiles) { # check each c* file
  $infile = $_; $tmpfile = "$_.tmp";
  @temp = split("\/",$infile); $dir = @temp[1]; 
  open IN, "$infile" or die "Could not open file $_ for reading: $!";
  print "> $infile\n";
  open OUT, ">$tmpfile" or die "Could not open file for writing: $!";
  while (<IN>) {
    chomp; $line = $_;
    if ( /(^.*class_sethelpsymbol.*\(.*,.*gensym\(.*[\"|\'])(.+)([\"|\'].*\).*\).*\;)/ ) {
      $start = $1;  $help = $2;  $end = $3; 
      $help =~ s/\.pd//; # remove ".pd" suffix
      $help =~ s/$prefix//; # remove prefix
      $help =~ s/$suffix//; # remove suffix
      
      # extract relevant parts of the help string
      @temp = split("\/",$help); 
      $nhelp = pop(@temp); # help name
      $phelp = join("\/",@temp);  # help path
      
      # find the help file
      $fhelp = `find $dir -name '$nhelp.pd'`; chomp($fhelp);
      $pattern = quotemeta($nhelp); # print "!! $pattern\n";
      if ( ! $fhelp =~ /\/$pattern\.pd/ || ! length($fhelp) ) {
        $fhelp = `find $dir -name \"help-$nhelp.pd\"`; chomp($fhelp);
				if ( ! $fhelp =~ /\/help-$pattern\.pd/ || ! length($fhelp) ) {
          $fhelp = `find $dir -name "$nhelp-help.pd"`; chomp($fhelp);
        }
      }
      
      # If the helpfile exists, 
      if ( length($fhelp) ) {
        print "$dir ($phelp) : $help => $nhelp --> $fhelp\n";
				if (! -d "$help_home/$phelp" ) {
					mkdir("$help_home/$phelp", 0755);
				}
				if ($help_format) {
					`mv $fhelp $help_home/$phelp/$nhelp$suffix.pd`;
				} else {
					`mv $fhelp $help_home/$phelp/$prefix$nhelp.pd`;
				}
				print OUT "$start$help$end\n"; # write new line
      } else {
        print OUT "$line\n"; # write original line
      }
    } else {
      print OUT "$line\n"; # write original line
    }
  }
  close IN  or die "Could not close file: $!";	
  close OUT or die "Could not close file: $!";	
  `mv -f $tmpfile $infile`;
}


