#\- extract [fmt=%n.m{e|f}] [fmt1=%n.m{e|f}] 
#		[list={#_#..|str_str..}]  [skip=n] 
#
# extract a list of values from the results file produced by run of react;
#
# NOTE: extract is a filter: <stdin extract >stdout
#
# fmt, fmt1, list, and skip are awk parameters;
#
# fmt, fmt1:
# the format can be selected by setting fmt for the species concentration and
# fmt1 for the time (the first value ouput);
# the format of the format string is that of printf's "e" or "f" format;
#
# list:
# the time is always printed; the species for which concentrations are
# printed can be selected by setting list to an underscore-separated list
# of species identifiers, either numeric or string;
#
# the defaults are to print all species, %12.5e;
#
# skip:
# obvious;
#
#
# example:
#	<filename extract -v fmt=%9.2e -v fmt1=8.2e -v list=1_2_7 -v skip=10
#
# NOTE: this code is _not_ hardened...(:^)

awk  $* '
BEGIN		{
	if (list) {
		num_list = split(list, dummy, "_")
		for (i = 1; i <= num_list; i++)
			list_elements[dummy[i]] = i
		if (list ~ /^[0-9_]+$/)
			number_type = 1
		else
			number_type = 0
	}
	if (fmt && !fmt1) fmt1 = fmt "   "
	if (!fmt) fmt = "%12.5e"
	if (!fmt1) fmt1 = "%12.5e   "
	header_fmt = fmt
	header_fmt1 = fmt1
	gsub(/\.[^ 	]*/, "s", header_fmt)
	gsub(/\.[^ 	]*/, "s", header_fmt1)
	number = "^[-+]?([0-9]+[.]?[0-9]*|[.][0-9]+)" \
				"([eE][-+]?[0-9]+)?$"
}

/^[ 	]*time/	{
	count = -2
	flag = 1
	time_string = $1
	$1 = ""
	num_species = split($0, species)
	for (i = 1; i <= num_species; i++) {
		species_id[species[i]] = i
	}
	printf header_fmt1, time_string
	for (i = 1; i < NF; i++) {
		if (list == "")
			printf header_fmt, $(i+1)
		else if (number_type && i in list_elements)
			printf header_fmt, $(i+1)
		else if (species[i] in list_elements) 
			printf header_fmt, $(i+1)
	}
	printf "\n"
	next
}

flag == 0	{
	next
}

$1 ~ number 	{
	count++
	if (skip > 1 && count > 0 && (count % skip)) next
	printf fmt1, $1
	for (i = 1; i < NF; i++) {
		if (list == "")
			printf fmt, $(i+1)
		else if (number_type && i in list_elements)
			printf fmt, $(i+1)
		else if (species[i] in list_elements) 
			printf fmt, $(i+1)
	}
	printf "\n"
}' 
