Added more code for memory management