optimize code, use flag as true/false