improved optimisation funcition and added mem cleanup on delete