Started refactoring, not quite working yet
Some more refactoring