Lots of bug fixes

Github issues #26, 27, 28, 29, 35, 34, 37, 36, 40