Almost there
Minus some corner cases, it is working.