#!/bin/sh  
# \
exec oagtclsh "$0" "$@"

# $Log: not supported by cvs2svn $
# Revision 1.2  2005/11/28 20:11:49  emery
# Added 2-line comment that describes the script.
#
# Revision 1.1  2003/10/17 22:46:37  emery
# First installation.
#

if [info exists env(OAG_TOP_DIR)] {
    set auto_path [linsert $auto_path 0 $env(OAG_TOP_DIR)/oag/apps/lib/$env(HOST_ARCH)]
} else {
    set auto_path [linsert $auto_path 0 /usr/local/oag/apps/lib/$env(HOST_ARCH)]
}

APSStandardSetup

# Averages the columns in a *.twi file.
# presently doesn't do multiple page files correctly.

set itemList ""
set input ""
set output ""
set args $argv
set usage "usage: averageOverElements -input <file> -output <file> -itemList \{list of items\}"
APSParseArguments {itemList input output}
if {![llength $itemList] || ![string length $input] || \
      ![string length $output]} {
    puts stderr $usage
    exit
}

# add lattice position
lappend itemList s

set option ""
set convertOption ""
set newItem ""
set lengthDefined 0
foreach item $itemList {
    if [regexp beta $item] {
        regsub {beta(.)} $item {alpha\1} otherItem
        if !$lengthDefined {
            append option "\"-def=col,Length,i_row 0 == ? s : s i_row 1 - &s \\\[ - \\\$\""
            set lengthDefined 1
        }
        append option " \"-def=col,${item}Entrance,i_row 0 == ? ${item} : i_row 1 - &${item} \\\[ \$\""
        append option " \"-def=col,${otherItem}Entrance,i_row 0 == ? ${otherItem} : i_row 1 - &${otherItem} \\\[ \\\$\""
        append option " \"-def=col,${item}Average,${item} ${item}Entrance + 2 / ${otherItem} ${otherItem}Entrance - 6 / Length * +\""
        lappend removableItem ${item}Entrance ${otherItem}Entrance Length
    } else {
    # regular quantity to average
        append option " \"-def=col,${item}Entrance,i_row 0 == ? ${item} : i_row 1 - &${item} \\\[ \\\$\""
        append option " \"-def=col,${item}Average,${item} ${item}Entrance + 2 /\""
        lappend removableItem ${item}Entrance
    }
}

eval exec sddssort $input -pipe=out -column=s \
| sddsprocess -pipe $option \
| sddsconvert -pipe=in $output -noWarning \
  -delete=col,[join $removableItem ,] 

exit
