# $Source: /home/greatdev/src/analysis/convertc/RCS/convertc.awk,v $

# $Author: jwagner $

# $Revision: 1.5 $
# $Date: 2000/03/09 17:33:13 $
# $Locker:  $
#
# Description: This awk-Script converts concentrations (or any other 
# Description: numerical columns) automatically to an appropriate format
# Description: where the larges number should look like xxx.yyyyy
# Description: For this, three variables have to be set:
# Description: 	COLUMN:    The column to be analysed (starts with 1)
# Description:	MODCOLUMN: The list of columns to be modified 
# Description:			(comma seperated, starts with 1)	
# Description:	TMPFILE:   File to which the factor is exported (To
# Description:		   determine the new unit outside the script, this
# Description:		   way is a special workaround for ArcView.
# Description:		   Exporting to an environment variable would be 
# Description:		   easier but ArcView evaluates them only on StartUp

function inArray(x, a) 
{
	for (i in a)
	{	if (x == a[i])
		{	
			return 1
		}
	}

	return 0
}

BEGIN {
# initialize variables
	max = 0
	cnt = 0

# read indexes of columns to modify (starting with 1)
	split(MODCOLUMNS, columns,",")
	
#read the header
	getline line
	print line
}

{
# read lines and scan for maximum	

	line = $0
	numfields = split(line, field)
	fields[cnt] = line
	cnt+=1
	
	if (field[COLUMN] > max)
	{	max = field[COLUMN] 
	}
}

END {
# eval dimension of max
# This approach results in too high factors if max is exaclty dividable by 10:
# e.g. max = 1 --> factor = 1000 instead of 1 (1.0000000001 -> 1)

	EXPSHIFT = 2	# for GREAT-ER 1.0.2 to have a harmonic visualization of
			# low concentrations

	exponent = (log(max) / log(10) - EXPSHIFT) / 3

	if ( exponent < 0 )
		exponent = (int(exponent - 1.0))*(-3)
	else
		exponent = (int(exponent))*(-3)
		

	factor = 10^exponent

	for (i in fields) {
		fielddelimiter=""
 		numfields = split( fields[i], field)

		for (j=1; j<=numfields; j++) {
			if (inArray(j, columns))
				printf("%s%g", fielddelimiter,
							field[j]*factor)
			else	
				printf("%s%s", fielddelimiter, field[j])

			fielddelimiter = "\t"
		}

		printf("\n")

	}

	print factor > TMPFILE
}
