Second pass on code

First versions were hastily written so now going back and cleaning some
things up. Still a ways to go though.