Multiple fixes and improvements

Replaces #15, #23 and #26.

Hopefully i got it right this time...