Major refactoring and re-write.
Major refactoring and re-write.