#!/bin/bash

# Change this path
ACODIR=~/algorithms/ACOTSP-1.03-COMPILE/

# parameters should be always passed to ACOTSP
FIXED_PARAMS=" --time 0 --tries 1 --quiet --tours 100000"
CHOSEN_PARAMS="--acs --localsearch 0 --alpha 3.82 --beta 9.38 --rho  0.55 --ants 59 --nnls 11 --q0 0.28 --dlb 1"

# The instance name and the candidate id are the first parameters
CANDIDATE=$1
INSTANCE_ID=$2
SEED=$3
INSTANCE=$4

# All other parameters are the candidate parameters to be passed to ACOTSP
shift 4 || exit 1
CAND_PARAMS=$*

# Create temporary directory
MYDIR=`mktemp -d`

# In case of error, we print the current time:
error() {
    echo "`TZ=UTC date`: error: $@" >&2
    exit 1
}

# Copy code
cd "${MYDIR}"
cp -R "${ACODIR}" .

GCCOUT="${MYDIR}/c${CANDIDATE}-${INSTANCE_ID}-${SEED}.gccout"
GCCERR="${MYDIR}/c${CANDIDATE}-${INSTANCE_ID}-${SEED}.gccerr"

cd "ACOTSP-1.03-COMPILE"

# Compile with the specified options
if [ -z "$CAND_PARAMS" ] ; then
  make 1> ${GCCOUT} 2> ${GCCERR}
else
  make OPTIONS="${CAND_PARAMS}" 1> ${GCCOUT} 2> ${GCCERR}
fi 

if [[ -s $GCCERR ]] ; then
  echo "10000000"
  exit 0
fi

STDOUT="c${CANDIDATE}-${INSTANCE_ID}-${SEED}.stdout"
STDTIME="c${CANDIDATE}-${INSTANCE_ID}-${SEED}.stdtime"
STDERR="c${CANDIDATE}-${INSTANCE_ID}-${SEED}.stderr"

# Execute the benchmark
/usr/bin/time --format "MARK %S %U" -o ${STDTIME} ./acotsp ${FIXED_PARAMS} ${CHOSEN_PARAMS} --seed $SEED -i $INSTANCE 1>${STDOUT} 2>${STDERR}

# The output of the candidate $CANDIDATE should be written in the file 
# c${CANDIDATE}.stdout (see hook run for ACOTSP). Does this file exist?
if [ ! -s "${STDOUT}" ]; then
    # In this case, the file does not exist. Let's exit with a value 
    # different from 0. In this case irace will stop with an error.
    error "${STDOUT}: No such file or directory"
fi

# Ok, the file exist. It contains the whole output written by ACOTSP.
# This script should return a single numerical value, the best objective 
# value found by this run of ACOTSP. The following line is to extract
# this value from the file containing ACOTSP output.
T1=$(cat ${STDTIME} | grep 'MARK' | cut -d ' ' -f2)
T2=$(cat ${STDTIME} | grep 'MARK' | cut -d ' ' -f3)
COST=${T2}
if ! [[ "$COST" =~ ^[-+0-9.e]+$ ]] ; then
    error "${STDTIME}: Output is not a number"
fi

# Print it!
echo "$COST"

# We are done with our duty. Clean files and exit with 0 (no error).
rm -rf "${STDOUT}" "${STDERR}" "${STDTIME}" "${GCCOUT}" "${GCCERR}"
rm -rf best.* stat.* cmp.* 
cd ..
rm -rf "${MYDIR}"

exit 0
