#!/bin/sh

set -e

usage() {
	while [ $# -gt 0 ]; do echo "$1" >&2; shift; done
	echo "usage: ${0##*/} [-c] [-m minnum] [-M maxnum] [-n count] prog infile out1file out2file" >&2
	exit 1
}

iterations=100
max_nums=100
minnum=-1000
maxnum=1000
cnt_first=false

while getopts "ci:m:M:n:" opt; do case $opt in
	c)	cnt_first=true;;
	i)	iterations=$((OPTARG + 0));;
	m)	minnum=$((OPTARG + 0));;
	M)	maxnum=$((OPTARG + 0));;
	n)	max_nums=$((OPTARG + 0));;
	*)	usage;;
esac; done
[ $iterations -gt 0 ] || usage "invalid iterations count";
[ $max_nums -gt 0 ] || usage "invalid maximum numbers count";

shift $(($OPTIND - 1))
[ $# -eq 4 ] || usage
prog=$1; shift
infile=$1; shift
out1file=$1; shift
out2file=$1; shift

make $prog

while [ $((iterations--)) -ne 0 ]; do
	cnt=$(jot -r 1 1 $max_nums)
	nums=$(jot -r $cnt $minnum $maxnum)
	echo -n >"$infile"
	$cnt_first && echo -n "$cnt " >$infile
	echo $nums >>$infile
	t0=$(mktemp t0.XXXXXXXX)
	$cnt_first && echo $cnt >$t0
	echo $nums | awk -v RS=" " // | grep -v '^[[:space:]]*$' | sort -n >>$t0

	rm -f -- "$out1file" "$out2file"	# for "a" mode programs
	./$prog

	t1=$(mktemp t1.XXXXXXXX)
	$cnt_first && echo -n "$cnt " >$t1
	awk -v RS=" " // <"$out1file" | grep -v '^[[:space:]]*$' >$t1
	t2=$(mktemp t2.XXXXXXXX)
	$cnt_first && echo -n "$cnt " >$t2
	awk -v RS=" " // <"$out2file" | grep -v '^[[:space:]]*$' >$t2

	diff -u $t0 $t1
	diff -u $t0 $t2

	rm $t0 $t1 $t2
done
