#!/bin/sh
#
# hpgl2heatimg - convert HPGL position plot to heatmap of position frequency
#
# Usage: hpgl2heatimg [-m mul] [-s] [-i] [hpglfile] ... > outfile.png
#
# where: -m mul	specifies the scaling factor by which the coordinates will be
#		multiplied (default is 1). By default, the figures are scaled
#		so that data in the HPGL input file represent centimeters on
#		the 25x18cm drawing region of a plotter page. You should set
#		this to match what was specified as a multiplier to plotposn
#
#	 -s	specifies that output will be SVG-format, rather than PNG
#		(currently only works with -i option)
#
#	 -i	specifies that data will be interpolated into a surface plot
#
#	 hpglfile is one (or more) HPGL plot files, likely produced from the
#		plotposn script, showing the position tracking produced by
#		a motion capture system's coordinate output
#		(if no file specified, the script reads from its std input)
#
#	 outfile.png is the output file name, which will be a PNG-format
#		image file
#
# Scaling of the output graph corresponds to the HPGL coordinate system, in cm.
# Colour scale is set to be equivalent to Matlab heat maps.
#
# Copyright (c) 2018, Gilles Detillieux, Spinal Cord Research Centre,
# University of Manitoba.  All Rights Reserved.
#

mopt=1
sopt=0
iopt=0
while :
do
	case "$1" in
	-\?|-help|--help)	sed -n '3,/^# Univ/s/^#/ /p' "$0"; exit ;;
	-m[-.0-9]*)	mopt=`expr "x$1" : 'x-m\(.*\)'`; shift ;;
	-m)	shift; mopt="$1"; shift ;;
	-s)	sopt=1; shift ;;
	-i)	iopt=1; shift ;;
	-*)	set --; break ;;
	*)	break ;;
	esac
done

#case "$#" in
#0)	echo "Usage: hpgl2heatimg [-m mul] [-s] [-i] [hpglfile] ... > outfile.png
#	or hpgl2heatimg --help	for detailed usage information" >&2; exit 1 ;;
#esac

T=`mktemp /tmp/hhpl.XXXXXXXX`
trap "rm -f $T" 0
trap "exit 1" 1 2 3 13 15

replot -t ${@+"$@"} | tr ',;' ' \012' | sed -n '/^P[DU][0-9]/s/^P[DU]//p' |
 awk '{++cnt[int(($1-80)/400/'"$mopt"')][int(($2-320)/400/'"$mopt"')];}
      END{for(j=0;j<=int(18/'"$mopt"'+0.5);++j){
		for(i=0;i<=int(25/'"$mopt"'+0.5);++i)printf(" %2d",cnt[i][j]);
	print "";}}' > $T

case "$sopt" in
1)	sopt="svg size 800,600 dynamic enhanced" ;;
*)	sopt="png size 800,600" ;;
esac

case "$iopt" in
1)	iopt="set dgrid3d
set pm3d interpolate 0,0
splot" with=pm3d ;;
*)	iopt="plot" with=image ;;
esac

gnuplot <<!
set terminal $sopt
set output "/dev/stdout"
set view map
set palette defined (0 0 0 0.5, 1 0 0 1, 2 0 0.5 1, 3 0 1 1, 4 0.5 1 0.5, 5 1 1 0, 6 1 0.5 0, 7 1 0 0, 8 0.5 0 0)
#set palette rgbformula -7,2,-7
#set palette grey
$iopt "$T" matrix title '' with $with
!
