Mostly working now, although it needs some refactoring.