Fixed some memory leaks and some general cleanup