Rearranging some stuff and fixing memory leaks