Added cleanup for memory and fixed cd off by 1 error