Cleanup code and adds some speedups