#Read in a verify config file

unless (-s "config") {
  print "missing token configuration file.\n";
  exit 1;
} 

chomp(@CONFIG = `cat config`);
open(HANDLE, ">config");
$COUNT = 0;
foreach $LINE (@CONFIG) {
  $COUNT++; 
  @LIST = split (/:/, $LINE);
  $SIZE = @LIST;
  if ($SIZE < 5) {
    print "Config file line $COUNT: ";
    print "only $SIZE of 5 elements found.\n";
    print "\nUsage:\n\n";
    print "    Name : default value : begin token : end token : file\n"; 
    exit 1;
  } elsif ($SIZE > 5) { 
    print "Config file line $COUNT: ";
    print "$SIZE fields found when only 5 is expected.\n";
    print "\nUsage:\n\n";
    print "    Name : default value : begin token : end token : file\n"; 
    exit 1;
  } else {
    unless ($LIST[0] =~ /\S+/) {
      print "Config file line $COUNT: ";
      print "\"Name\" field may not be empty.\n";
      exit 1;
    } 
    $LIST[0] =~ s/^\s*//;
    $LIST[0] =~ s/\s*$//;
    $LIST[2] =~ (s/\s//g);
    $LIST[2] = "\U$LIST[2]"; 
    unless ($LIST[2] =~ /\S+/) {
      print "Config file line $COUNT: ";
      print "\"begin token\" field may not be empty.\n";
      exit 1;
    } elsif ($LIST[2] =~ /^help$|^END-NEOS-INPUT$/i) {
      print "Config file line $COUNT: ";
      print "The token \"$LIST[2]\" is reserved for the NEOS server.\n";
      exit 1;
    } 
    $LIST[3] =~ (s/\s//g);
    $LIST[3] = "\U$LIST[3]"; 
    unless ($LIST[3] =~ /\S+/) {
      print "Config file line $COUNT: ";
      print "\"end token\" field may not be empty.\n";
      print "\nUse \"null\" for single line tokens.\n"; 
      exit 1;
    } 
    $LIST[4] =~ (s/\s//g);
    unless ($LIST[4] =~ /\S+/) {
      print "Config file line $COUNT: ";
      print "\"file\" field may not be empty.\n";
      exit 1;
    } elsif ($LIST[4] =~ /^NOHEADER$|^HELP$|^job\.|\.out$|\.error$|^DONE$|^SOLVER_DONE$|^NO_SEND$|^BAD_PARSE$|^NO_PORT$|^TIMEOUT$/) {
      print "Config file line $COUNT: ";
      print "The file \"$LIST[4]\" is reserved for the NEOS server.\n";
      exit 1;
    } 
    $LIST[1] =~ s/^\s*//;
    $LIST[1] =~ s/\s*$//;
    print HANDLE "$LIST[0]:$LIST[1]:$LIST[2]:$LIST[3]:$LIST[4]\n";
  }
}
close(HANDLE);
