[Felix] Did lots of refactoring of the code and added better memory management