This implementation is extremely complicated. I'm pretty sure there's a more succinct way of expressing it.