Fix memory management and tidy up