#!/bin/bash
# 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
#% 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: output
#% 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: label with coordinates instead of numbering
#%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
    echo "$PROG: gnuplot required, please install first" 2>&1
    exit 1
fi

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

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
      echo "Please use -i if you don't use the 'group' parameter"
      exit 1
   fi
fi

if [ $GIS_FLAG_I -eq 0 ] ; then

	# ## PARSES THE GROUP FILES - gets rid of ugly header info from group list output
	i.group  group=$GIS_OPT_GROUP -l | sed 's+ in + +g' | grep "group" -v | grep "\-\-\-\-$" -v > "$TMP2"
	as=0
	lists=""
	xlabels=""
	ass=0
	for i in $( cat "$TMP2" ); do
		er=`expr $as % 2`
		as=`expr $as + 1`
		if [ "$er" -eq "0" ]; then
			ass=`expr $ass + 1`
			if [ "$as" -eq "1" ]; then
  	                  lists=$i
			  xlabels="'$i' 1"
			else
   	                  lists=$lists,$i
			  xlabels="$xlabels, '$i' $ass"
		        fi
 		fi       
	 done

NUMBANDS=$ass
RASTERMAPS="$lists"

# ## get data from list of files and set the x-axis labels
else
  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
  if [ `d.mon -L | grep -v 'not running' | wc -l | awk '{print $1}'` -eq 2 ] ; then
	  echo "Error: no graphic device open (d.mon)"
	  exit 1
  fi
  d.where -1 | r.what input=$RASTERMAPS > "$TMP1"
else 
  asss=0
  if [ `d.mon -L | grep -v 'not running' | wc -l | awk '{print $1}'` -eq 2 ] ; then
	  echo "Error: no graphic device open (d.mon)"
	  exit 1
  fi
  d.where | r.what input=$RASTERMAPS > "$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 large" >> 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 ylabel 'DN Value'" >> spectrum.gnuplot

## if more then 2 points we can draw an interpolated spline:
#if [ $PARAM_NUM -gt 2 ]
#then
#   echo "set data style linespoints" >> spectrum.gnuplot
#   echo "plot 'data' with points pt 779, '' smooth csplines t 'spline interpolated'" >> spectrum.gnuplot
#else
   echo "set data style 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 '$i'" 
      else
        str="plot 'data_$i' title '${COORD[$i]}'" 
      fi
     else
      if [ $GIS_FLAG_C -eq 0 ] ; then
        str=$str",'data_$i' title '$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
