Revised code with the sugested ideas