It's actually not as hard as I thought, though surely has wierd edge cases which users might need to handle manually.