Added more intelligent memory handling