Changed code to reduce wasted operations