Fix #126

This pull request fixes mainly #126, and some other things along the way.

Tests added.