Cleaned up code, added comments, some input checking.