cleaned up code and added a few speedups