Decided to re-write #146 due to bugs with previous solution.
Also made it a lot easier to read.