Added a few error checks, improved comments, and simplified several
functions.