Basic code refactoring and speed-ups.