Update code from ryanhiebert to make it simpler and more versatile.