Small refactoring, move code in classes and another small bugfixes.