Some refactoring and memory management