Made login robust and refactored to allow for tests; added tests