Merge of Themaister's patches and mine