Slightly simplified and optimized version.