Almost done. Bug fix. Need some tests and a bit refactor