Added error checking for failed login; cleanup of code organization