Complete refactoring to use more pragmatic, generic datastructures with helper functions.