#!/bin/bash

if [ $# -ne 5 ] ; then
  echo "Usage: run ALG DATADIR FRAC DELTA WORKDIR"
  exit
fi
  
ALG=$1
DATADIR=$2
FRAC=$3
DELTA=$4
WORKDIR=$5
STARTDIR=`pwd`
if [ $SEMIBOUND_DIR ] ; then
  BASEDIR=$SEMIBOUND_DIR
else
  echo "SEMIBOUND_DIR not defined!"
  exit
fi

if [ ! -d $DATADIR ] ; then 
  echo "Directory $DATADIR does not exist!"
  exit
fi
cd $DATADIR
DATADIR=`pwd`
cd $STARTDIR

# copy the data to workdir
if [ -e $WORKDIR ] ; then
  echo "Directory $WORKDIR already exists!"
  exit
fi
mkdir -p $WORKDIR
cd $WORKDIR
WORKDIR=`pwd`

cp $DATADIR/* .

# ignore the unlabeled data, split the labeled into a train and test set
mv labeled labeled_all
mv unlabeled tmp
$BASEDIR/split $FRAC labeled_all
mv labeled train
mv unlabeled test
mv tmp unlabeled

# train and test
cd $BASEDIR/algs/$ALG
train $WORKDIR/train
predict $WORKDIR/test $WORKDIR/train $WORKDIR/test_preds
predict $WORKDIR/unlabeled $WORKDIR/train $WORKDIR/unlabeled_train_preds
train $WORKDIR/labeled_all
predict $WORKDIR/unlabeled $WORKDIR/labeled_all $WORKDIR/unlabeled_preds
cd $BASEDIR

for i in $WORKDIR/*_preds ; do
  algs/$ALG/labels $i > $WORKDIR/tmp
  mv $WORKDIR/tmp $i;
done;

# compute the test set bound
algs/$ALG/labels $WORKDIR/test > $WORKDIR/tmp
errors=`errors $WORKDIR/tmp $WORKDIR/test_preds`
cases=`lines $WORKDIR/tmp`
DELTASHARE=`perl -e "print $DELTA / 2"`
bound_for_rand=`upper_bound $DELTASHARE $cases $errors`
rm $WORKDIR/tmp;

# compute dist
errors=`errors $WORKDIR/unlabeled_train_preds $WORKDIR/unlabeled_preds`
cases=`lines $WORKDIR/unlabeled_train_preds`
DELTASHARE=`perl -e "print $DELTA / 2"`
bound_dist=`upper_bound $DELTASHARE $cases $errors`

# cheat and compute the error rate of the randomized ensemble on unlabeled data
algs/$ALG/labels $WORKDIR/unlabeled > $WORKDIR/tmp
errors=`errors $WORKDIR/tmp $WORKDIR/unlabeled_train_preds`
cases=`lines $WORKDIR/tmp`
error_rate=`perl -e "print $errors / $cases"`

perl -e "print $bound_for_rand + $bound_dist" > $WORKDIR/results
echo "" $bound_for_rand $bound_dist $error_rate >> $WORKDIR/results
cat $WORKDIR/results
GLOBIGNORE=$WORKDIR/results
rm $WORKDIR/*
