Refactor of the login code to clean it up extensively and make it more readable.