#!/bin/bash

# Run ALL the UTEP stations in 1x1 deg chunks, concatenating output into one
# file for comparison with UTEP supplied terrain correction values...

OUTPUT=UTEP.my_tc.all

function run_tc() {
  local N=$1 S=$2 E=$3 W=$4
  local STNFILE="all/allutep_$N-${S}_$E-$W"
  local OUT=${STNFILE}.tc
  # if output file exists and is non-zero size, return
  if [ -s $OUT ]; then
    echo $OUT already exists, skipping...
    return
  fi
  echo "# current block: $N to $S, $E to $W" > $OUT
  ./grab_stns $N $S $E $W > $STNFILE
  time ../terrain $STNFILE >> $OUT 2>>tc_out_allUTEP
  #echo $N $S $E $W $STNFILE $OUT
  }

# loop through a number of 1x1 deg blocks
function do_loops() {
  local SOUTH=$1 S_EAST=$2 END_S=$3 END_E=$4
  local EAST=$2
  while [ $SOUTH -lt $END_S ]; do
    NORTH=$(( $SOUTH + 1 ))
    EAST=$S_EAST
    while [ $EAST -lt $END_E ]; do
      WEST=$(( $EAST + 1 ))
      run_tc  $NORTH $SOUTH -$EAST -$WEST
      EAST=$(( $EAST + 1 ))
    done
    SOUTH=$(( $SOUTH + 1 ))
  done
  }

# cleanup from last run
#rm all/allutep_*
echo `date` > tc_out_allUTEP

echo "# Automated run of all blocks of UTEP stations for TC testing." > $OUTPUT
# run small blocks; this is expected to be run as a bg nohup'd task, so
# fire up 3 groups looping chunks; let each chunk run
# as-fast-as-possible so always have some running....

do_loops 20 70 35 119 &	# 20-30 has many blocks w/no stns
do_loops 35 70 42 129 & # most stations in 35-45 zone
do_loops 42 70 50 129 &

# wait for all terrain corrections to finish, then cat em together
wait
cat all/allutep_*.tc >> $OUTPUT
