Refactored, mostly working