Moved code around to improve clarity and reduce PEP8 errors.