Clean code and add some tests. Bug fix.