Started refactoring, fixed memory leaks
Finished refactoring