#! /usr/bin/perl -w
#
# split N
#
# Script to divide the subdomains of a complete run in half repeatedly
#  getting the .ccf file names from system.pscf

# N times (limited to 7, default 5), creating a succession of directories named
# the current one D with a 2 appended for each split:  D2, D22, ..., D22222, ...
# In the new directory, remove *.ccf[ct] and theory* files

use Cwd;
use File::Copy;

if (defined($ARGV[0])) { #count parameter
  $N = $ARGV[0];
  die "Count parameter must be in [1..7]" 
    unless ($N =~ /\d/ && $N >= 1 && $N <= 7);
} else {
  $N = 5;
}
 
for ($i=1; $i<=$N; $i++) {
  # Divide the subdomains of a complete run in half.
  # Driven by system.pscf file.  Each component .ccf file is adjusted
  #  but in a new directory that is a copy of the current one D with 
  #  2 appended to D.
  # To preserve permissions and times, the directory is copied with a UNIX
  #  system command unless Perl thinks it's Windows.

  #copy current directory D into D2
  $dir = getcwd();
#print "Working on $dir (index $i)\n";  #debug
  $dir2 = $dir."2";
  unlink glob("$dir2/*");
  rmdir $dir2;
  mkdir $dir2;

  if ($^O eq "MSWin32") { #bad form!  but no way out...
    opendir(BASE,"<$dir") or die "Current directory disappeared!";
    @allfilenames = readdir BASE;
    foreach $f (@allfilenames) {
      if ($f !~ /^\./) {
        copy($f,"$dir2/$f");
      }
    }
    close(BASE);
  } else {  # everybody else? 
    system("cp -p $dir/* $dir2");
  }
  $dir = $dir2;  #name now the new directory

  open(PSCF, "<".$dir."/system.pscf") || die "can't open system.pscf";
  $line = <PSCF>;  #discard Polish line
  if (-e "ident.bin") {
    $ccffile = "ident.ccf\n";  
  }
  else {
    $ccffile = <PSCF>;
  }
  while ($ccffile) {  #process each file name in the file
    chop($ccffile);
    open(CCF, "<$ccffile") || die "can't open .ccf file ", $ccffile;
    open(NCCF, ">".$dir."/".$ccffile) || die "failed to open new .ccf filep";
    $line = <CCF>; 
    print NCCF $line;  #copy the name
    while ($line = <CCF>) {  #read each subdomain line in the file
      if ($line eq "\n") { #just copy a blank line
      print  NCCF"\n";
      } else {
      @subs = split(" ",$line);
      $numex = $subs[2];
        $mid = ($subs[0] + $subs[1])/2;
        print NCCF $subs[0]." ".$mid." ".$numex."\n";
        print NCCF $mid." ".$subs[1]." ".$numex."\n";
      }
    }
    close(CCF);
    close(NCCF);
    $ccffile = <PSCF>;  #get next file until EOF
  }
  close(PSCF);
  #remove files that are surely out of date
  unlink glob("$dir/*.ccft");
  unlink glob("$dir/*.ccfc");
  unlink glob("$dir/theory*");
  chdir $dir;  #to new directory for repeat
}
