Refactor horrible code