#!/bin/sh
#
############################################################################
#
# MODULE:       v.in.mapgen
#
# AUTHOR(S):    Andreas Lange, andreas.lange@rhein-main.de
#               Updated for GRASS 6 by Hamish Bowman
#
# PURPOSE:      Import data from Mapgen or Matlab into a GRASS vector map
#
# COPYRIGHT:    Original version (c) Andreas Lange
#               Updates by Hamish Bowman (c) 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.
#############################################################################
#
# REQUIREMENTS:  awk
#
# DATA AVAILABILITY: e.g., NOAA's Online Coastline Extractor
#                    http://www.ngdc.noaa.gov/mgg/shorelines/shorelines.html
#

#%Module
#%  description: Imports Mapgen or Matlab-ASCII vector maps into GRASS.
#%  keywords: vector, import
#%End
#%flag
#%  key: f
#%  description: Input map is in Matlab format
#%end
#%flag
#%  key: z
#%  description: Create a 3D vector points map from 3 column Matlab data 
#%end
#%option
#% key: input
#% type: string
#% gisprompt: old_file,file,input
#% description: Name of input file in Mapgen/Matlab format
#% required : yes
#%end
#%option
#% key: output
#% type: string
#% gisprompt: new,vector,vector
#% description: Name for output vector map (omit for display to stdout)
#% required : no
#%end

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

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

PROG=`basename "$0"`

#### check if we have awk
if [ ! -x "`which awk`" ] ; then
    g.message -e "awk required, please install awk or gawk first" 
    exit 1
fi

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

#### check if we have tac
# perhaps try `type -t` instead of `which`, as it is more POSIXy
if [ -x "`which tac`" ] ; then
   TAC=tac
else
   TAC=awk_tac
fi

awk_tac()
{
   awk '1 { last = NR; line[last] = $0; }
          END { for (i = last; i > 0; i--) { print line[i]; } }'
}

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

OPTS=""

FILE="$GIS_OPT_INPUT"
if [ ! -e "$FILE" ] ; then
   g.message -e "Input file <$FILE> not found."
   exit 1
fi

if [ -n "$GIS_OPT_OUTPUT" ] ; then
    NAME="$GIS_OPT_OUTPUT"
else
    unset NAME
fi


# -z implies -f
if [ $GIS_FLAG_Z -eq 1 ] && [ $GIS_FLAG_F -eq 0 ] ; then
   GIS_FLAG_F=1
fi

if [ $GIS_FLAG_Z -eq 1 ] ; then
  # make a 3D vector file
  do3D="-z"
else
  do3D=""
fi

#### setup temporary file
TMPFILE="`g.tempfile pid=$$`"
if [ $? -ne 0 ] || [ -z "$TMPFILE" ] ; then
    g.message -e "unable to create temporary files"
    exit 1
fi

#### trap ctrl-c so that we can clean up tmp
trap 'rm -f "$TMPFILE"' 2 3 15

#### create ascii vector file
if [ $GIS_FLAG_F -eq 1 ] ; then
  ## HB:  OLD v.in.mapgen.sh Matlab import command follows.
  ##    I have no idea what it's all about, so "new" matlab format will be
  ##    a series of x y with "nan nan" breaking lines. (as NOAA provides)
  ##  Old command:
  #  tac $FILE | $AWK 'BEGIN { FS="," ; R=0 }
  #    $1~/\d*/   { printf("L %d\n", R) }
  #    $1~/   .*/ { printf(" %lf %lf\n", $2, $1) ; ++R }
  #    $1~/END/   { }' | tac > "$TMPFILE"

  ## matlab format. Cleanse with NaN->nan and spaces to tabs,
  ##   and skip blank and comment lines
  grep -v '^#\|^$' "$FILE" | "$TAC" | awk '
    {print $1 "\t" $2 "\t" $3}
    END {if ($3~/[0-9Nna]/) print "NaN\tNaN\tNaN"
         else print "NaN\tNaN"}' | \
   tr 'N' 'n' | awk '
    BEGIN { FS="\t" ; R=0 }
    $1~/nan.*/ { printf("L %d\n", R) ; R=0 ; next }
    $1~/\d*\d*/ { printf(" %.15g %.15g %.15g\n", $1, $2, $3) ; ++R }
    END {;}' | \
   grep -v "^L 0$" | "$TAC" > "$TMPFILE"

else
  ## mapgen format.
  "$TAC" "$FILE" | awk '
    BEGIN { FS="\t" ; R=0 }
    $1~/#.*/ { printf("L %d\n", R) ; R=0 }
    $1~/\d*\.\d*/ { printf(" %.8f %.8f\n", $1, $2) ; ++R }
    END {;}' | "$TAC" > "$TMPFILE"
fi

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

#### process points list to ascii vector file (merge in vertices)
cat "${TMPFILE}" >> "${TMPFILE}.dig"

#### if no name for vector file given, cat to stdout
if [ -z "$NAME" ] ; then
    g.message "Output to stdout" 
    cat "${TMPFILE}.dig" 2>/dev/null
else
    #### import to binary vector file
    g.message "Importing with v.in.ascii ..." 
    v.in.ascii $do3D input="${TMPFILE}.dig" output="$NAME" format=standard

    #### check success/failure
    if [ $? -eq 0 ] ; then
	g.message message="\"$NAME@$MAPSET\" successfully created." 
    else
	g.message -e "An error occured on creating \"$NAME\" in mapset \"$MAPSET\", please check"'!'
    fi
fi

#### clean up the mess
rm -f "$TMPFILE" "${TMPFILE}.dig"

#### end
exit 0
