Updated with fixes after running Valgrind for mem leaks