Some edge cases remaining, but basically working.