#!/bin/bash
export LC_ALL=en_US.UTF-8
touch ramso
time=0.1
FreeRam=$(free|grep "Mem:"|sed -n 's/  */ /gp'|cut -d " " -f7)
MinFreeRam=$(cat "logs/minFreeRam" | cut -d " " -f1)
if [ -z $MinFreeRam ];then MinFreeRam=$FreeRam;fi
loopcount=0

while [ ! -e "ramsc" ]
do
	((loopcount++))
	FreeRam=$(free|grep "Mem:"|sed -n 's/  */ /gp'|cut -d " " -f7)
	if [ $MinFreeRam -gt $FreeRam ]
		then MinFreeRam=$FreeRam
		fi
	if [ $MinFreeRam -gt 3200000 ]
		then time=1
		fi
	if [ $MinFreeRam -gt 7500000 ]
		then time=3
		fi
	if [ $MinFreeRam -lt 7500000 ]
		then time=1
		fi
	if [ $MinFreeRam -lt 3200000 ]
		then touch logs/LOWram.warning
		time=0.5
		fi
	if [ $MinFreeRam -lt 2000000 ]
		then time=0.2
		fi
	if [ $MinFreeRam -lt 1000000 ]
		then time=0.1
		fi
	if [ $loopcount -lt 50 ] && [ $MinFreeRam -gt 7500000 ]
		then time=1
		fi
	if [ $loopcount -lt 40 ] && [ $MinFreeRam -gt 3200000 ]
		then time=0.3
		fi
	if [ $loopcount -lt 10 ]
		then time=0.1
		fi
	if [ $loopcount -gt 400000 ]
		then exit
		fi
	if [ -e "runFAILED" ] || [ -e "runOK" ] || [ ! -e "runSTARTED" ]
		then exit
		fi
	sleep $time
done

Ram=$(free|grep "Mem:"|sed -n 's/  */ /gp'|cut -d " " -f2)
echo $MinFreeRam" / "$Ram > logs/minFreeRam
if [ -e "logs/LOWram.warning" ];then echo "Warning: During the meshing process, a low amount of available RAM was detected. If not anough RAM is avalable, the meshing process will crash. Maybe another application used too much RAM while this process was running. Or maybe the detail size parameter you use is too small for this geometry. The more RAM you have on your computer, the more cells you can mesh." > logs/LOWram.warning;fi

