Fix use of freed memory and clean up code