#!/bin/bash

set -e

while [ $# -gt 0 ]; do

    case $1 in
	*.err)
	    ERFILE=$(basename "$1" .err).errors
	    grep "Current strategy value: " "$1" | cut -f2 -d: | cut -b2- > $ERFILE
	    
	    R -q --no-save --vanilla <<EOF
data = read.csv("$ERFILE")
errors = data[[1]]
best.error = Reduce(max,errors,accumulate=TRUE)
improvement = c(FALSE,best.error[1:length(best.error)-1]!=best.error[2:length(best.error)])

pdf("${ERFILE}.pdf")

plot(x=1:length(errors),y=errors, type="l", col="red")
lines(x=1:length(errors),y=best.error, col="green")
points(x=(1:length(errors))[improvement], y=best.error[improvement])

dev.off()
EOF

	    	    R -q --no-save --vanilla <<EOF
data = read.csv("$ERFILE")
errors = -data[[1]]
errors = log(errors-min(errors)+1)
best.error = Reduce(min,errors,accumulate=TRUE)
improvement = c(FALSE,best.error[1:length(best.error)-1]!=best.error[2:length(best.error)])

pdf("${ERFILE}.log.pdf")

plot(x=1:length(errors),y=errors, type="l", col="red")
lines(x=1:length(errors),y=best.error, col="green")
points(x=(1:length(errors))[improvement], y=best.error[improvement])

dev.off()
EOF

	    
	;;
	*)
	    echo Bad file extension in "$1" Skipping
	    ;;
    esac
    
    shift
done
