This took fucking ages and it still fails sometimes in edge cases, but I don't give a FUCK right now.