Initial code. Works as far as I've tested, which is not extensively.