Minor refactoring and speed improvements