modified code to run efficiently