Refactoring almost done (still have to debug, tho)