Added some defensive code and explanatory comments.