Mem leak fixed; some refactoring