Fix issue #20 and fix a few bugs