Improved and optimized implementation