# convert output from react to set of files = input to xgobi

# usage: $0 [filename=xgobi_root_name] react_root_name.r

# if no first parameter (filename=xgobi_root_name) then set filename=$$=pid
# remove points with very small values of concentration of any species
# covert negative to positive concentrations

# brushcolor.list ==  ident:brushcolor
# 0 Red, 1 Green, 2 Yellow, 3 Orange, 4 YellowGreen, 5 HotPink, 6 SkyBlue,
# 7 SlateBlue, 8 Orchid, 9 Peru
#
# brushglyph.list ==  ident:glyph
# 0 point, 1 small plus, 2 medium plus, 3 large plus, 
# 4 small X, 5 medium X, 6 large X, 
# 7 small rectangle, 8 medium rectangle, 9 large rectangle, 
# 10 small circle, 11 medium circle, 12 large circle

awkvar="filename=$$"

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

egrep -v 'e\-3[8-9]|e\-[4-9][0-9]' $* |
awk -v $awkvar '
BEGIN		{
	split("Red Green Yellow Orange YellowGreen HotPink SkyBlue SlateBlue Orchid Peru", colors_list)
	col_file = filename ".col"
	glyphs_file = filename ".glyphs"
	dat_file = filename ".dat"
	label_file = filename ".label"
	row_file = filename ".row"
	colors_file = filename ".colors"
	number = "^[-+]?([0-9]+[.]?[0-9]*|[.][0-9]+)" \
				"([eE][-+]?[0-9]+)?$"
}

/rate constant/	{
	getline
	gsub(/\t+/, " ")
	label = sprintf("%g\t", $2)
	$1 = ""; $2 = ""
	label = label $0
	getline
	gsub(/\t+/, " ")
	while (NF > 0) {
		label = sprintf("%s;%g\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
	}
	flag = 1
	next
}

flag == 0	{
	next
}

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

END	{
	print label > label_file
	print "ident" > col_file
	print "time" > col_file
	print "concn" > col_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("%s=%g", data[1,i], data[2,i])
		else 
			label1 = sprintf("%s, %s=%g", label1, data[1,i], data[2,i])
		for (j=3;j<=n_rows; j++) {
			print data[1,i] > row_file
			print ((i-1)%12)+1 > glyphs_file
			print colors_list[((i-2)%10)+1] > colors_file
		}
	}
	print label1 > label_file
	for (i=2;i<=n_cols; i++) {
		for (j=3;j<=n_rows; j++) {
			if ( data[j,i] > 0 )
				print i, data[j,1], data[j,i] > dat_file
			else
				print i, data[j,1], -data[j,i] > dat_file
		}
	}
}' -


