Accept most modifications from @coderanger