#!/bin/sh
#
# burstbars -- convert cycle start and end markers to burst bars in plot
#
# Usage:  burstbars [-c] pltfile.plt > outfile.plt
#
# where:  -c		specifies that the crossings should be left in place
#	  pltfile.plt	specifies the name of the plot file to be converted
#	  outfile.plt	specifies the output plot file name
#
# The specified raw waveform plot file is examined to find the characteristic
# vertical bars of the cycle start and end crossing markers.  These markers
# are suppressed in the output, and replaced with horizontal bars spanning
# the start to end of each burst, at the bottom of the plot, between the
# bottom waveform and the time scale bar.  The plot file must be produced
# using pen number 3 for Markers (Plot/Markers 3), and with both the
# "Display crossings" (Set/W.F.-disp/Mark-crossings) and the
# "Display both crossings" (Set/W.F.-disp/Both-crossings) options set to Y.
#
# If the -c option is specified, the vertical crossing markers are not
# suppressed, but the horizontal bars are added in.
#
# Copyright (c) 2011, Gilles Detillieux, Spinal Cord Research Centre,
# University of Manitoba.  All Rights Reserved.
#

copt=n
while :
do
	case "$1" in
	-\?|-help|--help)	sed -n '3,/^# Univ/s/^#/ /p' "$0"; exit ;;
	-c*)	copt=y; shift ;;
	-*)	set --; break ;;
	*)	break ;;
	esac
done

if [ "$#" -ne 1 ]
then
	echo "Usage:  $0 [-c] pltfile.plt > outfile.plg
	or  $0 --help  for detailed usage information" >&2
	exit 1
fi

perl -p -e '
  if (/^PU;SP(\d+);$/) {
	$pen = $1;
  } elsif (/^PU(\d+),(\d+);LO(\d+);LB.*;$/) {
	if ($3 == 18) {
		if ($minwfy eq "" || $minwfy > $2) {
			$minwfy = $2;
		}
	} elsif ($3 == 16) {
		if ($maxtsy eq "" || $maxtsy < $2) {
			$maxtsy = $2;
		}
	}
  } elsif (/^PU(\d+),(\d+);PD(\d+),(\d+);$/
			&& $pen == 3 && $1 == $3 && $2 > $maxtsy+100) {
	if ($2 < $minwfy+100) {
		if ($lasty ne "" && $lasty < $2) {
			$y = int(($2 + $maxtsy+50) / 2);
			print "PU$lastx,$y;PD$1,$y;\n";
		}
		$lastx = $1;
		$lasty = $2;
	}
	s/^.*// if ("'"$copt"'" eq "n");
  }
' ${@+"$@"}
