Fix leaks and tidy up