Updating code to incorporate @cardil's changes, plus some of my own.
More to come.