Major speed improvements and some refactoring