#!/bin/bash

rm -f tmp.training tmp.test
prev=0

get_test(){
  grep -C1 accuracy\ = $1 | while read line; do 
    if [[ "$line" =~ Iteration ]]; then i=$(echo $line | sed -e 's/^.*Iteration //g' -e 's/, Testing.*$//g'); fi
    if [[ "$line" =~ accuracy ]]; then a=$(echo $line | sed -e 's/^.*accuracy = //g'); fi
    if [[ "$line" =~ loss ]]; then 
        l=$(echo $line | sed -e 's/^.*: loss = //g' -e 's/ (.*$//g')
        echo $i $a $l
    fi
  done
}

get_train(){
  egrep '(Test net output.*|Iteration [0-9]*,) loss =' $1 | sed -e 's/.*Iteration //g' -e 's/, loss =//g' | while read a b; do 
	if [[ "$a" =~ ^[0-9]+$ ]]; then
		echo "$a	$b"
	fi
  done
}

extract_data(){
  get_test $1 > tmp.test
  get_train $1 > tmp.train
  mv tmp.test test.dat
  mv tmp.train train.dat
}

extract_data $1
gnuplot -e "set title 'Monitoring $1'" caffe.plot &

while sleep 5; do 
    extract_data $1
done 

