Fix a few issues

I fixed a few potential crashes and cleaned up some code. Hopefilly improves performance.