#! /bin/bash

# Usage of the works is permitted provided that this
# instrument is retained with the works, so that any entity
# that uses the works is notified of this instrument.
#
# DISCLAIMER: THE WORKS ARE WITHOUT WARRANTY.

if [ -z "$1" -o -z "$2" -o -z "$3" ]
then
  echo Error: Missing required parameter! >&2
  exit 1
fi
[ -z "$HEATSHRINK" ] && HEATSHRINK=heatshrink
source="$1"
destbase="$2"
destext="$3"
shift 3
dobreak=0

	mkdir -p "$destbase"
	rm -f "$destbase$destext"
	winmsg=""
	for w in 4 5 6 7 8 9 10 11 12 13 14; do
	  for l in 3 4 5 6 7 8 9 10 11 12 13; do
	    ((l >= w)) && continue
	    if msg="$("$HEATSHRINK" -ve -w $w -l $l \
		"$source" \
		"$destbase"/"w${w}l$l.bin" "$@")"; then
	      if [ ! -f "$destbase$destext" ] \
		|| (( ( $(stat -c %s "$destbase"/"w${w}l$l.bin") + 2 ) \
		  <= $(stat -c %s "$destbase$destext") )); then
		echo -ne "!"
		winmsg="$msg"
		printf "\x$(printf "%02X" "$w")\x$(printf "%02X" "$l")" > "$destbase$destext"
		cat "$destbase"/"w${w}l$l.bin" >> \
		  "$destbase$destext"
	      else
		echo -ne "."
	      fi
	    else
	      dobreak=1
	      break
	    fi
	  done
	  if ((dobreak))
	  then
	    break
	  fi
	done
	echo ""
	if [ -z "$winmsg" ]; then
	  echo "Error: Compression failure!"
	  exit 1
	else
	  echo "$winmsg"
	fi
