Refactors code heavily