#!/bin/sh
#
############################################################################
#
# MODULE:       d.vect.thematic
# AUTHOR(S):	Michael Barton, Arizona State University with contributions
#               by Martin Landa, Jachym Cepicky, Daniel Calvelo Aros and Moritz Lennert
# PURPOSE:	    Displays thematic vector map with graduated colors
#               or graduated points and line thickneses
# COPYRIGHT:	(C) 2006 by 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: Displays thematic vectormap
#%  keywords: display, legend
#%End
#%option
#% key: map
#% type: string
#% gisprompt: old,vector,vector
#% description: Vector map to display thematically
#% required : yes
#%end
#%option
#% key: type
#% type: string
#% description: Vector map type
#% options: area,point,centroid,line,boundary
#% answer: area
#% required : yes
#%end
#%option
#% key: column
#% type: string
#% description: Attribute column to use for thematic display (must be numeric)
#% required : yes
#%end
#%option
#% key: themetype
#% type: string
#% options: graduated_colors,graduated_points,graduated_lines
#% answer: graduated_colors
#% description: Type of thematic display
#% required : yes
#%end
#%option
#% key: themecalc
#% type: string
#% options: interval,std_deviation,quartiles,custom_breaks
#% answer: interval
#% description: Thematic divisions of data for display
#% required : yes
#%end
#%option
#% key: breakpoints
#% type: string
#% description: Break points for custom breaks option. Separate values by spaces. (0 10 20 30 ...)
#% required : no
#%end
#%option
#% key: layer
#% type: integer
#% description: Layer to use for thematic display
#% answer: 1
#% required : no
#%end
#%option
#% key: icon
#% type: string
#% description: Vector point icon for point data
#% options: basic/box,basic/circle,basic/cross2,basic/diamond,basic/star,basic/cross1,basic/x
#% answer: basic/circle
#% required : no
#%end
#%option
#% key: size
#% type: double
#% description: Icon size for point data (minimum icon size/line width for graduated points/lines)
#% answer: 5
#% required : no
#%end
#%option
#% key: maxsize
#% type: double
#% description: Maximum icon size/line width for graduated points and lines
#% answer: 20
#% required : no
#%end
#%option
#% key: nint
#% type: integer
#% description: Number of classes for interval theme (integer)
#% answer: 4
#% required : no
#%end
#%option
#% key: colorscheme
#% type: string
#% description: Color scheme for graduated color mapping (select 'single_color' for graduated point/line display)
#% options: blue-red,red-blue,green-red,red-green,blue-green,green-blue,cyan-yellow,yellow-cyan,custom_gradient,single_color
#% answer: blue-red
#% required : yes
#%end
#% option
#% key: pointcolor
#% type: string
#% description: Color for graduated points map (grass named color or R:G:B triplet). Set color scheme to single color.
#% answer: 255:0:0
#% required : no
#%end
#% option
#% key: linecolor
#% type: string
#% description: Color for graduated lines or point/area outlines (grass named color or R:G:B triplet). Set color scheme to single color.
#% answer: 0:0:0
#% required : no
#%end
#% option
#% key: startcolor
#% type: string
#% description: Beginning color for custom color gradient. Must be expressed as R:G:B triplet.
#% answer: 255:0:0
#% required : no
#%end
#% option
#% key: endcolor
#% type: string
#% description: Ending color for custom color gradient. Must be expressed as R:G:B triplet
#% answer: 0:0:255
#% required : no
#%end
#% option
#% key: monitor
#% type: string
#% description: Select x11 display monitor for legend
#% options: x0,x1,x2,x3,x4,x5,x6,none
#% answer: x1
#% required : no
#%end
#%option
#% key: group
#% type: string
#% gisprompt: new_file,file,group
#% description: Name of group file where thematic map commands will be saved
#% required : no
#%end
#%option
#% key: where
#% type: string
#% description: WHERE conditions of SQL statement without 'where' keyword
#% required : no
#%end
#%option
#% key: psmap
#% type: string
#% description: Root for the name of psmap instruction files to be in current directory (if not set, no psmap instruction files will be created)
#% required : no
#%end
#%flag
#% key: f
#% description: Only draw fills (no outlines) for areas and points
#%end
#%flag
#% key: u
#% description: Update color values to GRASSRGB column in attribute table
#%end
#%flag 
#%key: l
#%description: Create graphic legend in x11 display monitor
#%end
#%flag 
#%key: s
#%description: Use with GIS Manager (special legend and display output)
#%end
#%flag 
#%key: m
#%description: Use math notation brackets in legend
#%end
#%flag 
#%key: g
#%description: Save thematic map commands to group file for GIS Manager
#%end

if  [ -z "$GISBASE" ] ; then
    echo "You must be in GRASS GIS to run this program."
 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
    echo "$PROG: awk required, please install awk or gawk first" 2>&1
    exit 1
fi

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

# check column type
COLTYPE="`v.info -c $GIS_OPT_MAP layer=1 2> /dev/null | grep -w $GIS_OPT_COLUMN | cut -d'|' -f1 | tr -s '[:upper:]' '[:lower:]'`"

#COLTYPE=... 
if [ -z "$COLTYPE" ] ; then 
   echo "ERROR: No such column [$GIS_OPT_COLUMN]" 
   exit 1 
fi 

if [ "$COLTYPE" = "integer" -o "$COLTYPE" = "double precision" ] ; then
	echo ""
else
	echo "ERROR: Column <$GIS_OPT_COLUMN> is of type <$COLTYPE> which is not numeric."
	exit 1
fi

# create temporary file to hold output from v.univar.sh
TMP1="`g.tempfile pid=$$`"
if [ $? -ne 0 ] || [ -z "$TMP1" ] ; then
    echo "ERROR: unable to create temporary file for statistics" 1>&2
    exit 1
fi

# create temporary file to hold d.graph commands for legend
TMP2="`g.tempfile pid=$$`"
if [ $? -ne 0 ] || [ -z "$TMP2" ] ; then
    echo "ERROR: unable to create temporary file for legend" 1>&2
    exit 1
fi

# Create temporary file to commands for GIS Manager group
TMP3="`g.tempfile pid=$$`"
if [ $? -ne 0 ] || [ -z "$TMP3" ] ; then
    echo "ERROR: unable to create temporary file for group" 1>&2
    exit 1
fi

# Create temporary file for commands for ps.map map file
TMP4="`g.tempfile pid=$$`"
if [ $? -ne 0 ] || [ -z "$TMP4" ] ; then
    echo "ERROR: unable to create temporary file for ps.map legend" 1>&2
    exit 1
fi

# Create temporary file for commands for ps.map legend file
TMP5="`g.tempfile pid=$$`"
if [ $? -ne 0 ] || [ -z "$TMP5" ] ; then
    echo "ERROR: unable to create temporary file for ps.map legend" 1>&2
    exit 1
fi

# create file to hold elements for GIS Manager legend
TMP6="`g.tempfile pid=$$`"
if [ $? -ne 0 ] || [ -z "$TMP6" ] ; then
    echo "ERROR: unable to create temporary file for GIS Manager legend" 1>&2
    exit 1
fi


# Set display variables for group
atype=0
ptype=0
ctype=0
ltype=0
btype=0

case "$GIS_OPT_TYPE" in
    "area" ) atype=1 ;; 
    "point" )  ptype=1 ;;
    "centroid" ) ctype=1 ;;
    "line" ) ltype=1 ;;
    "boundary" ) btype=1 ;;
esac

cleanup()
{
    \rm -f $TMP1 $TMP1.sort
    \rm -f $TMP2 $TMP2.sort
    \rm -f $TMP3 $TMP3.sort
    \rm -f $TMP4 $TMP4.sort
    \rm -f $TMP5 $TMP5.sort
    \rm -f $TMP6 $TMP6.sort
}

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

# identify current monitor or start monitor
currmon=`eval d.mon -L | grep "(selected)" | awk '{print $1}'`

if [ -z $currmon ] ; then
	echo ""
	echo "*** You must open a display monitor ***"
	echo ""
fi



table=`v.db.connect $GIS_OPT_MAP -g | grep -w $GIS_OPT_LAYER | awk '{print $2}'`
database=`v.db.connect $GIS_OPT_MAP -g | grep -w $GIS_OPT_LAYER | awk '{print $4}'`

if [ -z "$table" ]
    then
    echo "No table connected or layer <$GIS_OPT_LAYER> doesn't exist!"
    exit 1
 fi

# update color values to the table?
if [ "$GIS_FLAG_U" -eq 1 ] ; then
    # test, if the column GRASSRGB is in the table
    if [ -z "`db.columns table=$table database=$database | grep -i grassrgb`" ] ; then
        echo "Creating column 'grassrgb' in table '$table'"
        echo "ALTER TABLE $table ADD COLUMN grassrgb varchar(11)" | db.execute database=$database
    fi
fi

# Group name
if [ -z "$GIS_OPT_GROUP" ] ; then
    group="themes"
else
    group=$GIS_OPT_GROUP
fi

echo "Group $group" > "$TMP3"

# Calculate statistics for thematic intervals
if [ -z "$GIS_OPT_WHERE" ] ; then
  v.univar.sh -e database=$database table=$table column=$GIS_OPT_COLUMN > "$TMP1"
else
  v.univar.sh -e database=$database table=$table column=$GIS_OPT_COLUMN where="$GIS_OPT_WHERE" > "$TMP1"
fi
  
min="`grep 'Minimum:' $TMP1 | sed s/Minimum://`"
max="`grep 'Maximum:' $TMP1 | sed s/Maximum://`"
mean="`grep 'Mean:' $TMP1 | sed s/Mean://`"
sd="`grep 'Standard deviation:' $TMP1 | sed s/'Standard deviation:'//`"
q1="`grep '1st Quartile:' $TMP1 | sed s/'1st Quartile:'//`"
q2="`grep 'Median' $TMP1 | sed s/'Median (.* N):'//`"
q3="`grep '3rd Quartile:' $TMP1 | sed s/'3rd Quartile:'//`"
q4=$max
ptsize=$GIS_OPT_SIZE

if [ -n "$GIS_OPT_BREAKPOINTS" ] && [ "$GIS_OPT_THEMECALC" != "custom_breaks" ] ; then
    echo "WARNING: Custom breakpoints ignored due to themecalc setting."
fi

# set interval for each thematic map calculation type
case "$GIS_OPT_THEMECALC" in 
"interval" )
    numint=$GIS_OPT_NINT
    step=`echo $min $max $numint | awk '{print (($2 - $1) / $3)}'`
    breakpoints=`echo $min $max $numint | awk '{for(i=0;i<$3;i++){printf $1+($2-$1)/$3*i " "}printf $2}'`
    annotations=""
    ;;

"std_deviation" )
    # 2 standard deviation units on either side of mean,
    # plus min to -2 sd units and +2 sd units to max, if applicable
    breakpoints=`echo $min $max $mean $sd | awk '{printf $1;for(i=-2;i<=2;i++){ith=$3+i*$4;if($1<ith && $2>ith){printf " " ith}}print " " $2}'`
    annotations=`echo $min $max $mean $sd | awk '{printf "";for(i=-2;i<=2;i++){ith=$3+i*$4;if($1<ith && $2>ith){if(i!=0){printf ";"((i<0)?"":"+") i "sd"} }}print ";"}'`
    numint=`echo $breakpoints | awk '{print NF-1}'`
    ;;

"quartiles" )
    numint=4
    # one for each quartile
    breakpoints="$min $q1 $q2 $q3 $max"
    annotations=" q1; q2; q3; q4"
    ;;

"custom_breaks" )
	if [ -z "$GIS_OPT_BREAKPOINTS" ] ; then
	    breakpoints=`cat | awk '{gsub("[^0-9., ]","",$0);print}'`
	else
		breakpoints="$GIS_OPT_BREAKPOINTS"
	fi
    numint=`echo $breakpoints|awk '{print NF-1}'`
    annotations=""
    ;;

 "*")
    echo "Unknown themecalc type"
    cleanup
    exit
esac

pointstep=`echo $GIS_OPT_MAXSIZE $ptsize $numint | awk '{print (($1 - $2) / ($3-1))}'`

# legend title
echo "color 0:0:0" > "$TMP2"
echo "size 2 2" >> "$TMP2"
echo "move 1 95" >> "$TMP2"
echo "text Thematic map legend for column $GIS_OPT_COLUMN of map $GIS_OPT_MAP" >> "$TMP2"
echo "size 1.5 1.8" >> "$TMP2"
echo "move 4 90" >> "$TMP2"
echo "text Value range: $min - $max" >> "$TMP2"

echo "title - - - {Thematic map legend for column $GIS_OPT_COLUMN of map $GIS_OPT_MAP}" > "$TMP6"

echo "text 1% 95% Thematic map legend for column $GIS_OPT_COLUMN of map $GIS_OPT_MAP" >> "$TMP5"
echo "  ref bottom left" >> $TMP5
echo "end" >> $TMP5
echo "text 4% 90% Value range: $min - $max" >> "$TMP5"
echo "  ref bottom left" >> $TMP5
echo "end" >> $TMP5

echo "Thematic map legend for column $GIS_OPT_COLUMN of map $GIS_OPT_MAP"
echo ""
echo "Value range: $min - $max"

# graduated color thematic mapping

if [ "$GIS_OPT_THEMETYPE" = "graduated_colors" ] ; then
    # set color schemes for graduated color maps
    case "$GIS_OPT_COLORSCHEME" in
		"blue-red" )
	    startc="0:0:255"
	    endc="255:0:0"
	    ;;    
        "red-blue" )
	    startc="255:0:0"
	    endc="0:0:255"
	    ;;
        "green-red" )
	    startc="0:255:0"
	    endc="255:0:0"
	    ;;
        "red-green" )
	    startc="255:0:0"
	    endc="0:255:0"
	    ;;
        "blue-green" )
	    startc="0:0:255"
	    endc="0:255:0"
	    ;;
		"green-blue" )
	    startc="0:255:0"
	    endc="0:0:255"
	    ;;
		"cyan-yellow" )
	    startc="0:255:255"
	    endc="255:255:0"
	    ;;
		"yellow-cyan" )
	    startc="255:255:0"
	    endc="0:255:255"
	    ;;
        "custom_gradient" )
	    startc="$GIS_OPT_STARTCOLOR"
	    endc="$GIS_OPT_ENDCOLOR"
	    ;;
        "single_color" )
	    if [ "$GIS_OPT_THEMETYPE" = "graduated_points" ]; then
			startc="$GIS_OPT_LINECOLOR"
			endc="$GIS_OPT_LINECOLOR"
	    else
			startc="$GIS_OPT_POINTCOLOR"
			endc="$GIS_OPT_POINTCOLOR"
	    fi
	    ;;
        "*")
	    echo "This should not happen: gparser error. Unknown color scheme $GIS_OPT_COLORSCHEME"
	    cleanup
	    exit
	    ;;
    esac

    for i in 1 2 3; do
	eval color$i=`echo $startc | cut -d':' -f$i`
	eval endcolor$i=`echo $endc | cut -d':' -f$i`
    done

    #The number of color steps is one less then the number of classes
    nclrstep=`expr $numint - 1`
    
    clrstep1=`expr \( $color1 - $endcolor1 \) / $nclrstep`
    clrstep2=`expr \( $color2 - $endcolor2 \) / $nclrstep`
    clrstep3=`expr \( $color3 - $endcolor3 \) / $nclrstep`

    themecolor="$startc"

    # display graduated color themes
    if [ "$GIS_OPT_THEMECALC" = "interval" ] ; then
        echo "move 4 87" >> "$TMP2"
        echo "text Mapped by $numint intervals of $step" >> "$TMP2"

		echo "subtitle - - - {Mapped by $numint intervals of $step}" >> "$TMP6"

        echo "text 4% 87% Mapped by $numint intervals of $step" >> "$TMP5"
        echo "  ref bottom left" >> $TMP5
        echo "end" >> $TMP5

        echo "Mapped by $numint intervals of $step"
    fi

    # display graduated color themes for standard deviation units
    if [ "$GIS_OPT_THEMECALC" = "std_deviation" ] ; then

        echo "move 4 87" >> "$TMP2"
        echo "text Mapped by standard deviation units of $sd (mean =$mean)" >> "$TMP2"

		echo "subtitle - - - {Mapped by standard deviation units of $sd (mean =$mean)}" >> "$TMP6"

        echo "text 4% 87% Mapped by standard deviation units of $sd (mean =$mean)" >> "$TMP5"
        echo "  ref bottom left" >> $TMP5
        echo "end" >> $TMP5

        echo "Mapped by standard deviation units of $sd (mean =$mean)"
    fi

    # display graduated color themes for quartiles
    if [ "$GIS_OPT_THEMECALC" = "quartiles" ] ; then

        echo "move 4 87" >> "$TMP2"
        echo "text Mapped by quartiles (median =$q2)" >> "$TMP2"

		echo "subtitle - - - {Mapped by quartiles (median =$q2)}" >> "$TMP6"

        echo "text 4% 87% Mapped by quartiles (median =$q2)" >> "$TMP5"
        echo "  ref bottom left" >> $TMP5
        echo "end" >> $TMP5

	

        echo "Mapped by quartiles (median =$q2)"
    fi

    echo "move 4 83" >> "$TMP2"
    echo "text Color" >> "$TMP2"
    echo "move 14 83" >> "$TMP2"
    echo "text Value" >> "$TMP2"
    echo "move 4 80" >> "$TMP2"
    echo "text =====" >> "$TMP2"
    echo "move 14 80" >> "$TMP2"
    echo "text ============" >> "$TMP2"


    echo "text 4% 83% Color" >> "$TMP5"
    echo "  ref bottom left" >> $TMP5
    echo "end" >> $TMP5
    echo "text 14% 83% Value" >> "$TMP5"
    echo "  ref bottom left" >> $TMP5
    echo "end" >> $TMP5
    echo "text 4% 80% =====" >> "$TMP5"
    echo "  ref bottom left" >> $TMP5
    echo "end" >> $TMP5
    echo "text 14% 80% ============" >> "$TMP5"
    echo "  ref bottom left" >> $TMP5
    echo "end" >> $TMP5


    echo ""
    echo "Color(R:G:B)" "Value" | awk '{print $1 "\t" $2}'
    echo "============" "==========" | awk '{print $1 "\t" $2}'

    line1=78
    line2=76
    line3=75

    i=1
    first="true"

	# if running in GUI, turn off immediate mode rendering so that the
	# iterated d.vect commands will composite using the display driver
	if [ "$GIS_FLAG_S"  -eq 1 ] ; then
		rendermode=$GRASS_RENDER_IMMEDIATE
		autowrite=$GRASS_PNG_AUTO_WRITE
		GRASS_RENDER_IMMEDIATE=FALSE
		export GRASS_RENDER_IMMEDIATE
		GRASS_PNG_AUTO_WRITE=FALSE
		export GRASS_PNG_AUTO_WRITE
		d.mon start=PNG
	fi

    while [ $i -le $numint ]     
        do 
        if [ "$GIS_FLAG_M" -eq 1 ] ; then
        # math notation
           if [ "$first" = "true" ] ; then
                closebracket="]"
                openbracket="["
                mincomparison=">="
                first="false"
            else
                closebracket="]"
                openbracket="]"
                mincomparison=">"            
            fi
        else
            closebracket="" 
            openbracket=""
            if [ "$first" = "true" ] ; then
                mincomparison=">="
                first="false"
            else
                mincomparison=">"            
            fi
        fi

        themecolor="$color1:$color2:$color3"
        if [ "$GIS_FLAG_F" -eq 1 ] ; then
        	linecolor="none"
        else
        	if [ "$GIS_OPT_TYPE" = "line" -o "$GIS_OPT_TYPE" = "boundary" ] ; then
         	   linecolor=$themecolor
        	else
        	    linecolor="$GIS_OPT_LINECOLOR"
        	fi
        fi
      
        rangemin=`echo $i $breakpoints | awk '{t=$1+1;print $t}'`
        rangemax=`echo $i $breakpoints | awk '{t=$1+2;print $t}'`

        if [ -z "$annotations" ]; then
            extranote=""
        else
            extranote=`echo $annotations| cut -d';' -f$i`
        fi

        echo "color $themecolor" >> "$TMP2"
        echo "polygon" >> "$TMP2"
        echo "5 $line1" >> "$TMP2"
        echo "8 $line1" >> "$TMP2"
        echo "8 $line3" >> "$TMP2"
        echo "5 $line3" >> "$TMP2"
        echo "color $linecolor" >> "$TMP2"
		echo "move 5 $line1" >> "$TMP2"
		echo "draw 8 $line1" >> "$TMP2"
		echo "draw 8 $line3" >> "$TMP2"
		echo "draw 5 $line3" >> "$TMP2"
		echo "draw 5 $line1" >> "$TMP2"
        echo "move 14 $line2" >> "$TMP2"
        echo "color 0:0:0" >> "$TMP2"
        echo "text $openbracket$rangemin - $rangemax$closebracket $extranote"  >> "$TMP2"

		echo "area $themecolor $linecolor - {$openbracket$rangemin - $rangemax$closebracket $extranote}" >> "$TMP6"

        if [ "$GIS_OPT_TYPE" = "line" -o "$GIS_OPT_TYPE" = "boundary" ] ; then
		  echo "line 5% $line1% 8% $line1%" >> $TMP5
		  echo "  color $linecolor" >> $TMP5
		  echo "end" >> $TMP5
          echo "text 14% $line1% $openbracket$rangemin - $rangemax$closebracket $extranote"  >> "$TMP5"
          echo "  ref center left" >> $TMP5
          echo "end" >> $TMP5
        elif [ "$GIS_OPT_TYPE" = "point" -o "$GIS_OPT_TYPE" = "centroid" ] ; then
          echo "point 8% $line1%" >> "$TMP5"
		  echo "  color $linecolor" >> "$TMP5"
		  echo "  fcolor $themecolor" >> "$TMP5"
		  echo "  size $GIS_OPT_SIZE" >> "$TMP5"
		  echo "  symbol $GIS_OPT_ICON" >> "$TMP5"
		  echo "end" >> "$TMP5"
          echo "text 14% $line1% $openbracket$rangemin - $rangemax$closebracket $extranote"  >> "$TMP5"
          echo "  ref center left" >> $TMP5
          echo "end" >> $TMP5
		else
          echo "rectangle 5% $line1% 8% $line3%" >> "$TMP5"
		  echo "  color 0:0:0" >> "$TMP5"
		  echo "  fcolor $themecolor" >> "$TMP5"
		  echo "end" >> "$TMP5"
          echo "text 14% $line3% $openbracket$rangemin - $rangemax$closebracket $extranote"  >> "$TMP5"
          echo "  ref bottom left" >> $TMP5
          echo "end" >> $TMP5
        fi
	


        echo $themecolor@$rangemin@$rangemax@$extranote@$openbracket@$closebracket | awk -F@ '{print $1 "\t\t" $5$2" - "$3$6" "$4}'
		if [ -z "$GIS_OPT_WHERE" ] ; then
            sqlwhere="$GIS_OPT_COLUMN $mincomparison $rangemin and $GIS_OPT_COLUMN<=$rangemax"
		else
            sqlwhere="$GIS_OPT_COLUMN $mincomparison $rangemin and $GIS_OPT_COLUMN<=$rangemax AND $GIS_OPT_WHERE"
		fi

        # update color to database?
        if [ $GIS_FLAG_U -eq 1 ] ; then
            echo "UPDATE $table SET GRASSRGB = '$themecolor' WHERE\
                $sqlwhere" | db.execute database=$database
        fi
               
        # Create group for GIS Manager
        if [ "$GIS_FLAG_G" -eq 1 ] ; then
        
            # change rgb colors to hex
            xthemecolor=`echo $themecolor | awk -F: '{printf("#%02X%02X%02X\n",$1,$2,$3)}'`
#            xlinecolor=`echo $linecolor | awk -F: '{printf("#%02X%02X%02X\n",$1,$2,$3)}'`
            
            if [ "$linecolor" = "black" ] ; then
                xlinecolor="#000000"
            else
                xlinecolor=$xthemecolor
            fi

            # create group entry
            echo "  _check 1" >> "$TMP3"
            echo "  Vector $GIS_OPT_COLUMN = $rangemin - $rangemax" >> "$TMP3"
            echo "    _check 1" >> "$TMP3"
            echo "    map $GIS_OPT_MAP" >> "$TMP3"
            echo "    display_shape 1" >> "$TMP3"
            echo "    display_cat 0" >> "$TMP3"
            echo "    display_topo 0" >> "$TMP3"
            echo "    display_dir 0" >> "$TMP3"
            echo "    display_attr 0" >> "$TMP3"
            echo "    type_point $ptype" >> "$TMP3"
            echo "    type_line $ltype" >> "$TMP3"
            echo "    type_boundary $btype" >> "$TMP3"
            echo "    type_centroid $ctype" >> "$TMP3"
            echo "    type_area $atype" >> "$TMP3"
            echo "    type_face 0" >> "$TMP3"
            echo "    color $xlinecolor" >> "$TMP3"
            echo "    fcolor $xthemecolor" >> "$TMP3"
            echo "    width $ptsize" >> "$TMP3"
            echo "    _use_fcolor 1" >> "$TMP3"
            echo "    lcolor #000000" >> "$TMP3"
            echo "    sqlcolor 0" >> "$TMP3"
            echo "    icon $GIS_OPT_ICON" >> "$TMP3"
            echo "    size $ptsize" >> "$TMP3"
            echo "    field $GIS_OPT_LAYER" >> "$TMP3"
            echo "    lfield $GIS_OPT_LAYER" >> "$TMP3"
            echo "    attribute" >> "$TMP3"
            echo "    xref left" >> "$TMP3"
            echo "    yref center" >> "$TMP3"
            echo "    lsize 8" >> "$TMP3"
            echo "    cat" >> "$TMP3"
            echo "    where "$sqlwhere >> "$TMP3"
            echo "    _query_text 0" >> "$TMP3"
            echo "    _query_edit 1" >> "$TMP3"
            echo "    _use_where 1" >> "$TMP3"
            echo "    minreg" >> "$TMP3"
            echo "    maxreg" >> "$TMP3"
            echo "    _width 0.1" >> "$TMP3"
            echo "  End" >> "$TMP3"
        fi
        
        
        # display theme vector map

        d.vect map=$GIS_OPT_MAP type=$GIS_OPT_TYPE layer=$GIS_OPT_LAYER \
            where="$sqlwhere" \
            color=$linecolor fcolor=$themecolor icon=$GIS_OPT_ICON size=$ptsize

        if [ "$GIS_OPT_TYPE" = "line" -o "$GIS_OPT_TYPE" = "boundary" ] ; then
		  echo "vlines $GIS_OPT_MAP" >> $TMP4
		  echo "  type $GIS_OPT_TYPE" >> $TMP4
		  echo "  layer $GIS_OPT_LAYER" >> $TMP4
		  echo "  where $sqlwhere" >> $TMP4
		  echo "  color $linecolor" >> $TMP4
		  echo "  label $rangemin - $rangemax" >> $TMP4
		  echo "end" >> $TMP4
        elif [ "$GIS_OPT_TYPE" = "point" -o "$GIS_OPT_TYPE" = "centroid" ] ; then
		  echo "vpoints $GIS_OPT_MAP" >> $TMP4
		  echo "  type $GIS_OPT_TYPE" >> $TMP4
		  echo "  layer $GIS_OPT_LAYER" >> $TMP4
		  echo "  where $sqlwhere" >> $TMP4
		  echo "  color $linecolor" >> $TMP4
		  echo "  fcolor $themecolor" >> $TMP4
		  echo "  symbol $GIS_OPT_ICON" >> $TMP4
		  echo "  label $rangemin - $rangemax" >> $TMP4
		  echo "end" >> $TMP4
		else
		  echo "vareas $GIS_OPT_MAP" >> $TMP4
		  echo "  layer $GIS_OPT_LAYER" >> $TMP4
		  echo "  where $sqlwhere" >> $TMP4
		  echo "  color $linecolor" >> $TMP4
		  echo "  fcolor $themecolor" >> $TMP4
		  echo "  label $rangemin - $rangemax" >> $TMP4
		  echo "end" >> $TMP4
		fi


        # increment for next theme
        i=`expr $i + 1`
		if [ $i = $numint ] ; then
		  color1=$endcolor1
		  color2=$endcolor2
		  color3=$endcolor3
		else
          color1=`expr $color1 - $clrstep1`
          color2=`expr $color2 - $clrstep2`
          color3=`expr $color3 - $clrstep3`
		fi
        line1=`expr $line1 - 4`
        line2=`expr $line2 - 4`
        line3=`expr $line3 - 4`
    done
    
    # reset rendering for GUI use
	if [ "$GIS_FLAG_S"  -eq 1 ] ; then
		d.mon stop=PNG
		d.mon select=$currmon
		GRASS_RENDER_IMMEDIATE=$rendermodeexport
		export GRASS_RENDER_IMMEDIATE
		GRASS_PNG_AUTO_WRITE=$autowrite
		export GRASS_PNG_AUTO_WRITE
	fi
fi

#graduated points and line widths thematic mapping

if [ "$GIS_OPT_THEMETYPE" = "graduated_points" -o "$GIS_OPT_THEMETYPE" = "graduated_lines" ] ; then

    #display graduated points/lines by intervals
    if [ "$GIS_OPT_THEMECALC" = "interval" ] ; then
        echo "move 4 87" >> "$TMP2"
        echo "text Mapped by $numint intervals of $step" >> "$TMP2"

		echo "subtitle - - - {Mapped by $numint intervals of $step}" >> "$TMP6"

        echo "text 4% 87% Mapped by $numint intervals of $step" >> "$TMP5"
        echo "  ref bottom left" >> $TMP5
        echo "end" >> $TMP5

        echo "Mapped by $numint intervals of $step"
    fi
        
    # display graduated points/lines for standard deviation units
    if [ "$GIS_OPT_THEMECALC" = "std_deviation" ] ; then

        echo "move 4 87" >> "$TMP2"
        echo "text Mapped by standard deviation units of $sd (mean =$mean)" >> "$TMP2"

		echo "subtitle - - - {Mapped by standard deviation units of $sd (mean =$mean)}" >> "$TMP6"

        echo "text 4% 87% Mapped by standard deviation units of $sd (mean =$mean)" >> "$TMP5"
		echo "  ref bottom left" >> $TMP5
		echo "end" >> $TMP5
	
        echo "Mapped by standard deviation units of $sd (mean =$mean)"
    fi
    
    # display graduated points/lines for quartiles
    if [ "$GIS_OPT_THEMECALC" = "quartiles" ] ; then

        echo "move 4 87" >> "$TMP2"
        echo "text Mapped by quartiles (median =$q2)" >> "$TMP2"

		echo "subtitle - - - {Mapped by quartiles (median =$q2)}" >> "$TMP6"

        echo "text 4% 87% Mapped by quartiles (median =$q2)" >> "$TMP5"
        echo "  ref bottom left" >> $TMP5
        echo "end" >> $TMP5

        echo "Mapped by quartiles (median =$q2)"
    fi
        
    line1=76
    line2=75
    echo "move 4 83" >> "$TMP2"
    echo "text Size/width" >> "$TMP2"
    echo "move 25 83" >> "$TMP2"
    echo "text Value" >> "$TMP2"
    echo "move 4 80" >> "$TMP2"
    echo "text ==============" >> "$TMP2"
    echo "move 25 80" >> "$TMP2"
    echo "text ==============" >> "$TMP2"


    echo "text 4% 83% Icon size" >> "$TMP5"
    echo "  ref bottom left" >> $TMP5
    echo "end" >> $TMP5
    echo "text 25% 83% Value" >> "$TMP5"
    echo "  ref bottom left" >> $TMP5
    echo "end" >> $TMP5
    echo "text 4% 80% ============" >> "$TMP5"
    echo "  ref bottom left" >> $TMP5
    echo "end" >> $TMP5
    echo "text 25% 80% ============" >> "$TMP5"
    echo "  ref bottom left" >> $TMP5
    echo "end" >> $TMP5

    

    echo ""
    echo "Size/width" "Value" | awk '{print $1 " " $2"\t"$3}'
    echo "==========" "=====" | awk '{print $1 "\t" $2}'

    themecolor=$GIS_OPT_POINTCOLOR
    
	if [ "$GIS_FLAG_F" -eq 1 ] ; then
		linecolor="none"
	else
		linecolor="$GIS_OPT_LINECOLOR"
	fi

    i=$numint
    ptsize=$GIS_OPT_MAXSIZE

	# if running in GUI, turn off immediate mode rendering so that the
	# iterated d.vect commands will composite using the display driver
	if [ "$GIS_FLAG_S"  -eq 1 ] ; then
		rendermode=$GRASS_RENDER_IMMEDIATE
		autowrite=$GRASS_PNG_AUTO_WRITE
		GRASS_RENDER_IMMEDIATE=FALSE
		export GRASS_RENDER_IMMEDIATE
		GRASS_PNG_AUTO_WRITE=FALSE
		export GRASS_PNG_AUTO_WRITE
		d.mon start=PNG
	fi

    while [ $i -ge 1 ]     
        do 
        if [ "$GIS_FLAG_M" -eq 1 ] ; then
        # math notation
           if [ "$i" = "1" ] ; then
                closebracket="]"
                openbracket="["
                mincomparison=">="
            else
                closebracket="]"
                openbracket="]"
                mincomparison=">"            
            fi
        else
            closebracket="" 
            openbracket=""
            if [ "$i" = "1" ] ; then
                mincomparison=">="
            else
                mincomparison=">"            
            fi
        fi

        themecolor=$GIS_OPT_POINTCOLOR

		if [ "$GIS_FLAG_F" -eq 1 ] ; then
			linecolor="none"
		else
			linecolor="$GIS_OPT_LINECOLOR"
		fi
      
        rangemin=`echo $i $breakpoints | awk '{t=$1+1;print $t}'`
        rangemax=`echo $i $breakpoints | awk '{t=$1+2;print $t}'`

        if [ -z "$annotations" ]; then
            extranote=""
        else
            extranote=`echo $annotations| cut -d';' -f$i`
        fi            

        iconsize=`echo $ptsize | awk '{print int($1 / 2)}'`
        lineht=`echo $ptsize | awk '{print int($1 / 4)}'`
        if [ "$lineht" -lt "4" ] ; then
            lineht=4
        fi

		if [ "$GIS_OPT_THEMETYPE" = "graduated_lines" ]; then
	        echo "color $linecolor" >> "$TMP2"
			echo "line $themecolor $linecolor $ptsize {$openbracket$rangemin - $rangemax$closebracket $extranote}" >> "$TMP6"
	    else
			echo "color $themecolor" >> "$TMP2"
			echo "point $themecolor $linecolor $ptsize {$openbracket$rangemin - $rangemax$closebracket $extranote}" >> "$TMP6"
		fi

        echo "icon + $iconsize 5 $line1" >> "$TMP2"
        echo "color 0:0:0" >> "$TMP2"
        echo "move 10 $line2" >> "$TMP2"
        echo "text $ptsize pts" >> "$TMP2"
        echo "move 25 $line2" >> "$TMP2"
        echo "text $openbracket$rangemin - $rangemax$closebracket $extranote"  >> "$TMP2"

        echo "point 8% $line1%" >> "$TMP5"
		echo "  color $linecolor" >> "$TMP5"
		echo "  fcolor $themecolor" >> "$TMP5"
		echo "  size $iconsize" >> "$TMP5"
		echo "  symbol $GIS_OPT_ICON" >> "$TMP5"
		echo "end" >> "$TMP5"
        echo "text 25% $line1% $openbracket$rangemin - $rangemax$closebracket $extranote"  >> "$TMP5"
        echo "  ref center left" >> $TMP5
        echo "end" >> $TMP5

        echo $ptsize@$rangemin@$rangemax@$extranote@$openbracket@$closebracket | awk -F@ '{print $1 "\t\t" $5$2" - "$3$6" "$4}'

	if [ -z "$GIS_OPT_WHERE" ] ; then
           sqlwhere="$GIS_OPT_COLUMN $mincomparison $rangemin and $GIS_OPT_COLUMN<=$rangemax"
	else
           sqlwhere="$GIS_OPT_COLUMN $mincomparison $rangemin and $GIS_OPT_COLUMN<=$rangemax AND $GIS_OPT_WHERE"
	fi

        # update color to database?
        if [ $GIS_FLAG_U -eq 1 ] ; then
            echo "UPDATE $table SET GRASSRGB = '$themecolor' WHERE\
                $sqlwhere" | db.execute database=$database
        fi
      
        # Create group for GIS Manager
        if [ "$GIS_FLAG_G" -eq 1 ] ; then
        
            # change rgb colors to hex
            xthemecolor=`echo $themecolor | awk -F: '{printf("#%02X%02X%02X\n",$1,$2,$3)}'`
            xlinecolor="#000000"

            # create group entry
            echo "  _check 1" >> "$TMP3"
            echo "  Vector $GIS_OPT_COLUMN = $rangemin - $rangemax" >> "$TMP3"
            echo "    _check 1" >> "$TMP3"
            echo "    map $GIS_OPT_MAP" >> "$TMP3"
            echo "    display_shape 1" >> "$TMP3"
            echo "    display_cat 0" >> "$TMP3"
            echo "    display_topo 0" >> "$TMP3"
            echo "    display_dir 0" >> "$TMP3"
            echo "    display_attr 0" >> "$TMP3"
            echo "    type_point $ptype" >> "$TMP3"
            echo "    type_line $ltype" >> "$TMP3"
            echo "    type_boundary $btype" >> "$TMP3"
            echo "    type_centroid $ctype" >> "$TMP3"
            echo "    type_area $atype" >> "$TMP3"
            echo "    type_face 0" >> "$TMP3"
            echo "    color $xlinecolor" >> "$TMP3"
            echo "    width $ptsize" >> "$TMP3"
            echo "    fcolor $xthemecolor" >> "$TMP3"
            echo "    _use_fcolor 1" >> "$TMP3"
            echo "    lcolor #000000" >> "$TMP3"
            echo "    sqlcolor 0" >> "$TMP3"
            echo "    icon $GIS_OPT_ICON" >> "$TMP3"
            echo "    size $ptsize" >> "$TMP3"
            echo "    field $GIS_OPT_LAYER" >> "$TMP3"
            echo "    lfield $GIS_OPT_LAYER" >> "$TMP3"
            echo "    attribute" >> "$TMP3"
            echo "    xref left" >> "$TMP3"
            echo "    yref center" >> "$TMP3"
            echo "    lsize 8" >> "$TMP3"
            echo "    cat" >> "$TMP3"
            echo "    where "$sqlwhere >> "$TMP3"
            echo "    _query_text 0" >> "$TMP3"
            echo "    _query_edit 1" >> "$TMP3"
            echo "    _use_where 1" >> "$TMP3"
            echo "    minreg" >> "$TMP3"
            echo "    maxreg" >> "$TMP3"
            echo "    _width 0.1" >> "$TMP3"
            echo "  End" >> "$TMP3"
        fi
        
        #graduates line widths or point sizes

        if [ "$GIS_OPT_THEMETYPE" = "graduated_lines" ] ; then
        	d.vect map=$GIS_OPT_MAP type=$GIS_OPT_TYPE layer=$GIS_OPT_LAYER \
            where="$sqlwhere" \
            color=$linecolor fcolor=$themecolor icon=$GIS_OPT_ICON size=$ptsize \
            width=$ptsize
		else 
			d.vect map=$GIS_OPT_MAP type=$GIS_OPT_TYPE layer=$GIS_OPT_LAYER \
            where="$sqlwhere" \
            color=$linecolor fcolor=$themecolor icon=$GIS_OPT_ICON size=$ptsize
		fi

	  echo "vpoints $GIS_OPT_MAP" >> $TMP4
	  echo "  type $GIS_OPT_TYPE" >> $TMP4
	  echo "  layer $GIS_OPT_LAYER" >> $TMP4
	  echo "  where $sqlwhere" >> $TMP4
	  echo "  color $linecolor" >> $TMP4
	  echo "  fcolor $themecolor" >> $TMP4
	  echo "  symbol $GIS_OPT_ICON" >> $TMP4
	  echo "  size $ptsize" >> $TMP4
	  echo "  label $rangemin - $rangemax" >> $TMP4
	  echo "end" >> $TMP4


        ptsize=`echo $ptsize $pointstep | awk '{print $1 - $2}'`

        line1=`expr $line1 - $lineht`
        line2=`expr $line2 - $lineht`
        i=`expr $i - 1`
    done
    # reset rendering for GUI use
	if [ "$GIS_FLAG_S"  -eq 1 ] ; then
		d.mon stop=PNG
		d.mon select=$currmon
		GRASS_RENDER_IMMEDIATE=$rendermode
		export GRASS_RENDER_IMMEDIATE
		GRASS_PNG_AUTO_WRITE=$autowrite
		export GRASS_PNG_AUTO_WRITE
	fi

fi

# Create graphic legend
if [ "$GIS_FLAG_L" -eq 1 -a "$GIS_OPT_MONITOR" != "none" ] ; then
    echo ""
    echo ""
    if [ `eval d.mon -L | grep $GIS_OPT_MONITOR | awk '{print $5}'` = "not" ] ; then
        d.mon start=$GIS_OPT_MONITOR > /dev/null
    else 
        d.mon select=$GIS_OPT_MONITOR > /dev/null
        d.erase
    fi
    d.graph input=$TMP2
    d.mon select=$currmon
fi

# Create group file for GIS Manager
echo "End" >> "$TMP3"
if [ "$GIS_FLAG_G" -eq 1 ] ; then
    cat $TMP3 > $group".dm"
fi

# Create ps.map map file
echo "end" >> "$TMP4"
if [ "$GIS_OPT_PSMAP" ] ; then
    cat $TMP4 > $GIS_OPT_PSMAP.psmap
fi

# Create ps.map legend file
echo "end" >> "$TMP5"
if [ "$GIS_OPT_PSMAP" ] ; then
    cat $TMP5 > $GIS_OPT_PSMAP\_legend.psmap
fi

# Create text file to use with d.graph in GIS Manager
if [ "$GIS_FLAG_S" -eq 1 ] ; then
	tmpdir=`eval dirname $TMP6`
	tlegfile="$tmpdir/gismlegend.txt"
#	echo $tlegfile > outtxt.txt
    cp $TMP6 $tlegfile
fi

cleanup
