#!/bin/sh
#
# hpgl2heatmap - convert HPGL position plot to heatmap of position frequency
#
# Usage: hpgl2heatmap [-m mul] [hpglfile] ... > outfile.svg
#
# 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
#
#	 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.svg is the output file name, which will be an SVG-format
#		drawing 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
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 ;;
	-*)	set --; break ;;
	*)	break ;;
	esac
done

#case "$#" in
#0)	echo "Usage: hpgl2heatmap [-m mul] [hpglfile] ... > outfile.svg
#	or hpgl2heatmap --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

gnuplot <<!
set terminal svg size 800,600 dynamic enhanced
set output "/dev/stdout"
set view map
set dgrid3d
set pm3d interpolate 0,0
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
splot "$T" matrix title '' with pm3d
#plot "$T" matrix title '' with image
!
