#!/bin/bash

MINIMUM_FREQUENCY=0
MAXIMUM_FREQUENCY=0
MAXIMUM_MISFIT=""

while [ "$1" ]; do
  case "$1" in
    "-min")
      shift
      MINIMUM_FREQUENCY=$1
    ;;
    "-max")
      shift
      MAXIMUM_FREQUENCY=$1
    ;;
    "-misfit")
      shift
      MAXIMUM_MISFIT=$1
    ;;
    "-h")
      echo "Usage: select_sh_peak_frequency [OPTIONS] <inreport> <outreport>"
      echo
      echo "Options:"
      echo "  -min     minimum frequency to select"
      echo "  -max     maximum frequency to select"
      echo "  -misfit  maximum misfit to select in inreport"
      echo
      echo "  Copyright (C) 2013 Marc Wathelet (marc@geopsy.org)"
      exit 0
    ;;
    *)
      break
    ;;
  esac
  shift
done

REPORT_FILE=$1
OUT_REPORT_FILE=$2

if [ -e "$OUT_REPORT_FILE" ]; then
  echo "Output report file $OUT_REPORT_FILE already exists"
  exit 2
fi
if [ -z "$REPORT_FILE" ]; then
  echo "Missing report file"
  exit 2
fi
if [ -z "$MAXIMUM_MISFIT" ]; then
  echo "Missing maximum misfit" 
  exit 2
fi
if [ "$MINIMUM_FREQUENCY" -eq 0 ] || [ "$MAXIMUM_FREQUENCY" -eq 0 ]; then
  echo "Missing minimum and/or maximum frequencies" 
  exit 2
fi

INDEX_FILE=$(tempfile)

gpdcreport $REPORT_FILE -m $MAXIMUM_MISFIT -nobugreport | gpsh -s frequency -min 0.1 -max 30 -n 200 -qp 100 -qs 50 -nobugreport | gpcurve -max-index -nobugreport | awk -v min=$MINIMUM_FREQUENCY -v max=$MAXIMUM_FREQUENCY '
/^# Layered model/ {
  sub(":", "", $4)
  i=$4 
}
!/^#/{
  f=0.1+(30-0.1)/(200-1)*$1
  if(f>=min && f<=max) {
    print i
  }
}' > $INDEX_FILE

cat $INDEX_FILE | gpdcreport -index $REPORT_FILE -o $OUT_REPORT_FILE
echo "$(cat $INDEX_FILE | wc -l) models selected and saved in $OUT_REPORT_FILE"
rm $INDEX_FILE
exit 0
