#!/bin/sh

# Split combined S3 image file into separate hex files"

set -e

TOOL="`dirname $0`/prism2_srec"

if [ ! -x "$TOOL" ]; then
    echo "Could not find compiled prism2_srec tool using path '$TOOL'"
    exit 1
fi

TMPDIR=`mktemp -d srec_temp.XXXXXX` || exit 1
IN=$TMPDIR/data
PART=$TMPDIR/part
cat > $IN

num=0
while [ -s $IN ]; do
    num=$(($num+1))
    echo "Image $num"
    eline=`grep -n ^S6 $IN | head -1 | cut -f1 -d:`
    if [ -n "$eline" ]; then
	head -$eline $IN | grep -vE '^S6|^S4' > $PART
	tail +$(($eline+1)) $IN > $IN.tmp && mv $IN.tmp $IN
    else
	grep -vE '^S6|^S4' $IN > $PART
	rm $IN
    fi

    fname=`$TOOL dummydev $PART 2> /dev/null | grep "^Included file name" | head -1 | colrm 1 20`
    if [ -z "$fname" ] || echo "$fname" | grep -q /; then
	fname=image-$num.hex
    fi
    mv $PART $TMPDIR/$fname
    echo "  ==> $fname"
    $TOOL dummydev $TMPDIR/$fname 2> /dev/null | grep -E '^Component|0x8' || true
    echo
done

rm -f $IN $PART
echo "Resulting files in '$TMPDIR':"
ls -l $TMPDIR
