#!/usr/bin/env perl
use strict;
################################################################################
sub show_documentation {
  my $exit_status = shift@_;
  print "
  ACTION
  ======

    Script to remake the filesets defined perdefault in the
    AAA_CATALOG.html and DATSET.files.

  SYNTAX
  ======

    remakeFileSets.pl  <dir> <nFiles> <remDir>

      -h    to get this help

      <dir>      - directory where the dataset definition resides.
      <nFiles>   - number of files per fileset
      <remDir>   - remote directory

";
  exit $exit_status;
}
#
# Called from user
#
# VERSION 0.0                                                 16/05/2002 Ch.Paus
################################################################################
my ($DIR,$NFILES) = ("./",50);
my ($REMDIR) = ("/cdf/scratch/cdfdata/scratch/pent-mit-stn-22/root");
my ($SERVER) = ("fcdfdata051.fnal.gov");
#-------------------------------------------------------------------------------
my ($rc,$cmd,$dset,$fset,$oldFset,$lastOldFset,$nFiles,$line);
my (@f);
#-------------------------------------------------------------------------------

if ("$ARGV[0]" eq "-h") { &show_documentation(1); }

if ($#ARGV == 2) { $DIR    = "$ARGV[0]"; $NFILES = "$ARGV[1]";
		   $REMDIR = "$ARGV[2]"; }
else             { &show_documentation(2); }

$fset = 0;
$nFiles = 0;
$lastOldFset = -1;

open(INPUT,"cat $DIR/*.files |");
open(FILES,">TEST.BAK");
while(<INPUT>) {
  chop($_);
  if (/#/) {
  }
  else {
    @f       = split(" ",$_);
    $dset    = shift(@f);
    $line    = join(" ",@f);
    @f       = split('\.',$dset);
    $dset    = $f[0];
    $oldFset = $f[1];

    if    ($nFiles == 0) {
      $lastOldFset = $oldFset;
      printf "$dset.%04d $SERVER $REMDIR/$oldFset 1 1 1000000\n",$fset;
    }
    elsif ($oldFset != $lastOldFset) {
      $lastOldFset = $oldFset;
      $fset++;
      printf "$dset.%04d $SERVER $REMDIR/$oldFset 1 1 1000000\n",$fset;
    }
    elsif ($nFiles%$NFILES == 0) {
      $fset++;
      printf "$dset.%04d $SERVER $REMDIR/$oldFset 1 1 1000000\n",$fset;
    }

    printf FILES "$dset.%04d $line\n", $fset;
    $nFiles++;
  }
}
close INPUT;
close FILES;

exit 0;
