Fixed bugs in error checking.
Added comments.