Updated code to release memory at the end