Major refactor. Lots of debugging ahead