Almost completely re-wrote the first version of the class.