add optimization to remove redundant loops