#!/bin/bash

if test $# = 0 ; then
	files="`ls *.mod`"
else
	files="$*"
fi
echo $files

t=temp
words="EXTERNAL discontinuity LINEAR DISCRETE PARTIAL ERROR"

for i in $files ; do

	f="`echo $i | sed 's/\.mod//'`"
	nocmodl $f.mod 2>&1 | sed '/^Translating/d' > $t
	nline=`wc -l $t`
	rm $f.c
	thread_safe=""
	for word in $words ; do
		if grep -q "$word"' is not thread safe' $t ; then
			thread_safe=no
		fi
	done
	if grep -q 'Complain to hines' $t ; then
		thread_safe=no
	fi

	echo "
$f.mod:"
	if test "$nline" = "0 temp" ; then
		echo "$f.mod is Thread Safe"
	elif grep -q '^Thread Safe$' $t ; then
		echo "$f.mod is Thread Safe"
	elif test "$thread_safe" = "no" ; then
		cat $t
		echo -n "Continue:"
		read a
	elif grep -q 'POINTER is not thread safe' $t ; then
		cat $t
		echo "$f.mod should be examined and if, in fact, it is
or can be modified to be thread safe, the THREADSAFE keyword can be
prepended to the NEURON block."
		echo -n "Continue:"
		read a
	elif grep -q 'Assignment to the GLOBAL' $t ; then
		sed -n '/NEURON *{/,/}/p' $f.mod
		sed -n '/VERBATIM/,/ENDVERBATIM/p' $f.mod
		cat $t
		a="n"
		echo "If you know that this model is in fact thread safe when
the GLOBAL variables that are written to are promoted to thread instance
variables, and therefore it is ok to add the THREADSAFE keyword, then ..."
		echo "Add THREADSAFE? [y][n]: $a"
		read a
		if test "$a" = "y" ; then
			sed '/NEURON *{/a \
    THREADSAFE
' $f.mod > $t
			cp $t $f.mod
		fi
	elif grep -q 'VERBATIM' $t ; then
		sed -n '/VERBATIM/,/ENDVERBATIM/p' $f.mod
		cat $t
		a="n"
		echo "If you know that this model is in fact thread safe so
that it is ok to add the THREADSAFE keyword, then ..."
		echo "Add THREADSAFE? [y][n]: $a"
		read a
		if test "$a" = "y" ; then
			sed '/NEURON *{/a \
    THREADSAFE
' $f.mod > $t
			cp $t $f.mod
		fi
	else
		cat $t
		echo -n "Continue:"
		read a
	fi
	rm $t
done
