Incorporate fixes by emdagon

@emdagon I have pulled your changes to this repo.