Fix 133

Pull request for fix #133 + general refactorings + unit tests.