#!/bin/bash
echo "create run modules depending on run variable"
string=$1;
project=${string%.*};		# skip extension
runfile="run_$project.scad";
begin="/* runstart Start:autogenerated run file */";
einde="/* runeind End:autogenerated run file */";
echo "$begin" > $runfile
grep "^module " $project.scad | awk '{print $2}' | awk -F '(' '{print $1}' | while read -r line ; do
echo $line;
echo "if (run == \"$line\") { $line(); } " >> $runfile;
done
echo "$einde" >> $runfile
echo "Done";

echo -n > tempfile.tmp;
begin="/* runstart";
einde="/* runeind";
skip="0";
while IFS= read -r line
do

if [[ "$line" == "$begin"* ]]; then 
	skip="1";
fi
if [  "$skip" ==  "1" ] && [[  "$line" ==  "$einde"* ]]; then
	skip="2";
fi 
if [  "$skip" ==  "0" ] || [ "$skip" == "3" ]; then 
	echo "$line" >>tempfile.tmp;
fi

if [  "$skip" ==  "2" ]; then
	cat $runfile >>tempfile.tmp;
	skip=3;
fi
#	echo "$skip:: $line" 
done < "$project.scad"
if [  "$skip" ==  "0" ]; then
	cat $runfile >>tempfile.tmp;
fi
mv $project.scad backup_$project
mv tempfile.tmp $project.scad
rm $runfile
