changes and fixes made by dgstranz: https://github.com/dgstranz