Broke up a long function and rename/added variables to make the logic clearer.