Based on patch by Johan Sagaert, but with some additional tweaks. Signed-off-by: Peter Korsgaard <jacmet@sunsite.dk>