#!/bin/bash

## Decimal to hexa
d2h() {
  echo "obase=16; $@"|bc
}

## Tmp file cleanup
cleanup() {
if test -n "$VERBOSE"
then
	echo -e "!! Removing temporary files" >&2
fi	
if test -e "$fmidi7"; then rm -f "$fmidi7"; fi
if test -e "$fsplit-00"; then rm -f $fsplit-*; fi
}

argv=`getopt v $*`
set -- ${argv}
for i
do
	case "$i" in
	-v) shift
		VERBOSE="-v"
		echo "!! Verbose enabled" >&2
		;;
	--) shift;;
	esac
done

## song number
sn="$1"
let sn=sn+0
#======================= TEST FICHIER
if test ! \( "$sn" -gt 0 -a "$sn" -lt 16 \)   
then
	echo '?? uksyxify [-v] <song number 1-15> ' >&2
	cleanup
	exit 1
fi

#======================= CONVERSION 7BITS
fmidi7=`mktemp /tmp/uk7bits-XXXXX`
fsplit=`mktemp /tmp/uksplit-XXXXX`

if test -n "$VERBOSE"
then
	echo -e "!! fmidi7=$fmidi7\tfsplit=$fsplit" >&2
fi

cat | uk7bits > "$fmidi7"
rc=$?
if test $rc -ne 0
then
	echo "?? uksyxify : can't convert input file to  7bits format retcode=$rc" >&2
	cleanup
	exit 2
fi

#======================= SPLIT in 1024 bytes packets
split ${VERBOSE} -b 1024 -d "$fmidi7" "$fsplit-"
tb=`ls -1 $fsplit-* | wc -l`

#======================= First SYSEX 
## F0 00 20 63 
## 00 01 00 02
## 00 sn 00 tb  sn=song number 1-15 ; tb=total 1024 block number
## 89 7F
## Remplacer 89 par 09 sinon l'automate d'envoi foire dans usbmidi.c de alsa

hsn=`d2h $sn`
htb=`d2h $tb`
if test -n "$VERBOSE"
then
	echo -e "!! Header, total block $tb (0x$htb) to song $sn (0x$hsn)" >&2
fi	
echo -en "\xF0\x00\x20\x63\x00\x01\x00\x02\x00\x$hsn\x00\x$htb\x09\xF7" 

#======================= Several 1024 bytes blocks
## HEADER DE CHAQUE BLOC :
## F0 00 20 63
## 00 01 00 7F
## 00 sn 00 bn  sn=song number ; bn=block number
## 89 < 1024 bytes of 7bits encoded data....>  F7
## Meme chose, remplacer 89 par 09

bn=0
for fblock in `ls -1 $fsplit-* | sort`
do
	hbn=`d2h $bn`
	size=`stat -c "%s" ${fblock}`
	if test -n "$VERBOSE"
	then
		echo -e "!! Writing part $bn (0x$hbn) of $tb (0x$htb) : $fblock" >&2
	fi	
	echo -en "\xF0\x00\x20\x63\x00\x01\x00\x7F\x00\x$hsn\x00\x$hbn\x09"
	cat $fblock
	echo -en "\xF7"
## last block maybe incomplete
## having a look at midi output from U-key is easy with
## amidi -d -a -p hw:1
## "I'm alive" signal FE will stop from First Sysex to the last one
## you receive 90 3C 11 and 90 3C 33 with the first sysex
## then 90 3C 33 for each of the followinbg blocks
## except for the last one which trigger again the FE signal
	let bn+=1
done

cleanup

exit 0

