Improved code as suggested by dblock