#
# This script reads a csv containing 1000 rows of 5 dose groups (columns),
# and creates a separate test input file for each row.
#
# We assume that the csv fields are simple without any quoted data.

BEGIN {
# Awk variables for field and record separators
  FS = ",";
  OFS = " ";
  RS = "\r\n";
  ORS = "\r\n";
# Custom variables controlling test file creation
# Set default values if not specified on cmd line when awk is invoked
  if (iNTests == "") iNTests = 1000;
  if (zSeed == "") zSeed = 0;
  if (iAdvDir == "") iAdvDir = 0;
  if (iConstVar == "") iConstVar = 1;

  idataset = 0;
# Read line 1
  MyGetLine();
  basename = $1;
  gsub(/ /, "_", basename);
#  printf("basename= %s\n", basename)

# Read line 2
  MyGetLine();
  truebmd = $1;
  gsub(/ /, "_", truebmd);
#  printf("truebmd= %9.8f\n", truebmd)

## Ensure that directory for files exists
#dirname = basename;
#cmdline = sprintf("if test ! -d %s; then mkdir %s; else rm -f %s/%s*.avg; fi",
#		    dirname, dirname, dirname, basename);
#system(cmdline);

# Define the common part of the test dataset
  top[1] = "Linear Polynomial3 Power Hill"
  top[2] = "1 1 1 1"
  top[3] = "0 " iAdvDir " 1 1"
  top[4] = iNTests " 0.95 2 0.1 0 " iConstVar " " zSeed " " iAdvDir
# Actual data starts on line 7; so, read 5 more lines
# to get to the right point.
  MyGetLine()
  MyGetLine()
  MyGetLine()
  MyGetLine()
  MyGetLine()
}

# Each pass creates a test avg file
{
  idataset++;
  sCount = sprintf("%04d", idataset);
  daxname = (basename "_" truebmd "_" sCount ".dax");
#  FName = dirname "/" basename "_" truebmd "_" sCount ".avg" ;
  FName = basename "_" truebmd "_" sCount ".avg" ;
  for (i=1; i<5; i++)
    print top[i] >> FName;
  print daxname >> FName;
  print "Dose N Mean Std" >> FName
  print $3,$4,$5,$6 >> FName
  print $7,$8,$9,$10 >> FName
  print $11,$12,$13,$14 >> FName
  print $15,$16,$17,$18 >> FName
  if ($19 != "") {
    print $19,$20,$21,$22 >> FName
    if ($23 != "") {
      print $23,$24,$25,$26 >> FName
    }
  }
  close(FName)
  if (idataset == iNTests) exit;
}

function MyGetLine() {
  if (getline <= 0) {
    m = "unexpected EOF or error"
    m = (m ": " ERRNO)
    print m > "/dev/stderr"
    exit
  }
}
