Bug, mem leaks and other minor fixes

Here are the fixes to some minor bugs that I found in your code. 
Please make sure that the code still runs your tests witout any problems (I'm running on windows so I can't really build them).