adding optimization to the  function.