#! /bin/bash

source="$1"
destination="$2"
maxw="$3"
minw="$4"
maxl="$5"
minl="$6"
shift 2
if (( $# >= 4 ))
then
  shift 4
elif (( $# >= 3 ))
then
  shift 3
elif (( $# >= 2 ))
then
  shift 2
elif (( $# >= 1 ))
then
  shift 1
fi

	  [ -z "$INICOMP_HEATSHRINK" ] && INICOMP_HEATSHRINK=heatshrink

	mkdir -p tmp
	rm -f "$destination"
	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
	    [ -n "$maxw" ] && ((w > maxw)) && continue
	    [ -n "$minw" ] && ((w < minw)) && continue
	    [ -n "$maxl" ] && ((l > maxl)) && continue
	    [ -n "$minl" ] && ((l < minl)) && continue
	    if msg="$("$INICOMP_HEATSHRINK" -ve -w $w -l $l "$@" "$source" "tmp/w${w}l$l.bin" 2>&1)"; then
	      if [ ! -f "$destination" ] \
		|| (( ( $(stat -c %s "tmp/w${w}l$l.bin") + 2 ) <= $(stat -c %s "$destination") )); then
		echo -ne "!"
		winmsg="$msg"
		printf "\x$(printf "%02X" "$w")\x$(printf "%02X" "$l")" > "$destination"
		cat "tmp/w${w}l$l.bin" >> "$destination"
	      else
		echo -ne "."
	      fi
	    fi
	  done
	done
	echo ""
	if [ -z "$winmsg" ]; then
	  echo "Error: Compression failure!"
	  false
	else
	  echo "$winmsg"
	  true
	fi
