Added more code to improve memory efficiency