Implements #35.
Ported fix to #16.
Ported fix to #17