Major rework, added some utility functions.