Again fixes and refactoring. For issue #166