Patch by Frans van Veen and Jasper Alias with modifications by me.