#!/bin/sh -e

# weitere nette gpsbabel-Tricks:
# http://wiki.openstreetmap.org/wiki/Using_filters_with_GPSBabel
#
# Darüber hinaus kann man einen Trick machen und längere Tracks in
# ACTIVE LOG speichern - sobald dieser Track dann allerdings wieder
# im Gerät gespeichert wird, hat er auch blos noch 500 Punkte ...
# siehe
# http://blog.gpsies.com/article/143/track-mit-mehr-als-500-punkten-auf-den-garmin-etrex-speichern

# maxtargetpoints=100000 # sehr große Anzahl == alles
maxtargetpoints=1000 # sehr große Anzahl == alles
# maxtargetpoints=500      # mehr als 500 kann man nicht zum Garmin hochladen
# maxtargetpoints=250        # warum auch immer, am 18.10.2012 waren es nur 250 Punkte

usage() { echo "Usage: $0 [-p <maxtargetpoints>]" 1>&2; exit 1; }

while getopts ":p:" p; do
    case "${p}" in
        p)
            tp=${OPTARG}
            if [ $tp -lt 0 -o $tp -gt 1000000 ] ; then
        	usage
            fi
            maxtargetpoints=$tp
            ;;
        *)
            usage
            ;;
    esac
done
shift $((OPTIND-1))

targetpoints=$maxtargetpoints

if [ $# -lt 1 ] ; then
	echo "Welcher Track?"
	exit 1
fi

name=$1
backup="$1~"

numpoints=`grep '^<trkpt' $name | wc -l`

if [ "$2" = "1/2" ] ; then
    # Anzahl der Punkte halbieren
    targetpoints=$((numpoints/2))
fi
if [ "$2" = "1/4" ] ; then
    # Anzahl der Punkte halbieren
    targetpoints=$((numpoints/4))
fi
if [ "$2" = "1/8" ] ; then
    # Anzahl der Punkte halbieren
    targetpoints=$((numpoints/8))
fi
if [ "$2" = "1/10" ] ; then
    # Anzahl der Punkte halbieren
    targetpoints=$((numpoints/10))
fi

tmpfile=`mktemp`

if [ $targetpoints -ne $maxtargetpoints ] ; then
    echo "Reduziere Track mit $numpoints auf $targetpoints Trackpunkte"
fi

gpsbabel -i gpx -f $name  -x simplify,count=$targetpoints -o gpx -F $tmpfile
mv $name $backup
grep -v '^[[:space:]]\+<time>.\+</time>$' $tmpfile | \
 sed -e '/<trkpt/{;N;s/\n *//;}' \
     -e '/<ele>/{;N;s/\n *//;}'  \
     -e 's/^[[:space:]]*//'      \
  > $name
#  sed -e 's/    /\t/g' -e 's/  //' \
#  tr -d '\n' \
# gpsbabel trägt aktuelles Datum ein ...
# settrackdate $name
touch -r $backup $name
