#!/bin/bash
# 
############################################################################
#
# MODULE:      v.in.gpsbabel
#
# PURPOSE:     Import GPS data from a GPS receiver or file into a GRASS
#	       vector map using gpsbabel
#
# COPYRIGHT:   (c) 2000-2007 the GRASS Development Team
#	       This program is free software under the GNU General Public
#	       License (>=v2). Read the file COPYING that comes with GRASS
#	       for details.
#
# AUTHORS:     Claudio Porta & Lucio Davide Spano, students of Computer 
#		  Science, University of Pisa (Italy).
#		Commission from Faunalia Pontedera (PI)
#
#               With updates by Markus Neteler and Hamish Bowman
#
#		Based on v.in.garmin for GRASS 6 by Hamish Bowman
#		and v.in.garmin.sh for GRASS 5 by Andreas Lange
#
#############################################################################
#
# REQUIREMENTS:
#      -  gpsbabel from:
#	     http://gpsbabel.sourceforge.net
#      -  unix tools: grep, cat, tac, cut, paste, awk/nawk/gawk, sed
#      -  cs2cs from PROJ.4    http://proj.maptools.org/
#
#      - report supported formats:
#	 gpsbabel -^2 | tr '\t' ';' | sort -t';' -k3
#
#############################################################################

#%Module
#%  description: Import waypoints, routes, and tracks from a GPS receiver or GPS download file into a vector map.
#%  keywords: vector, import, GPS
#%End
#%flag
#%  key: v
#%  description: Verbose mode
#%end
#%flag
#%  key: w
#%  description: Import waypoints
#%end
#%flag
#%  key: r
#%  description: Import routes
#%end
#%flag
#%  key: t
#%  description: Import track
#%end
#%flag
#%  key: p
#%  description: Force vertices of track or route data as points
#%end
#%flag
#%  key: k
#%  description: Do not attempt projection transform from WGS84
#%end
#%option
#% key: input
#% type: string
#% description: Device or file used to import data
#% answer: /dev/gps
#%end
#%option
#% key: output
#% type: string
#% gisprompt: new,vector,vector
#% description: Name for new vector map (omit for display to stdout)
#% required : no
#%end
#%option
#% key: format
#% type: string
#% description: Format of GPS input data (use gpsbabel supported formats)
#% answer: garmin
#%end
#%option
#% key: proj
#% type: string
#% description: Projection of input data (PROJ.4 style), if not set Lat/Lon WGS84 is assumed
#% required: no
#%end

if [ -z "$GISBASE" ] ; then
    echo "You must be in GRASS GIS to run this program." 1>&2
    exit 1
fi

if [ "$1" != "@ARGS_PARSED@" ] ; then
  exec g.parser "$0" "$@"
fi

# set environment so that awk works properly in all languages
unset LC_ALL
LC_NUMERIC=C
export LC_NUMERIC

eval `g.gisenv`
: ${GISBASE?} ${GISDBASE?} ${LOCATION_NAME?} ${MAPSET?}
LOCATION="$GISDBASE"/"$LOCATION_NAME"/"$MAPSET"

PROG=`basename $0`

#### check for gpsbabel 
 if [ ! -x "`which gpsbabel`" ] ; then
    echo "ERROR: The gpsbabel program was not found, please install it first." 1>&2
    echo "       http://gpsbabel.sourceforge.net" 1>&2
    exit 1
fi

#### check for cs2cs
if [ ! -x "`which cs2cs`" ] ; then
    echo "ERROR: The cs2cs program was not found, please install it first." 1>&2
    echo "       http://proj.maptools.org" 1>&2
    exit 1
fi

#### check if we have awk
if [ ! -x "`which awk`" ] ; then
    echo "ERROR: awk is required, please install awk or gawk first." 1>&2
    exit 1
fi

#### set temporary files
TMP="`g.tempfile pid=$$`"
if [ $? -ne 0 ] || [ -z "$TMP" ] ; then
    echo "ERROR: Unable to create temporary files" 1>&2
    exit 1
fi

#### trap ctrl-c so that we can clean up tmp
trap 'rm -f "${TMP}."*' 2 3 15


#### process command line arguments 
WPT=1 ; RTE=0 ; TRK=0 ; KEEP_WGS84=0; VERBOSE=0


if [ $GIS_FLAG_V -eq 1 ] ; then
    VERBOSE=1
    PROGVERBOSE="-D 1"
fi

if [ -n "$GIS_OPT_OUTPUT" ] ; then
    NAME="$GIS_OPT_OUTPUT"
    if [ $VERBOSE -eq 1 ] ; then
	echo "output=$NAME" 1>&2
    fi
fi
if [ -n "$GIS_OPT_INPUT" ] ; then
    GPSdevice="-f $GIS_OPT_INPUT"
    if [ $VERBOSE -eq 1 ] ; then
	echo "file=$GIS_OPT_INPUT" 1>&2
    fi
fi


if [ $GIS_FLAG_W -eq 1 ] && ([ $GIS_FLAG_R -eq 1 ] || [ $GIS_FLAG_T -eq 1 ]) ; then
    echo "ERROR: One feature at a time please. Use v.patch if you need to combine them." 1>&2
    rm -f "${TMP}"
    exit 1
fi
# logic eludes me at pressent..  [combine with above]
if [ $GIS_FLAG_R -eq 1 ] && [ $GIS_FLAG_T -eq 1 ] ; then
    echo "ERROR: One feature at a time please. Use v.patch if you need to combine them." 1>&2
    rm -f "${TMP}"
    exit 1
fi

CREATE_POINTS=0

if [ $GIS_FLAG_W -eq 1 ] ; then
    WPT=1
    CREATE_POINTS=1
elif [ $GIS_FLAG_R -eq 1 ] ; then
    WPT=0
    RTE=1
    CREATE_POINTS=0
elif [ $GIS_FLAG_T -eq 1 ] ; then
    WPT=0
    TRK=1
    CREATE_POINTS=0
fi

if [ $GIS_FLAG_P -eq 1 ] ; then
    CREATE_POINTS=1
fi
if [ $GIS_FLAG_K -eq 1 ] ; then
    KEEP_WGS84=1
fi

if [ $GIS_FLAG_W -eq 0 ] && [ $GIS_FLAG_R -eq 0 ] && [ $GIS_FLAG_T -eq 0 ] ; then
    echo "WARNING: No features requested for download. Assuming waypoints." 1>&2
    WPT=1
    CREATE_POINTS=1
fi


#### set up projection info
if [ -n "$GIS_OPT_PROJ" ] ; then
    IN_PROJ="$GIS_OPT_PROJ"
else
    IN_PROJ="+proj=longlat +towgs84=0.000,0.000,0.000"
fi
OUT_PROJ="`g.proj -jf`"
PROJ_TYPE=`g.region -p | grep 'projection' | cut -f2 -d" "`

if [ $PROJ_TYPE -eq 0 ] && [ $KEEP_WGS84 -ne 1 ] ; then
    echo "ERROR: Cannot project to a XY location." 1>&2
    rm -f "${TMP}"
    exit 1
fi

STYLE="$GISBASE/etc/grass_write_ascii.style"

# How to do it
#
# gpsbabel [options] -i INTYPE -f INFILE -o OUTTYPE -F OUTFILE
# gpsbabel [options] -i INTYPE -o OUTTYPE INFILE [OUTFILE]
#
#(GPX file example):
# gpsbabel -w -i gpx -o xcsv,style=grass_write_ascii.style outfile.csv

#### receive data ...

if [ $CREATE_POINTS -eq 1 ] ; then
    if [ $WPT -eq 1 ] ; then
	echo "Loading Waypoints from <$GIS_OPT_INPUT> ..." 1>&2
	TYPE="-w"
	EXITCODE=$?
    elif [ $RTE -eq 1 ] ; then
	echo "Loading Routes as points from <$GIS_OPT_INPUT> ..." 1>&2
	TYPE="-r"
    elif [ $TRK -eq 1 ] ; then
	echo "Loading Tracks as points from <$GIS_OPT_INPUT> ..." 1>&2
	TYPE="-t"
    fi

    gpsbabel $TYPE -i $GIS_OPT_FORMAT $GPSdevice $PROGVERBOSE \
	-o xcsv,style="$STYLE" -F "$TMP".xcsv
    EXITCODE=$?

    if [ "`wc -l < "${TMP}.xcsv"`" -eq 0 ] ; then
	echo 'WARNING: No data! Exiting.' 1>&2
	rm -f "${TMP}."*
	exit 0
    fi

else
    if [ $RTE -eq 1 ] ; then
	echo "Loading Routes from <$GIS_OPT_INPUT> ..." 1>&2
	TYPE="-r"
	EXITCODE=$?
    elif [ $TRK -eq 1 ] ; then
	echo "Loading Tracks from <$GIS_OPT_INPUT> ..." 1>&2
	TYPE="-t"
	EXITCODE=$?
    fi
    gpsbabel $TYPE -i $GIS_OPT_FORMAT $GPSdevice $PROGVERBOSE \
	-o gpx -F "$TMP".gpx
    EXITCODE=$?

    if [ $EXITCODE -eq 0 ] && \
       [ "`grep -c '<rte>' "${TMP}.gpx"`" -eq 0 ] && \
       [ "`grep -c '<trk>' "${TMP}.gpx"`" -eq 0 ] ; then
	echo 'ERROR No data! Exiting.' 1>&2
	rm -f "${TMP}."*
	exit 0
    fi
fi

#### check success/failure
if [ $EXITCODE -ne 0 ] ; then
    echo "ERROR: Error loading data from gpsbabel" 1>&2
    rm -f "${TMP}."*
    exit 1
fi


###################################
if [ $CREATE_POINTS -eq 1 ] ; then
###################################

    cat "${TMP}.xcsv" | cut -f 1,2 -d '|'| tr '|' ' '  > "$TMP".base
# FIXME: if last field (comments) is empty it causes a not-enough fields error in v.in.ascii

    cat "${TMP}.xcsv" | tr '+' '|' | cut -f3,4,5,6 -d '|' | \
	sed -e 's/-99999999.000000//' -e 's/|$/|_/' \
	    -e 's/01\/01\/1970|00:00:00 AM/|/' > "$TMP".attributes


    #### reproject if needed
    if [ "$IN_PROJ" = "$OUT_PROJ" ] || [ $KEEP_WGS84 -eq 1 ] ; then
	echo "No projection transformation performed" 1>&2
	cp "${TMP}.base" "${TMP}.P_base"
    else
	echo "Attempting waypoint projection transform with cs2cs" 1>&2
	cs2cs -f %.7f $IN_PROJ +to $OUT_PROJ < "${TMP}.base" > "${TMP}.P_base"
	EXITCODE=$?
	# check if transform REALLY worked (e.g. when the grid file is not found)
	BAD_PTS="`grep -c "^*" "${TMP}.P_base"`"
	if [ "$BAD_PTS" -gt 0 ] ; then
	    echo 1>&2
	    echo "WARNING: $BAD_PTS point(s) failed reprojection." 1>&2
	    EXITCODE=1
	fi
	if [ $EXITCODE -ne 0 ] ; then
	    echo "WARNING: Projection transform failed, retaining WGS84" 1>&2
	    echo 1>&2
	    cp -f "${TMP}.base" "${TMP}.P_base"
	fi
    fi

    cat "${TMP}.P_base" | awk '{print $1 "|" $2}' > "${TMP}.vertices"

    #### and put back together
    # wpt list:   x|y|<attr1>|...|<attr n>
    paste -d"|" "$TMP".vertices "$TMP".attributes > "$TMP".asc

    #### output or import
    if [ -z "$NAME" ] ; then
	echo "ASCII file redirected to stdout" 1>&2
	cat "${TMP}.asc" 2> /dev/null
    else
	#### import into new points file
	if [ $WPT -eq 1 ] ; then
	    echo "Importing Waypoints..." 1>&2
	elif [ $RTE -eq 1 ] ; then
	    echo "Importing Routes as points..." 1>&2
	elif [ $TRK -eq 1 ] ; then
	    echo "Importing Tracks as points..." 1>&2
	fi

	cat "${TMP}.asc" | v.in.ascii output="$NAME" cat=0 \
	  columns='x double precision, y double precision, altitude double precision, gmt_date varchar(10), gmt_time varchar(11), comments varchar(40)'
	EXITCODE=$?

	# EXITCODE also used at pgm termination below!
	if [ $EXITCODE -ne 0 ] ; then
	    echo "ERROR: While Importing data with v.in.ascii" 1>&2
	    rm -f "${TMP}."*
	    exit 1
	fi

    fi


#####################
else # CREATE_LINES
#####################

    #### prepare line components
    if [ $RTE -eq 1 ] ; then
	
	# this part is quite difficult using gpx... I'll explain all I've done
	# if someone has any suggest please mail!!!!

	# list of bytes where routes finish
	cat "$TMP.gpx" | grep -n "</rte>" > "$TMP.bytes"
	# number of routes
	cat "$TMP.bytes" | grep -c "</rte>" > "$TMP.var"
	ROUTE_NUMBER=0 
	read ROUTE_NUMBER < "$TMP.var" # route number to process
	READ_BYTES=0 # offset of bytes already read
	cp "$TMP.gpx" "$TMP.gpx2" # file to be "eaten" by head commands in while 
	ROUTE_ID=0 # route identifier

	while [ "$ROUTE_NUMBER" -gt 0 ] ; do
	    head -n 1 "$TMP.bytes" | cut -f 1 -d ':'> "$TMP.var"
	    END_BYTE=0
	    read END_BYTE < "$TMP.var" # this route ends at END_BYTE in $TMP.gpx file

	    TO_READ=0
	    TO_READ="`expr $END_BYTE - $READ_BYTES`"    # bytes to read from $TMP.gpx2 file 
	    READ_BYTES="`expr $READ_BYTES + $TO_READ`"  # update readed bytes

	    # list of points in route
	    head -n $TO_READ "$TMP.gpx2" | grep "<rtept" > "$TMP.points" 
	    POINTS=0 # number of points in route
	    cat "$TMP.points" | grep -c "<rtept" > "$TMP.var"
	    read POINTS < "$TMP.var"
	    echo "L $POINTS 1" >> "$TMP.base"
	    # read lat lon data
	    cat "$TMP.points" |cut -f2 -d'<'| cut -f2,3 -d ' ' | cut -f2,4 -d '"'|tr '"' '\t'> "$TMP.latlon"
	    cat "$TMP.latlon" |tr ',' '.'| awk '{printf(" %s %s\n", $2, $1) }'>> "$TMP.base"
	    # create attribute line
	    head -n $TO_READ "$TMP.gpx2"| grep -n "<rtept" | head -n 1| cut -f1 -d ':'> "$TMP.var"
	    OFFSET=0
	    read OFFSET < "$TMP.var"
	    head -n $OFFSET "$TMP.gpx2"> "$TMP.rte_attr"
	    # read needed attributes
	    ROUTE_ID="`expr $ROUTE_ID + 1`"
	    cat "$TMP.rte_attr"| grep "<number" | tail -n 1 | cut -f2 -d'<' | cut -f2 -d'>' > "$TMP.var"
	    NUMBER=0
	    read NUMBER < "$TMP.var" # read the route number
	    cat "$TMP.rte_attr"| grep "<name" | tail -n 1 | cut -f2 -d'<' | cut -f2 -d'>' > "$TMP.var"
	    R_NAME=""
	    read R_NAME < "$TMP.var" # read the route name

	    OFFSET="`expr $TO_READ - $OFFSET`"
	    head -n $TO_READ "$TMP.gpx2" | tail -n $OFFSET | grep "<name" | head -n 1 | cut -f2 -d'<' | cut -f2 -d'>' > "$TMP.var"
	    START_PNT=""
	    read START_PNT < "$TMP.var" # read the name of start point

	    # check that numberic values don't try and pass an empty string
### variable names don't line up with column names ?!
	    if [ -z "$ROUTE_ID" ] ; then
		ROUTE_ID="NULL"
        	echo "WARNING: Route $ROUTE_NUMBER: category number was empty. Bug?" 1>&2
	    fi
	    if [ -z "$NUMBER" ] ; then
		NUMBER="NULL"
		echo "WARNING: Route $ROUTE_NUMBER: route ID was empty. Bug?" 1>&2
	    fi

	    echo "$ROUTE_ID|$NUMBER|$R_NAME|$START_PNT" >> "$TMP.route_atts"

	    ROUTE_NUMBER="`expr $ROUTE_NUMBER - 1`"

	    # eat files
	    tail -n $ROUTE_NUMBER "$TMP.bytes" > "$TMP.bytes2"
	    mv "$TMP.bytes2" "$TMP.bytes"
	    head -n $TO_READ "$TMP.gpx2" > "$TMP.points"
	    B_GPX=0
	    wc -c < "$TMP.gpx2" > "$TMP.var"
	    read B_GPX < "$TMP.var"
	    B_PNT=0
	    wc -c < "$TMP.points" > "$TMP.var"
	    read B_PNT < "$TMP.var"
	    TO_READ="`expr $B_GPX - $B_PNT`"
	    tail -c $TO_READ "$TMP.gpx2" > "$TMP.points"
	    mv "$TMP.points" "$TMP.gpx2"
	done
	# create attr table: cat(int), id number(int 0-19), name varchar(16+), starting_wpt(varchar 10)
	ATTR_FILE="${TMP}.route_atts"
	ATTR_COLS='cat int, route_id int, name varchar(40), start_wpt varchar(40)'
    fi

    if [ $TRK -eq 1 ] ; then

	# list of bytes where tracks finish
	cat "$TMP.gpx" | grep -n "</trkseg>" > "$TMP.bytes"
	# number of tracks
	cat "$TMP.bytes" | grep -c "</trkseg>" > "$TMP.var"
	TRACK_NUMBER=0 
	read TRACK_NUMBER < "$TMP.var" # route number to process
	READ_BYTES=0 # offset of bytes already read
	cp "$TMP.gpx" "$TMP.gpx2" # file to be "eaten" by head commands in while 
	TRACK_ID=0 # track identifier
	while [ "$TRACK_NUMBER" -gt 0 ] ; do
	    head -n 1 "$TMP.bytes" | cut -f 1 -d ':'> "$TMP.var"
	    END_BYTE=0
	    read END_BYTE < "$TMP.var" # this route ends at END_BYTE in $TMP.gpx file
	    TO_READ=0

	    TO_READ="`expr $END_BYTE - $READ_BYTES`"    # bytes to read from $TMP.gpx2 file 
	    READ_BYTES="`expr $READ_BYTES + $TO_READ`"  # update readed bytes

	    # list of points in route
	    head -n $TO_READ "$TMP.gpx2" | grep "<trkpt" > "$TMP.points" 
	    POINTS=0 # number of points in track 
	    cat "$TMP.points" | grep -c "<trkpt" > "$TMP.var"
	    read POINTS < "$TMP.var"
	    echo "L $POINTS 1" >> "$TMP.base"
	    # read lat lon data
	    cat "$TMP.points" |cut -f2 -d'<'| cut -f2,3 -d ' ' | cut -f2,4 -d '"'|tr '"' '\t'> "$TMP.latlon"
	    cat "$TMP.latlon" |tr ',' '.'| awk '{printf(" %s %s\n", $2, $1) }'>> "$TMP.base"
	    # create attribute line
	    head -n $TO_READ "$TMP.gpx2"| grep -n "<trk" | head -n 1| cut -f1 -d ':'> "$TMP.var"
	    OFFSET=0
	    read OFFSET < "$TMP.var"
	    S_LAT=""
	    head -n 1 "$TMP.latlon" | cut -f1 > "$TMP.var"
	    read S_LAT < "$TMP.var"
	    S_LON=""
	    head -n 1 "$TMP.latlon" | cut -f2 > "$TMP.var"
	    read S_LON < "$TMP.var"
	    E_LAT=""
	    tail -n 1 "$TMP.latlon" | cut -f1 > "$TMP.var"
	    read E_LAT < "$TMP.var"
	    E_LON=""
	    tail -n 1 "$TMP.latlon" | cut -f2 > "$TMP.var"
	    read E_LON < "$TMP.var"

	    OFFSET="`expr $TO_READ - $OFFSET`"

	    head -n $TO_READ "$TMP.gpx2" | tail -n $OFFSET | grep "<time" > "$TMP.time"
	    S_TIME=""
	    head -n 1 "$TMP.time"| cut -f 2 -d'>'| cut -f1 -d'<'> "$TMP.var"
	    read S_TIME < "$TMP.var"
	    E_TIME=""
	    tail -n 1 "$TMP.time"| cut -f 2 -d'>'| cut -f1 -d'<'> "$TMP.var"
	    read E_TIME < "$TMP.var"

	    TRACK_ID="`expr $TRACK_ID + 1`"

	    # check that numberic values don't try and pass an empty string
	    if [ -z "$TRACK_ID" ] ; then
		TRACK_ID="NULL"
		echo "WARNING: Track $TRACK_NUMBER: category number was empty. Bug?" 1>&2
	    fi
	    if [ -z "$S_LAT" ] ; then
		S_LAT="NULL"
		echo "WARNING: Track $TRACK_NUMBER:  starting lat was empty. Bug?" 1>&2
	    fi
	    if [ -z "$S_LON" ] ; then
		S_LON="NULL"
		echo "WARNING: Track $TRACK_NUMBER:  starting lon was empty. Bug?" 1>&2
	    fi
	    if [ -z "$E_LAT" ] ; then
		E_LAT="NULL"
		echo "WARNING: Track $TRACK_NUMBER:  ending lat was empty. Bug?" 1>&2
	    fi
	    if [ -z "$E_LON" ] ; then
		E_LON="NULL"
		echo "WARNING: Track $TRACK_NUMBER:  ending lon was empty. Bug?" 1>&2
	    fi

	    echo "$TRACK_ID|$S_TIME|$S_LAT|$S_LON|$E_TIME|$E_LAT|$E_LON" >> "$TMP.track_atts"

	    TRACK_NUMBER="`expr $TRACK_NUMBER - 1`"

	    # eat files
	    tail -n $TRACK_NUMBER "$TMP.bytes" > "$TMP.bytes2"
	    mv "$TMP.bytes2" "$TMP.bytes"
	    head -n $TO_READ "$TMP.gpx2" > "$TMP.points"
	    B_GPX=0
	    wc -c < "$TMP.gpx2" > "$TMP.var"
	    read B_GPX < "$TMP.var"
	    B_PNT=0
	    wc -c < "$TMP.points" > "$TMP.var"
	    read B_PNT < "$TMP.var"

	    TO_READ="`expr $B_GPX - $B_PNT`"
	    
	    tail -c $TO_READ "$TMP.gpx2" > "$TMP.points"
	    mv "$TMP.points" "$TMP.gpx2"
	done

	# create attr table: cat(int), start_time varchar(40), start_lat(double precision), start_lon(double precision), \
	#			end_time varchar(40), end_lat(double precision), end_lon(double precision)
	
	ATTR_FILE="${TMP}.track_atts"
	ATTR_COLS='cat int, start_time varchar(40), start_lat double precision, start_lon double precision, end_time varchar(40), end_lat double precision, end_lon double precision'
    fi


    #### reproject if needed
    if [ "$IN_PROJ" = "$OUT_PROJ" ] || [ $KEEP_WGS84 -eq 1 ] ; then
	echo "No projection transformation performed" 1>&2
	cat "${TMP}.base" | awk 'BEGIN {;} $1=="L" { print } ; \
	    $1!="L" { " %s %s\n", $1, $2) } END {;}' > "${TMP}.P_base"
    else
	echo "Attempting waypoint projection transform with cs2cs" 1>&2
	cs2cs -tL -f %.7f $IN_PROJ +to $OUT_PROJ < "${TMP}.base" > "${TMP}.P_mid"
	EXITCODE=$?
	 # check if transform REALLY worked (e.g. grid file not found)
	 BAD_PTS="`grep -c "^*" "${TMP}.P_mid"`"
	if [ "$BAD_PTS" -gt 0 ] ; then
	    echo 1>&2
	    echo "WARNING: $BAD_PTS vertices failed reprojection." 1>&2
	    EXITCODE=1
	fi
	if [ $EXITCODE -ne 0 ] ; then
	    echo "Projection transform failed, retaining WGS84" 1>&2
	    echo 1>&2
	    cat "${TMP}.base" | awk 'BEGIN {;} $1=="L" { print } ; \
		$1!="L" { printf(" %s %s\n", $1, $2) } END {;}' > "${TMP}.P_base"
	else
	    cat "${TMP}.P_mid" | awk 'BEGIN {;} $1=="L" { print } ; \
		$1!="L" { printf(" %s %s\n", $1, $2) } END {;}' > "${TMP}.P_base"
	fi
    fi

    # add category numbers
    cat "${TMP}.P_base" | awk 'BEGIN { FS=" " ; R=0 } \
	$1=="L" { printf(" 1 %d\nL %d 1\n", R, $2) ; ++R } ; \
	$1!="L" { print } END { printf(" 1 %d\n", R) }' | sed -e '1d' > "${TMP}.P_baseC"


    #### create digit header
    cat << EOF > "${TMP}.dig"
ORGANIZATION: GRASSroots organization
DIGIT DATE:   `date +%D`
DIGIT NAME:   $PROG
MAP NAME:     $NAME
MAP DATE:     `date +%Y`
MAP SCALE:    1
OTHER INFO:   Imported by `echo $USER@$HOSTNAME`
ZONE:	 0
MAP THRESH:   0
VERTI:
EOF

    #### merge in vertices
#HB#?? locale test fixed this
    cat "${TMP}.P_baseC" | tr ',' '.' >> "${TMP}.dig"

    #### if no name for vector file given, cat to stdout
    if [ -z "$NAME" ] ; then
	echo "ASCII file redirected to stdout" 1>&2
	cat "${TMP}.dig" 2> /dev/null
    else
	#### import to binary vector file 
	echo "Importing with v.in.ascii" 1>&2
	v.in.ascii format=standard output="$NAME" input="${TMP}.dig"

	#### check success/failure
	if [ $? -eq 0 ] ; then
	    echo "Line vector <$NAME> successfully created." 1>&2
	else
	    echo 'ERROR: An error occured on creating <$NAME>, please check!' 1>&2
	    exit 1
	fi

	## create db links if they don't exist  (Markus made it automatic now? MN: yes.)
	DRIVER="`db.connect -p | grep '^driver:' | cut -f2 -d:`"
	DATABASE="`db.connect -p | grep '^database:' | cut -f2 -d:`"
	if [ "$DRIVER" = "(null)" ] || [ "$DATABASE" = "(null)" ] ; then
	    echo "Setting default database driver to DBF." 1>&2
	    db.connect driver=dbf database='$GISDBASE/$LOCATION_NAME/$MAPSET/dbf/'
	fi
	DRIVER="`db.connect -p | grep '^driver:' | cut -f2 -d:`"
	if [ "$DRIVER" = "dbf" ] && [ ! -d "$LOCATION/dbf/" ] ; then
	    mkdir "$LOCATION/dbf/"
	fi

	echo "Creating new table.." 1>&2
	echo "CREATE TABLE $NAME ($ATTR_COLS)" | db.execute

	echo "Populating table with attributes.." 1>&2
	# echo "COPY $NAME FROM '$ATTR_FILE'" | db.execute

	# "COPY table FROM 'filename.txt'" does not work for DBF and there is no
	#   db.in.ascii yet, so we use a hack ...

### <hack>
	if [ $RTE -eq 1 ] ; then
	    # =>  echo "INSERT INTO $NAME VALUES (2, 1, 'AB', 'B')" | db.execute
	    cat "$ATTR_FILE" | \
	      awk -F'|' '{
		printf("echo \"INSERT INTO $NAME VALUES (%d, %d, ^%s^, ^%s^)\" | db.execute\n", $1, $2, $3, $4) }' \
		    | tr '^' \' > "$ATTR_FILE"_exe
	fi
	if [ $TRK -eq 1 ] ; then
	    # =>  echo "INSERT INTO $NAME VALUES ()" | db.execute
	    cat "$ATTR_FILE" | \
	      awk -F'|' '{
		printf("echo \"INSERT INTO $NAME VALUES (%d, ^%s^, %s, %s, ^%s^, %s, %s)\" | db.execute\n", $1, $2, $3, $4, $5, $6, $7) }' \
		    | tr '^' \' > "$ATTR_FILE"_exe
	fi

	. "$ATTR_FILE"_exe
### </hack>

	echo "Connecting attribute table to vector file.." 1>&2
	v.db.connect map="$NAME" table="$NAME"
	EXITCODE=$?
    fi

fi  # if CREATE_POINTS or CREATE_LINES


# list column names
if [ $VERBOSE -eq 1 ] && [ -n "$NAME" ] ; then
    echo "<$NAME> columns:"
    db.columns "$NAME"
fi


#### clean up the mess
rm -f "${TMP}."* "${TMP}"

#### end
echo "Done." 1>&2

exit $EXITCODE
