#!/bin/sh

if [[ ${#} -ne 2 ]]; then
	echo "Usage: $0 <pkgname> <arch>" >&2
	echo "Where: <arch> is \"600\" or \"700\"" >&2
	exit 1
fi

name="${1##*/}"
name=${name%.*}
arch="${2}"
case ${arch} in
600)	fb=160;;
ROM)	fb=192; arch="600";;
700)	fb=0;;
*)	echo "<arch> must be \"600\", \"ROM\", or \"700\"" >&2
	exit 1
	;;
esac
ld1file="fnordering1.ld"
ld2file="fnordering2.ld"

# read pairs of lines, first is symbol name, second is label tag.
# todo: detect number spaces, architecture.
# TODO: handle case where HW_FIXED_SR0 (et al.) is used.
x=0
f=${fb}
# ensure no cruft is left-over...
echo -e "\t/* generated from ${name} */" > ${ld1file}
echo -e "\t/* generated from ${name} */" > ${ld2file}
while read line; do
	if [[ ${x} -eq 0 ]]; then
		sym="${line}"
		x=1
	else
		# redirect each line individually, so that file is closed/flushed
		# by the time 'ld' tries to read it.
		echo -e "\t*(.wang${arch}flabel.${sym})" >> ${ld1file}
		echo -e "\t*(.wang${arch}subr.${sym})" >> ${ld2file}

		# this line goes to the labeling output... not timing sensitive
		echo "${f} ${line}"
		((f+=1))
		x=0
	fi
done | awk -v name="${name}" \
'BEGIN{min=255;max=0;}
{
	f=$1+0;
	ff=$2;
	for (x=3; x<=NF; ++x) {
		ff=ff " " $x;
	}
	fc[f]=ff;
	if (f<min) min=f;
	if (f>max) max=f;
}
END{
	b=int(min/16);
	b=b*16;
	e=int((max+15)/16);
	e=e*16;
	while (b < e) {
		if ((b % 16) == 0) {
			if (b >= 208) {
				tag="SHIFT 4\\v 8\\v";
			} else if (b >= 192) {
				tag="4\\v 8\\v";
			} else if (b >= 176) {
				tag="SHIFT f(x)\\v";
			} else if (b >= 160) {
				tag="f(x)\\v";
			} else if (b >= 48) {
				tag="\\v\\s \\v\\s \\^\\s \\^\\s";
			} else if (b >= 32) {
				tag="\\v\\s \\v\\s \\^\\s \\v\\s";
			} else if (b >= 16) {
				tag="\\v\\s \\v\\s \\v\\s \\^\\s";
			} else {
				tag="\\v\\s \\v\\s \\v\\s \\v\\s";
			}
			printf "%s # left header %02x\n", tag, b;
		}
		if (b in fc) {
			l=fc[b];
			n=gsub(/_/," ",l);
			if (n > 0) {
				printf "<HTML><CENTER>%s</HTML>", l;
			} else {
				printf "%s", l;
			}
		}
		printf " # %02x\n", b;
		++b;
		if ((b % 16) == 0) {
			printf "%s # right header %02x\n", name, b-1;
		}
	}
}'
