Improve test coverage

Second PR on adding tests. I also did some refactoring to improve testability and corrected minor errors in argument parsing.

I prefer to send you small PR with incremental changes, but if you like I can send you larger PR less often. That might be harder to review and merges will be more problematic if changes occur in the meantime on master ...