Fixed PCH build, some leaks and tidied the code up a bit