Please excuse code quality -- making it work, then making the code pretty.