#!/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 vector map
#%  keywords: display, vector, thematic, legend
#%End
#%option
#% guisection: Files
#% key: map
#% type: string
#% gisprompt: old,vector,vector
#% description: Name of vector map
#% required : yes
#%end
#%option
#% guisection: Theme
#% key: type
#% type: string
#% description: Feature type
#% options: area,point,centroid,line,boundary
#% answer: area
#% required : yes
#%end
#%option
#% guisection: Theme
#% key: column
#% gisprompt: old_dbcolumn,dbcolumn,dbcolumn
#% type: string
#% description: Name of attribute column to use for thematic display (must be numeric)
#% required : yes
#%end
#%option
#% guisection: Theme
#% key: themetype
#% type: string
#% options: graduated_colors,graduated_points,graduated_lines
#% answer: graduated_colors
#% description: Type of thematic display
#% required : yes
#%end
#%option
#% guisection: Theme
#% key: themecalc
#% type: string
#% options: interval,std_deviation,quartiles,custom_breaks
#% answer: interval
#% description: Thematic divisions of data for display
#% required : yes
#%end
#%option
#% guisection: Theme
#% key: breakpoints
#% type: string
#% label: Break points for custom breaks option
#% description: Separate values by spaces (0 10 20 30 ...)
#% required : no
#%end
#%option
#% guisection: Theme
#% key: layer
#% type: integer
#% gisprompt: old_layer,layer,layer
#% description: Layer number
#% answer: 1
#% required : no
#%end
#%option
#% guisection: Points
#% 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
#% guisection: Points
#% key: size
#% type: double
#% label: Icon size for point data
#% description: Minimum icon size/line width for graduated points/lines)
#% answer: 5
#% required : no
#%end
#%option
#% guisection: Points
#% key: maxsize
#% type: double
#% description: Maximum icon size/line width for graduated points and lines
#% answer: 20
#% required : no
#%end
#%option
#% guisection: Theme
#% key: nint
#% type: integer
#% description: Number of classes for interval theme (integer)
#% answer: 4
#% required : no
#%end
#%option
#% guisection: Color
#% key: colorscheme
#% type: string
#% label: Color scheme for graduated color mapping
#% description: 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
#% guisection: Color
#% key: pointcolor
#% type: string
#% label: Color for graduated points map
#% description: GRASS named color or R:G:B triplet. Set color scheme to single color
#% answer: 255:0:0
#% required : no
#%end
#% option
#% guisection: Color
#% key: linecolor
#% type: string
#% label: Color for graduated lines or point/area outlines
#% description: GRASS named color or R:G:B triplet. Set color scheme to single color.
#% answer: 0:0:0
#% required : no
#%end
#% option
#% guisection: Color
#% key: startcolor
#% type: string
#% label: Beginning color for custom color gradient
#% description: Must be expressed as R:G:B triplet
#% answer: 255:0:0
#% required : no
#%end
#% option
#% guisection: Color
#% key: endcolor
#% type: string
#% label: Ending color for custom color gradient
#% description: Must be expressed as R:G:B triplet
#% answer: 0:0:255
#% required : no
#%end
#% option
#% guisection: Misc
#% 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
#%flag 
#% guisection: Files
#%key: g
#%description: Save thematic map commands to group file for GIS Manager
#%end
#%option
#% guisection: Theme
#% key: where
#% type: string
#% description: WHERE conditions of SQL statement without 'where' keyword
#% required : no
#%end
#%option
#% guisection: Files
#% key: psmap
#% type: string
#% label: Root for the name of psmap instruction files to be in current directory
#% description: If not set, no psmap instruction files will be created)
#% required : no
#%end
#%option
#% guisection: Files
#% key: group
#% type: string
#% gisprompt: new_file,file,group
#% description: Name of group file where thematic map commands will be saved
#% required : no
#%end
#%flag 
#% guisection: Theme
#%key: l
#%description: Create graphic legend in x11 display monitor
#%end
#%flag
#% guisection: Color
#% key: f
#% description: Only draw fills (no outlines) for areas and points
#%end
#%flag
#% guisection: Color
#% key: u
#% description: Update color values to GRASSRGB column in attribute table
#%end
#%flag 
#% guisection: Misc
#%key: s
#%description: Output legend for GIS Manager (for scripting use only)
#%end
#%flag 
#% guisection: Misc
#%key: m
#%description: Use math notation brackets in legend
#%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

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

# hard-coded parameter: the maximum number of legend items before
# we strip them using a middle ellipsis
MAX_LEG_ITEMS=18

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

#COLTYPE=... 
if [ -z "$COLTYPE" ] ; then 
   g.message -e message="No such column [$GIS_OPT_COLUMN]" 
   exit 1 
fi 

if [ "$COLTYPE" != "integer" ] && [ "$COLTYPE" != "double precision" ] ; then
   g.message -e message="Column <$GIS_OPT_COLUMN> is of type <$COLTYPE> which is not numeric."
   exit 1
fi

# create temporary file to hold output from v.univar
TMP1="`g.tempfile pid=$$`"
if [ $? -ne 0 ] || [ -z "$TMP1" ] ; then
    g.message -e "Unable to create temporary file for statistics"
    exit 1
fi

# create temporary file to hold d.graph commands for legend
TMP2="`g.tempfile pid=$$`"
if [ $? -ne 0 ] || [ -z "$TMP2" ] ; then
    g.message -e "Unable to create temporary file for legend"
    exit 1
fi

# Create temporary file to commands for GIS Manager group
TMP3="`g.tempfile pid=$$`"
if [ $? -ne 0 ] || [ -z "$TMP3" ] ; then
    g.message -e "Unable to create temporary file for group"
    exit 1
fi

# Create temporary file for commands for ps.map map file
TMP4="`g.tempfile pid=$$`"
if [ $? -ne 0 ] || [ -z "$TMP4" ] ; then
    g.message -e "Unable to create temporary file for ps.map legend"
    exit 1
fi

# Create temporary file for commands for ps.map legend file
TMP5="`g.tempfile pid=$$`"
if [ $? -ne 0 ] || [ -z "$TMP5" ] ; then
    g.message -e "Unable to create temporary file for ps.map legend"
    exit 1
fi

# create file to hold elements for GIS Manager legend
TMP6="`g.tempfile pid=$$`"
if [ $? -ne 0 ] || [ -z "$TMP6" ] ; then
    g.message -e "Unable to create temporary file for GIS Manager legend" 
    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" "$TMP2" "$TMP2.sort" "$TMP3" "$TMP3.sort" \
           "$TMP4" "$TMP4.sort" "$TMP5" "$TMP5.sort" "$TMP6" "$TMP6.sort"
}

# what to do in case of user break:
exitprocedure()
{
    g.message -e message='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
if [ "$GIS_FLAG_S" -ne 1 ] ; then
    currmon=`eval d.mon -L | grep "(selected)" | awk '{print $1}'`
fi

if [ -z "$currmon" -a "$GIS_FLAG_S" -ne 1 ] ; then
        g.message -e message='*** You must open a display monitor ***'
	cleanup
	exit 2
fi

# if running in the GUI, do not create a graphic legend in an xmon
if [ "$GIS_FLAG_S" -eq 1 ] ; then
    GIS_FLAG_L=0
    # if running in GUI, turn off immediate mode rendering so that the
    # iterated d.vect commands will composite using the display driver
    autowrite=$GRASS_PNG_AUTO_WRITE
    pngread=$GRASS_PNG_READ
    GRASS_PNG_READ=TRUE
    export GRASS_PNG_READ
    GRASS_PNG_AUTO_WRITE=FALSE
    export GRASS_PNG_AUTO_WRITE
fi

table=`v.db.connect "$GIS_OPT_MAP" -gl layer="$GIS_OPT_LAYER" fs="|" | cut -f2 -d'|'`
database=`v.db.connect "$GIS_OPT_MAP" -gl layer="$GIS_OPT_LAYER" fs="|" | cut -f4 -d'|'`
driver=`v.db.connect "$GIS_OPT_MAP" -gl layer="$GIS_OPT_LAYER" fs="|" | cut -f5 -d'|'`

if [ -z "$table" ] ; then
    g.message -e message="No table connected or layer <$GIS_OPT_LAYER> does not 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 driver=$driver| grep -i grassrgb`" ] ; then
        g.message message="Creating column 'grassrgb' in table '$table'"
        echo "ALTER TABLE $table ADD COLUMN grassrgb varchar(11)" | db.execute database="${database}" driver=${driver}
    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
  if [ "$GIS_OPT_TYPE" = "line" ] ; then
     v.univar -e -g map=$GIS_OPT_MAP type=line column=$GIS_OPT_COLUMN layer="$GIS_OPT_LAYER" > "$TMP1"
  else
     v.univar -e -g map=$GIS_OPT_MAP type=point,centroid column=$GIS_OPT_COLUMN layer="$GIS_OPT_LAYER" > "$TMP1"
  fi
else
  if [ "$GIS_OPT_TYPE" = "line" ] ; then
     v.univar -e -g map=$GIS_OPT_MAP type=line column=$GIS_OPT_COLUMN where="$GIS_OPT_WHERE" layer="$GIS_OPT_LAYER" > "$TMP1"
 else
     v.univar -e -g map=$GIS_OPT_MAP type=point,centroid column=$GIS_OPT_COLUMN where="$GIS_OPT_WHERE" layer="$GIS_OPT_LAYER" > "$TMP1"
 fi
fi
  
min=`grep 'min=' "$TMP1" | sed s/min=//`
max=`grep 'max=' "$TMP1" | sed s/max=//`
mean=`grep 'mean=' "$TMP1" | sed s/mean=//`
sd=`grep 'population_stddev=' "$TMP1" | sed s/'population_stddev='//`
q1=`grep 'first_quartile=' "$TMP1" | sed s/'first_quartile='//`
q2=`grep 'median=' "$TMP1" | sed s/'median='//`
q3=`grep 'third_quartile=' "$TMP1" | sed s/'third_quartile='//`
q4="$max"
ptsize="$GIS_OPT_SIZE"

if [ -n "$GIS_OPT_BREAKPOINTS" ] && [ "$GIS_OPT_THEMECALC" != "custom_breaks" ] ; then
    g.message -w "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=""
    ;;

 "*")
    g.message -e "Unknown themecalc type"
    cleanup
    exit
esac

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

# Prepare legend cuts for too large numint
if [ $numint -gt $MAX_LEG_ITEMS ]; then
    xupper=`echo $numint $MAX_LEG_ITEMS | awk '{print int($1 - $2/2)+1}'`
    xlower=`echo $MAX_LEG_ITEMS | awk '{print int($1/2)+1}'`
else
    xupper=0
    xlower=0
fi

# 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"

g.message message="Thematic map legend for column $GIS_OPT_COLUMN of map $GIS_OPT_MAP"
g.message message="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
	    ;;
        "*")
	    g.message -e message="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"

        g.message message="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"

        g.message message="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"

	

        g.message message="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 "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"

    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

    if [ $i -lt $xlower -o $i -ge $xupper ]; then
        xline1=`expr $line2 + 2`
        xline3=`expr $line2 - 1`
        echo "color $themecolor" >> "$TMP2"
        echo "polygon" >> "$TMP2"
        echo "5 $xline1" >> "$TMP2"
        echo "8 $xline1" >> "$TMP2"
        echo "8 $xline3" >> "$TMP2"
        echo "5 $xline3" >> "$TMP2"
        echo "color $linecolor" >> "$TMP2"
        echo "move 5 $xline1" >> "$TMP2"
        echo "draw 8 $xline1" >> "$TMP2"
        echo "draw 8 $xline3" >> "$TMP2"
        echo "draw 5 $xline3" >> "$TMP2"
        echo "draw 5 $xline1" >> "$TMP2"
        echo "move 14 $line2" >> "$TMP2"
        echo "color 0:0:0" >> "$TMP2"
        echo "text $openbracket$rangemin - $rangemax$closebracket $extranote"  >> "$TMP2"
    else
        if [ $i -eq $xlower ]; then
            echo "color 0:0:0" >> "$TMP2"
            echo "move 10 $line2" >> "$TMP2"
            echo "text ..." >> "$TMP2"
        else
            #undo next increment
            line2=`expr $line2 + 4`	    
        fi
    fi

    if [ $i -lt $xlower -o $i -ge $xupper ]; then
      echo "area $themecolor $linecolor - {$openbracket$rangemin - $rangemax$closebracket $extranote}" >> "$TMP6"

        if [ "$GIS_OPT_TYPE" = "line" -o "$GIS_OPT_TYPE" = "boundary" ] ; then
          echo "line 5% $xline1% 8% $xline1%" >> "$TMP5"
          echo "  color $linecolor" >> "$TMP5"
          echo "end" >> "$TMP5"
          echo "text 14% $xline1% $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% $xline1%" >> "$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% $xline1% $openbracket$rangemin - $rangemax$closebracket $extranote"  >> "$TMP5"
          echo "  ref center left" >> "$TMP5"
          echo "end" >> "$TMP5"
        else
          echo "rectangle 5% $xline1% 8% $xline3%" >> "$TMP5"
          echo "  color 0:0:0" >> "$TMP5"
          echo "  fcolor $themecolor" >> "$TMP5"
          echo "end" >> "$TMP5"
          echo "text 14% $xline3% $openbracket$rangemin - $rangemax$closebracket DCADCA $extranote"  >> "$TMP5"
          echo "  ref bottom left" >> "$TMP5"
          echo "end" >> "$TMP5"
        fi
    else
        if [ $i -eq $xlower ]; then
            echo "color 0:0:0" >>"$TMP5"
            echo "text 14% $xline3% ..." >> "$TMP5"
            echo "  ref bottom left" >> "$TMP5"
            echo "end" >> "$TMP5"

            echo "text - - - {...}" >> "$TMP6"
        fi
    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}" driver=${driver}
        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
    
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"

        g.message message="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"
	
        g.message message="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"

        g.message message="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 "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

    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 [ $i -lt $xlower -o $i -ge $xupper ]; then
        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"
    else
	if [ $i -eq $xlower ]; then
	    echo "color 0:0:0" >>"$TMP2"
	    echo "move 10 $line2" >> "$TMP2"
	    echo "text ..." >> "$TMP2"
            echo "text - - - ..." >> "$TMP6"
	else
	    # undo future line increment
	    line2=`expr $line2 + $lineht`
	fi
    fi

    if [ $i -lt $xlower -o $i -ge $xupper ]; then
        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"
    else
	if [ $i -eq $xlower ]; then
	    echo "text 25% $xline1% ..."  >> "$TMP5"
	    echo "   ref center left"  >> "$TMP5"
	    echo "end" >> "$TMP5"
	fi
    fi

        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}" driver=${driver}
        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

fi

if [ "$GIS_FLAG_S" -eq 1 ] ; then
    # reset display parameters
    GRASS_PNG_READ=$pngread
    export GRASS_PNG_READ
    GRASS_PNG_AUTO_WRITE=$autowrite
    export GRASS_PNG_AUTO_WRITE
fi

# Create graphic legend
if [ "$GIS_FLAG_L" -eq 1 -a "$GIS_OPT_MONITOR" != "none" ] ; then
    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"
    if [ -n "$currmon" ] ; then
      d.mon select=$currmon
    fi
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
