Refactored based on reviewer comments; also includes some performance enhancements.