complete refactoring and add number of speed improvements