Implements most of the logic, in an ugly way.