Trying to refactor this unextractable beast of code