Merged code tidy from @jakobloekke into latest version, added more comments