#!/bin/bash
#@DOC@ chack .lst file for badly defined variables
#
# Copyright (C) 2006  Nathan (Acorn) Pooley
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 2 as published by the Free Software Foundation.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License (gpl.txt) for more details. 
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
# 
# You can contact the author, Nathan (Acorn) Pooley, by writing
# to Nathan (Acorn) Pooley, 949 Buckeye Drive, Sunnyvale, CA  94086, USA
# or through the form at http://www.rawbw.com/~acorn/wand/feedback.html
# 

isok=1

list[0]=""
unset list
cnt=0
OPT_dolist=0
file=""

_addfile() {
	typeset j
	for j in "${list[@]}"
	do
		if [[ $j = $1 ]] ; then
			return
		fi
	done
	list[cnt]="$1"
	(( cnt = cnt + 1 ))
}

for i in "$@"
do
	if [[ $i = -l ]] ; then 
		OPT_dolist=1
	fi
	if [[ -f ${i%.*}.inc ]] ; then
		_addfile "${i%.*}.inc"
	fi
	if [[ -f ${i%.*}.asm ]] ; then
		_addfile "${i%.*}.asm"
	fi
	if [[ $i = *.lst || $i = *.hex ]] ; then
		if [[ -n $file ]] ; then
			echo "checkvars: ERROR: two .lst files specified:"
			echo "checkvars: ERROR:    $file"
			echo "checkvars: ERROR:    $i"
			isok=0
		fi
		file="${i%.lst}"
		file="${file%.hex}"
		file="$file.lst"
	fi
done

_catall() {
	for i in "${list[@]}"
	do
		cat "$i"
	done
}

_getlist() {
	grep '^v[ki]*_[a-z0-9A-Z_]* *[0-9a-fA-F]* *$' | \
	sed -n -e 's|^\(v[ki]*_[a-z0-9A-Z_]*\) *\([0-9a-fA-F]*\) *$|\2 \1|p' | \
	sort -u
}

_getlistb() {
	grep 'define.*b[ki]*_[a-z0-9A-Z_]*[ 	][ 	]*v' | \
	sed -n \
		-e 's|[ 	][ 	]*| |g' \
		-e 's|^ *#*define \(b[ki]*_[a-z0-9A-Z_]*\) \(v[a-z0-9A-Z_]*,[0-7]\).*|\2 \1|p' | \
	sort -u
}

_findprob() {
	err=0
	lastsym="???"
	lastaddr=x
	while read addr sym
	do
		if [[ $addr = $lastaddr ]] ; then
			echo "checkvars: sym $sym and $lastsym share addr $addr"
			err=1
		fi
		lastaddr=$addr
		lastsym=$sym
	done
	return $err
}

if [[ -n $file && ! -f $file ]] ; then
	echo "checkvars: ERROR: file not found: '$file'"
	isok=0
fi
if [[ -n $file && -f $file  ]] ; then
	cat $file | _getlist | _findprob || isok=0
fi

if (( cnt > 0 )) ; then
	_catall | _getlistb | _findprob || isok=0
fi

if (( OPT_dolist )) ; then
	
	if [[ -n $file && -f $file ]] ; then
		echo "checkvars: ================= List of variables for $file"
		cat $file | _getlist
	fi

	if (( cnt > 0 )) ; then
		echo "checkvars: ================= List of bit variables for ${list[*]}"
		_catall | _getlistb
	fi
	echo "checkvars: ================="
fi

if (( ! isok )) ; then
	echo "checkvars: VARIABLE ERROR!!!!"
	exit 1
fi
exit 0
