Fixed some bugs which I introduced with the last pull request.

Added tests for the cases which where broken.