Fixed memory leaks, added comments