# convert output from react to set of files = input to S display functions

# usage: $0 react_root_name

# remove points with very small values of concentration of any species
# perhaps -- covert negative to positive concentrations

usage="usage:  $0 react_root_name\n"

if [ $# -eq 0 ]
then
	echo $usage; exit 1
fi

if [ -r "$1.r" ]
then
	awkvar="filename=$1"
else
	echo $usage; exit 1
fi


if [ $1"x" != "x" ]
then
	case $1 in
	filename=*)	awkvar="$1";shift;;
	esac
fi

egrep -v 'e\-3[8-9]|e\-4[0-9]' $1.r |
awk -v $awkvar '
BEGIN		{
	col_file = filename ".col"
	dat_file = filename ".dat"
	label_file = filename ".lab"
	number = "^[-+]?([0-9]+[.]?[0-9]*|[.][0-9]+)" \
				"([eE][-+]?[0-9]+)?$"
}

/rate constant/	{
	getline
	gsub(/\t+/, " ")
	label = sprintf("%9.2e\t", $2)
	$1 = ""; $2 = ""
	label = label $0
	getline
	gsub(/\t+/, " ")
	while (NF > 0) {
		label = sprintf("%s;%9.2e\t", label, $2)
		$1 = ""; $2 = ""
		label = label $0
		getline
		gsub(/\t+/, " ")
	}
	gsub(/ +/, "", label)
	gsub(/\t+/, ",", label)
	gsub(/;/, " ", label)
	next
}

/^[ 	]*time/	{
	n_cols=NF
	n_rows = 1
	for (i=1;i<=n_cols; i++) {
		data[n_rows,i] = $i
		col[$i] = i
		print $i > col_file
	}
	flag = 1
	next
}

flag == 0	{
	next
}

$1 ~ number	{
	n_rows++
	for (i=1;i<=n_cols; i++) {
		data[n_rows,i] = $i
	}
	print $0 > dat_file
}

END	{
	# calculate halftime for last product 
	# == 2nd column of data matrix 
	# time == 1st column
	# 1st row is a list of column headers, 
	# 2nd row is the list of starting concentrations
	for (j = 3; j <= n_rows; j++) {
		if ((data[j,2] - data[2,2])/(data[n_rows,2] - data[2,2]) > 0.5){
			halftime = data[j-1,1] + \
				(data[j,1] - data[j-1,1]) * \
				(0.5 * (data[n_rows,2] - data[2,2]) + \
				data[2,2] - data[j-1,2]) / \
				(data[j,2] - data[j-1,2])
			break
		}
	}

	printf "Final Values:  E=%9.3e, S=%9.3e, (E+S)=%9.3e\n", 
		data[n_rows,col["E"]], data[n_rows,col["S"]], 
		data[n_rows,col["E"]] + data[n_rows,col["S"]] > label_file
	printf "%s t(1/2)=%9.3e, tau=%9.3e, 1/tau=%9.3e\n",
		data[1,2], halftime, halftime/0.691, 0.691/halftime > label_file
	printf "EBAR+SBAR %9.3e TAU %9.3e\n",
		data[n_rows,col["E"]] + data[n_rows,col["S"]], halftime/0.691 > label_file

	print label > label_file

	# time is the first column, and is skipped,
	# i.e., the row idents are the species
	for (i=2;i<=n_cols; i++) {
		# the first row of data[] is the list of column headers,
		# the second row is the list of starting concentrations,
		# the calculated time series starts at the third row
		if (i == 2 ) {
			label1 = sprintf("Start: %s=%9.3e", data[1,i], data[2,i])
			label2 = sprintf("End:   %s=%9.3e", data[1,i], data[n_rows,i])
		}
		else {
			label1 = sprintf("%s, %s=%9.3e", label1, data[1,i], data[2,i])
			label2 = sprintf("%s, %s=%9.3e", label2, data[1,i], data[n_rows,i])
		}
	}
	print label1 > label_file
	print label2 > label_file
}' -


