More refactoring and optimizations. Currently has runtime errors.