Greatly reorganized code to use namespaces, lots of performance improvements, some utility functions.