Pretty working but for corner cases, throws exceptions.
Now working albeit a bit dirty.