Some refactoring, some debugging. Generally works now