#amalgam.pl
#
# Rudolf Cardinal, 16 June 99.
# I imagine this code marks me for my usual programming language...

($switches) = ( $ARGV[0] =~ /^-(\w+)/ );
$switches =~ tr/A-Z/a-z/;    # canonicalize to lower case
if ($switches) {
  # print "Switches: $switches\n";
  shift @ARGV;    # get rid of the switches from ARGV
  # NOTE - shift returns the dropped value, but it modifies the array directly too.
  # So writing "@ARGV = shift" makes ARGV contain nothing but the first item.
}
( $output, @input ) = @ARGV;

$allow_append = 0;    # default
$allow_append = 1 if ($switches =~ /a/);

if ( !$output || !@input ) {
  print "Amalgam (Perl version) - amalgamates files for import to Access/Excel\n";
  print "by amalgamating the files, retaining the first line from only the first file.\n";
  print "\n";
  print "Syntax:\n";
  print "  amalgam [-a] outputfile input1 [input2 [input3]]...\n\n";
  print "Input files may take wildcards.\n";
  print "Switches:\n";
  print "  -a   Allows amalgam to append to an existing file.";
  die "\n";
}

$donefirst = 0;
if (-e $output) {
  if (!$allow_append) {
    die "Output file exists, unwilling to continue. Use -a switch if you meant it.\n";
  }
  print "Output file exists, appending...\n";
  open(Output, "<" . $output) || die "Can't read output file (trying to get header)\n";
  $headerline = <Output>;
  close(Output);
  $donefirst = 1;             # don't redo the first line in this situation
}

open(Output, ">>" . $output) || die "Can't write to output file.\n";

print "Amalgamating...\n";
print "- Writing to $output\n";
print "- Reading from " . ($#input+1) . " file(s): @input\n";

@ARGV = @input;
# Allows us to use the magic filehandle <> below.

while (<>) {
  if ($. == 1) {
    # The first line of a file.
    if ($donefirst == 0) {
      $donefirst = 1;
      $headerline = $_;
      print Output "$_";
    }
    else {
      print "*** Warning - file $ARGV has a different header from the output.\n" if ($_ ne $headerline);
      # Use "eq" and "ne" for string comparison, not "==" and "!=".
    }
  }
  else {
    # Not the first line of a file.
    print Output "$_";
  }
  close(ARGV) if (eof);   # Taken from the eof() description, this is how to reset line numbering for each file.
}

close(Output);
print "Done.\n";
