Fixed bug #740 by using a simpler and smarter approach. Patch from Ko van