Bug fix and tests