Moved some code around and ensured memory is freed