Improved range function