added clamp function to prevent overflow