#!/bin/sh
############################################################################
#
# MODULE:       v.dissolve
# AUTHOR:       M. Hamish Bowman, Dept. Marine Science, Otago Univeristy,
#                 New Zealand
#               Markus Neteler for column support
# PURPOSE:      Dissolve common boundaries between areas with common cat
#                 (frontend to v.extract -d)
# COPYRIGHT:    (c) 2006 Hamish Bowman, and 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.
#
#############################################################################

#%Module
#% description: Dissolve boundaries between adjacent areas sharing a common category number or attribute
#% keywords: vector, area, dissolve
#%End

#%option
#% key: input
#% type: string
#% gisprompt: old,vector,vector
#% key_desc: name
#% description: Name of input vector map 
#% required: yes
#%end

#%option
#% key: output
#% type: string
#% gisprompt: new,vector,vector
#% key_desc: name
#% description: Name for output vector map
#% required: yes
#%end

#%option
#% key: layer
#% type: integer
#% description: Layer number. If -1, all layers are extracted
#% answer: 1
#% required : no
#%end

#%option
#% key: column
#% type: string
#% description: Name of column used to dissolve common boundaries
#% 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

#### setup temporary file
TMP=$$

cleanup()
{
   g.remove vect="$GIS_OPT_OUTPUT"_${TMP}
}

# what to do in case of user break:
exitprocedure()
{
   echo "User break!" 1>&2
   cleanup
   exit 1
}
# shell check for user break (signal list: trap -l)
trap "exitprocedure" 2 3 15

# does map exist?
eval `g.findfile element=vector file=$GIS_OPT_INPUT`
if [ ! "$file" ] ; then
   echo "Vector map '$GIS_OPT_INPUT' not found in mapset search path"
   exit 1
fi

if [ -z "$GIS_OPT_COLUMN" ] ; then
   v.extract -d input="$GIS_OPT_INPUT" output="$GIS_OPT_OUTPUT" type=area \
             layer="$GIS_OPT_LAYER"
else
   table=`v.db.connect $GIS_OPT_INPUT -g | grep -w $GIS_OPT_LAYER | awk '{print $2}'`
   if [ -z "$table" ] ; then
      echo -e "\nERROR: There is no table connected to this map!"
      cleanup
      exit 1
   fi
   v.reclass input="$GIS_OPT_INPUT" output="$GIS_OPT_OUTPUT"_${TMP} layer="$GIS_OPT_LAYER" \
             column="$GIS_OPT_COLUMN"
   v.extract -d input="$GIS_OPT_OUTPUT"_${TMP} output="$GIS_OPT_OUTPUT" type=area \
             layer="$GIS_OPT_LAYER"
   cleanup

fi

exit
