#!/bin/sh
#
# Copyright (C) 2016 FAUmachine Team <info@faumachine.org>.
# This program is free software. You can redistribute it and/or modify it
# under the terms of the GNU General Public License, either version 2 of
# the License, or (at your option) any later version. See COPYING.
#

DIR=/opt/gcc-arm-none-eabi-4_8-2014q2/bin
PREFIX=arm-none-eabi

if [ $# != 1 ] ; then
	echo "Usage!"
	exit 1
fi

if [ -f labels ] ; then
	cat labels \
	| while read a t l c ; do
		if [ "${t}" = "func" -o "${t}" = "data" ] ; then
			echo "${a} ${l}"
		fi
	done > labels.$$
	./disas_bin labels.$$ < $1 > out.$$.s
	rm labels.$$
else
	./disas_bin < $1 > out.$$.s
fi

${DIR}/${PREFIX}-gcc -c out.$$.s -o out.$$.o

# ${DIR}/${PREFIX}-objdump -d out.$$.o > out.arm
${DIR}/${PREFIX}-objdump -d -M force-thumb out.$$.o > out.arm

if [ -f labels ] ; then
	cat labels \
	| while read a t l c ; do
		if [ "${c}" != "" ] ; then
			cat out.arm \
			| sed -e "s#<${l}>:#<${l}>: ; ${c}#" \
			> out.arm.$$
			mv out.arm.$$ out.arm
		fi

		cat out.arm \
		| sed -e "s|	${a} 	.*$|	${a}	.word ${l}|" \
		> out.arm.$$
		mv out.arm.$$ out.arm
	done
fi
if [ -f strings ] ; then
	cat strings \
	| while read a s ; do
		cat out.arm \
		| sed -e 's|	'"${a}"' 	.*$|	'"${a}"'	\&"'"${s}"'\\0"|' \
		> out.arm.$$
		mv out.arm.$$ out.arm
	done
fi

rm out.$$.o
rm out.$$.s
