General refactoring, mainly on memory management