#! /bin/bash

# Script for testing of `ultoa_invert' function.
# Usage example:
#   ./invert-tst.sh  [msb]
# Single arg: start value of msb (must 0..255).
# It is desirable to check script before running in work mode: comment
#   line with `run_sim' to do this.

# 2005-02-10	Begin.
# 2005-02-12	Last modif.

src_list="ultoa_invert.S"
bname=invert-tst
avr_gcc=avr-gcc

set -e

core=core_avr_dump.core

simulavr=simulavr
if ! $simulavr --version 2>/dev/null ; then
    simulavr=~/usr/simulavr/bin/simulavr
fi

simul ()
{
    echo "-------- Begin= $begin  nvals= $nvals:  $*"
    mcu=$1
    shift
    $avr_gcc -W -Wall -I. -mmcu=$mcu -DBEGIN=${begin}u -DNVALS=$nvals \
	$* -o $bname.elf $bname.c $src_list
    exit_addr=0x`avr-nm $bname.elf | grep __stop_program | cut -f1 -d' '`
    avr-objcopy -O binary $bname.elf $bname.bin
    $simulavr -d $mcu -B $exit_addr -C $bname.bin >/dev/null
    if ! grep -q r24=00 $core || ! grep -q r25=00 $core
    then
	echo >&2 "*** Simulate: exit with non-zero code"
	exit 1
    fi
    rm -f $bname.{elf,bin} $core
}

run_sim ()
{
    for mcu in at90s8515 atmega8 ; do
	for opt in "-Os -frename-registers" ; do
	    simul $mcu $opt
	done
    done
}

msb=${1:-0}
if (( msb < 0 || msb > 255 )) ; then
    echo >&2 "*** Invalid start (msb)"
    exit 1
fi

let "begin = msb << 24, 1"
nvals=262144

if (( 16777216 % nvals )) ; then
    echo >&2 "*** Invalid nvals"
    exit 1
fi

success=
echo "Start with: msb= ${msb}, nvals= ${nvals}"
for (( ; msb < 256 ; msb++ ))
do
    for (( i = 0 ; i < 16777216 / nvals ; i++ ))
    do
	date
	run_sim
#	echo "begin= $begin"
	let "begin += nvals, 1"
	if [ $success ] ; then
	    echo "success: $success"
	fi
    done
    success=${success:+${success},}
    success=${success}${msb}
    echo -e "success: $success \a"
done

echo "All OK"

# eof
