Working implementation, some parts untested.