Fixes inspired from:
http://stackoverflow.com/a/3821998/360844
and
https://github.com/zagaberoo/diode/commit/1dee920b1399df5bd3817d479c6ce48c5236fcd7