improved code as suggested by Jedd