## Awk Script: line2ace.awk
##
## Command Syntax: nawk -f line2ace.awk <line-oriented record file>
##
## Purpose: move selected fields from line records into .ace file format
##
## Input: line-oriented record data file in tabular format
##        (e.g. output file generated by ace2line.awk)
##        * data records delimited by end-of-line; fields by specified delimiter (tab);
##          set built-in AWK variables RS and FS, respectively, in the BEGIN section 
##          below for new assignments
##        * first record line starts with class name and then lists tag names that 
##          correspond to each field in input
##        * multiple values intended for .ace file separated by "$" in input field;
##          set variable "multi_sep" in the BEGIN section for new assignment
##        * each record line should start with an alpha-numeric character
##        * order of fields determines order of tags in .ace output
##
## Output: .ace-formatted data for all fields in input file -- for a single class
##         * if (tab-separated) field is null in first record, skip that field in 
##           .ace output
##         * tags ordered the same as fields in line-oriented input records
##
##
## See Also: ace2line.awk, ace_sel.awk
##
## Global Variables: 
##      multi_sep = "$"; multi-value separator for a single field in input
##
##      i, j -- numeric index
##      nth  -- number count of fields in output
##
##      tag_name[<nth>] = tag name corresponding to the nth field in input
##      multi_value[<nth>] = array of values for a single field
##
BEGIN {
	FS = "\t";
	multi_sep = "$"; 
	parsing_1st_record = 1;
}  # end of BEGIN

# processing .ace data file
$0 == "" || $0 ~ /^[^A-Za-z0-9]/ {
	# skip any line that doesn't not start with an alpha-numeric character;

	next;
}

parsing_1st_record == 1 {
	nth = 0;
	while (nth < NF) {
	  if ($nth == "") {
	    print "ERROR: invalid tag name in first record line; exit abnormally";
	    exit 1; 
	  }  # end of if

	  nth++;
	  tag_name[nth] = $nth;
	}  # end of while
	parsing_1st_record = 0;
	
	next;
}

NF != nth { 
	print "";
	print "WARING: incorrect number of data fields at input line " NR;
	print "        -- current record line is ignored";
	print "";

	next;
}
	
{       
	if ($1 == "") {
	  print "";
	  print "WARNING: required data missing at input line " NR; 
	  print "         -- current record line is ignored";
	  print "";       

	  next;
	} else {
	  print tag_name[1], ":", "\"" $1 "\"";
	}  # end of if ... else

	for (i = 2; i <= NF; i++) {
	  j = split($i, multi_value, multi_sep);
	  for ( ; j > 0; j--) {
	    if (multi_value[j] ~ /^[0-9]+$/) {
	      print tag_name[i], multi_value[j];
	    } else {
	      print tag_name[i], "\"" multi_value[j] "\"";
	    }  # end of if ... else
	  }  # end of for 
	
	}  # end of for
	
	print "";
}  

