Some memory leak and bugs resolved, besides minor code refactoring to be more homogeneous