Big refactor, fixing bugs