#!/bin/bash

# Run a set of strips of UTEP stations, concatenating output into one
# file

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
  }

# 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=$WEST
    done
    SOUTH=$(( $SOUTH + 1 ))
  done
  }

# cleanup from last run
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 29 70 30 119 &
do_loops 39 70 40 129 &
do_loops 32 78 45 81 &

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