Fix length calculation, fix cast, and some cleanup

This series fixes an embarrassing issue in one of the commits from PR #53 (which was also missed by three well-qualified reviewers before the PR was submitted).  It also contains some additional safety checks and some cleanup.  Please see the commit messages for details.