Penultimate commit. Still not able to fix some bugs. Valgrind found memory leaks