#! /n/gnu/bin/gawk -f
# Last edited on 1999-11-20 23:28:10 by hcgl

BEGIN {
  usage = ( ARGV[0] " CANDS1 CANDS2 ... CANDSN > CANDSTOT" );
  abort = -1;
  
  split("", nc);
    
  printf "begin PZCandidate.List (format of 99-07-25)\n";

  ncands = 0;
  for(i = 1; i < ARGC; i++) { 
    printf "||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\n";
    printf "| file \"%s\"\n", ARGV[i];
    nc[i] = read_cands_header(ARGV[i]);
    printf "| candidates = %d\n", nc[i];
    ncands += nc[i];
  };
  printf "||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\n";
  printf "candidates = %d\n", ncands;
  printf "lambda = %d\n", lambda;
  for(i=1; i<ARGC; i++) { 
    for(k = 0; k < nc[i]+0; k++)
      { getline lin < ARGV[i];
        printf "%s\n", lin;
      }
    read_cands_tailer(ARGV[i]);
  }
  printf "end PZCandidate.List\n";
  exit 0;
}

(abort >= 0) { exit abort; }

function read_cands_header(file,    lin, n)
{
  # Reads the "begin" line, copies all comments to
  # standard output, sets the global variable "lambda", 
  # and returns the number of candidates.
  
  getline lin < file;
  if(lin != "begin PZCandidate.List (format of 99-07-25)")
    { file_error(file, "missing \"begin\" line"); }
  getline lin < file;
  while(lin ~ /^[|]/) 
    { printf "%s\n", lin;
      getline lin < file;
    }
  if (! match(lin, /^candidates *= */))
    { file_error(file, "missing \"candidates =\" line"); }
  n = substr(lin, RLENGTH+1);
  printf "%s candidates = %s\n", file, n > "/dev/stderr";
  getline lin < file;
  if (! match(lin, /^lambda *= */))
    { file_error(file, "missing \"lambda =\" line"); }
  lambda = substr(lin, RLENGTH+1);
  return n;
}

function read_cands_tailer(file,    lin)
{
  lin = "";
  getline lin < file;
  if (lin != "end PZCandidate.List")
    { printf "%s\n", lin > "/dev/stderr";
      file_error(file, "missing \"end\" line");
    }
}
  

function file_error(file, msg)
{
  printf "file \"%s\", line %d: %s\n", file, FNR, msg > "/dev/stderr";
  abort = 1;
  exit abort;
}