Break interactive login code out into function.

And fix a ton of bugs in it.