#!/usr/local/bin/perl
#
#
# Splits a single file into multiple .java files each belonging to the same
# package.
#
# For improvements, please edit the original in /homes/sep/matt/usr/srcAdm
# Joel Schroeder: Oct96
#

$usage = "Usage: $0 packagename [dir] < file \n";
$selfdoc = "
Splits file into many .java files (in the package packagename).
The .java files are separated in file by a string of >= 10 dashes (-).
\tpackagename - The name of the package which the .java files are part of.
\tdir         - Where the .java files are written (cd if not specified).  
\tfile        - The file to be split.
";

if( $#ARGV < 0 ||$#ARGV > 1 ) {
  print $usage;
  die $selfdoc;
  }

$pkg = $ARGV[0];
if( $#ARGV == 1) {
  $dir = $ARGV[1]."/"; }
else             {
  $dir = "./"; }

while (!eof(STDIN)) {
$foundName   = 0;
$pkgDeclared = 0;
$outData     = "";
  while ($_ = <STDIN>) {
    # substitute the package name (should probably be optional)
    if (s/^(\s*package\s+)[\w\.]+(\s*;)/$1$pkg$2/) { 
      $pkgDeclared = 1; 
    }
    # check if this line declares a public class or interface
    if (/^[^\/]*public[^\/]+(class|interface)\s+([\w\.]+)[^\w\.]+/) {
      $className = $2;
      $foundName =  1;  
    }
    last if /^\s*-{10,100}/ ;
    $outData = $outData.$_ ;
  }

  next if ($foundName == 0);
  
  $fileName = "$dir$className.java";
  open(currFile, ">$fileName") || die "Error opening $fileName.\n";
  select(currFile);
  if ($pkgDeclared == 0) {
    print "package $pkg;\n"; }
  print $outData;
  close( currFile);
}
