Merge in request #277 and #341 and add my own fixes on top.