Cleaned up ugly code. Still need to put some removed logging back in