#!/bin/ksh
# Automatically runs all-to-all tournament between two or more chess engines
# and saves the games in the file which you can later preview or analyze.
# Use "scid" to compute the tournament crosstable (score, standings)
#
# Usage: $0 [-p] matchgames timecontrol results.pgn eng1 eng2 [eng3 ...]
#    -p: turn pondering ON (default: OFF)
#    matchgames:  how many games to play between each 2 engines
#    timecontrol: how many minutes for each 40 moves for each eng
#        (approx. total tournament time: 4*tc*mg*eng*(eng-1)/2)
#    results.pgn: filename where to store played games
#    eng1:  use wrapper scripts to 'cd' to engines directories
#           with their files (books, EGTBs etc.) and to run
#           them with their flags/options/priorities
#    
# Hints: - If you run "ssh machine engx" instead of "engx" in your engine
#          wrapper script, turn pondering ON.
#        - If you have 2 or more CPUs turn pondering ON.
#        - Don't turn pondering ON unless you know what you're doing
#          and why.
#
# For more info about computer engine tournaments see
# A Beginner's Guide to running Computer Chess Tournament (by Aaron Tay)
# http://www.aarontay.per.sg/Winboard/computer.html
#
# Requirements: xboard and engines
#               ksh (modern bash should be enough, change the first line)
#               bc (not needed but recommended)
#
# author: martin.macok@underground.cz, 2003
# licence: public domain

USAGE="$0 [-p] matchgames timecontrol results.pgn eng1 eng2 [eng3 ...]"
if [ "$#" -lt 5 ] ; then
	echo "$USAGE"
	exit 1
fi

if [ "$1" = "-p" ] ; then # pondering on
	PONDER=
	shift
else # pondering off (default)
	PONDER=x
fi

MG="$1"
TC="$2"
SGF="$3"
shift 3

ROUND=1
ROUNDS=$(echo "$#*($#-1)/2"|bc)

echo "Total tournament time approximately" \
     $(echo 4*"${ROUNDS}"*"${MG}"*"${TC}"|bc) "minutes"

for ENG1 in "$@" ; do
	for ENG2 in $(echo "$@"|sed "s/^\(.* \|\)$ENG1\( \|$\)//") ; do
		echo "Round ${ROUND}/${ROUNDS}: $ENG1 vs $ENG2"
		xboard -xexit -"${PONDER}"ponder -xmovesound \
		       -mg "$MG" -tc "$TC" -sgf "$SGF" \
		       -fcp "$ENG1" -scp "$ENG2"
		ROUND=$(($ROUND + 1))
	done
done

echo "Results file: $SGF"

