#!/bin/bash

############################################################################
#
# MODULE:       i.spectral
# AUTHOR(S):    Markus Neteler, 18. August 1998
# PURPOSE:      displays spectral response at user specified locations in group or images
# COPYRIGHT:    (C) 1999 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.
#
#############################################################################

# written by Markus Neteler 18. August 1998
#            neteler geog.uni-hannover.de
# 
# bugfix: 25. Nov.98/20. Jan. 1999
# 3 March 2006: Added multiple images and group support by Francesco Pirotti - CIRGEO
# this script needs gnuplot

#%Module
#%  description: Displays spectral response at user specified locations in group or images.
#%  keywords: imagery, raster, multispectral
#%End
#%option
#% key: group
#% type: string
#% gisprompt: old,group,group
#% description: Group input
#% required : no
#%end
#%option
#% key: raster
#% type: string
#% gisprompt: old,cell,raster
#% description: Raster input maps
#% multiple : yes
#% required : no
#%end
#%option
#% key: output
#% type: string
#% gisprompt: new,file,file
#% description: Write output to PNG image
#% multiple : no
#% required : no
#%end
#%flag 
#%key: i
#%description: Use image list and not group
#%end
#%flag 
#%key: m
#%description: Select multiple points
#%end
#%flag 
#%key: c
#%description: Show pick coordinates instead of numbering in the legend
#%end

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

PARAM_NUM=$#

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

#check if present
if [ ! -x "`which gnuplot`" ] ; then
    g.message -e "gnuplot required, please install first"
    exit 1
fi

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

if [ `d.mon -L | grep -w '^x[0-9]' | grep -vc 'not running'` -eq 0 ] ; then
    g.message -e "No graphics device open (requires d.mon X-windows display)"
    exit 1
fi

TMP1="`g.tempfile pid=$$`"
TMP2="`g.tempfile pid=$$`"

# get y-data for gnuplot-data file
# get data from group files and set the x-axis labels

xlabels=""

if [ ! "$GIS_OPT_GROUP" ] ; then
   if [ $GIS_FLAG_I -eq 0 ] ; then
      g.message -e "Please use -i if you don't use the 'group' parameter"
      exit 1
   fi
fi

if [ $GIS_FLAG_I -eq 0 ] ; then
    # Parse the group listing and set the x-axis labels as the map names
    RASTERMAPS=`i.group -g group="$GIS_OPT_GROUP" | tr '\n' ',' | sed -e 's/,$//'`
    NUMBANDS=`i.group -g group="$GIS_OPT_GROUP" | wc -l`

    xlabels=`i.group -g group="$GIS_OPT_GROUP" | cut -f1 -d'@' | \
        sed -e "s/^\|$/'/g" | awk '{print $1,NR ","}' | tr '\n' ' ' | \
        sed -e 's/, $//'`

else
  ## get data from list of files and set the x-axis labels
  RASTERMAPS="$GIS_OPT_RASTER"
  news=`echo $GIS_OPT_RASTER | sed 's+,+ +g'`
  as=0
  for g in $news; do 
    as=`expr $as + 1`
    if [ "$as" -eq "1" ]; then
       xlabels="'$g' $as"
    else
       xlabels="$xlabels, '$g' $as"
    fi
   done

   NUMBANDS=$as
fi

rm -f "$TMP2"

#RASTERMAPS=`echo $RASTERMAPS | sed 's+ $++g' | sed 's+ +,+g'`

if [ "$GIS_FLAG_M" -eq "0" ]; then
  d.where -1 | r.what input="$RASTERMAPS" null=0 > "$TMP1"
else 
  asss=0
  d.where | r.what input="$RASTERMAPS" null=0 > "$TMP1"
  cat "$TMP1" > tmper
  rm -f "$TMP1"
  for asas in $(cat "tmper"); do
    asss=`expr $asss + 1`
    echo $asas | sed 's+||+|'$asss'|+g' >> "$TMP1"
  done
fi

cc=0

TT="`cat "$TMP1" | sed 's+\*+0+g' | sed 's+|+ +g'`"

NUMCLICKS="`cat "$TMP1" | wc -l`"
START=0

# tell data to outpu in different files to accept multiple plots - cache coordinates for output
for hell in $( cat "$TMP1"); do
   START=`expr $START + 1`
   #cc=`expr $cc + 1`
   COORD[$START]="`echo $hell | cut -d'|' -f1,2 | tr '|' ' '`"
   #LABELS[$START]="`cat "$TMP1" | cut -d'|' -f3 `"
   TOT="`echo $hell | sed 's+\*+0+g' | sed 's+|+ +g'`"
   cc=0
   for ix in $TOT; do
    cc=`expr $cc + 1`
    if [ "$cc" -gt 3 ]; then
      echo $ix >> "$TMP2"_$START
    fi
   done

done

rm -f "$TMP1"

NUM=$NUMBANDS
#echo $NUM
#echo $NUMCLICKS RRRRRRRRRRRR
NUM2=`expr $NUM / $NUMCLICKS`
NUM2=`expr $NUM2 + 1`


# build data file
# the x-axis... depending on number of bands
rm -f data.dum

  i=0
  while [ $i != $NUMBANDS ]
   do
    i=`expr $i + 1`
    echo $i >> data.dum
   done 

r=0
while [ $r != $NUMCLICKS ]
do
  r=`expr $r + 1`
  paste -d' ' data.dum "$TMP2"_$r > data_$r
  rm -f "$TMP2"_$r
done

# paste to data file
#paste -d' ' data.dum "$TMP2" > data
xrange=`expr $NUMBANDS + 1`

# build gnuplot script
if [ -n "$GIS_OPT_OUTPUT" ] ; then
  echo "set term png truecolor large size 825,550" >> spectrum.gnuplot
  echo "set output '$GIS_OPT_OUTPUT'" >> spectrum.gnuplot
fi
echo "set xtics ($xlabels)" >> spectrum.gnuplot
echo "set grid" >> spectrum.gnuplot
echo "set title 'Spectral signatures'" >> spectrum.gnuplot
##echo "set yrange [0:255]" >> spectrum.gnuplot
echo "set xrange [0:$xrange]" >> spectrum.gnuplot
echo "set noclabel" >> spectrum.gnuplot
echo "set xlabel 'Bands'" >> spectrum.gnuplot
echo "set xtics rotate by -40" >> spectrum.gnuplot
echo "set ylabel 'DN Value'" >> spectrum.gnuplot

## if more then 2 points we can draw an interpolated spline:
#if [ $PARAM_NUM -gt 2 ]
#then
#   echo "set style data linespoints" >> spectrum.gnuplot
#   echo "plot 'data' with points pt 779, '' smooth csplines t 'spline interpolated'" >> spectrum.gnuplot
#else
   echo "set style data lines" >> spectrum.gnuplot
  

 rm -f data.dum

 i=0
str=""
  while [ $i != $NUMCLICKS ]
   do
    i=`expr $i + 1`
    if [ "$i" -eq "1" ]
     then
      if [ $GIS_FLAG_C -eq 0 ] ; then
        str="plot 'data_$i' title 'Pick $i'" 
      else
        str="plot 'data_$i' title '${COORD[$i]}'" 
      fi
     else
      if [ $GIS_FLAG_C -eq 0 ] ; then
        str=$str",'data_$i' title 'Pick $i'" 
      else
        str=$str",'data_$i' title '${COORD[$i]}'" 
      fi
     fi

   done 
str=$str" with linespoints pt 779"
echo $str >> spectrum.gnuplot


$GRASS_GNUPLOT spectrum.gnuplot 
 

i=0
while [ $i != $NUMCLICKS ]
   do
 i=`expr $i + 1`
 rm -f data_$i
done

rm -f spectrum.gnuplot
