improved flag checks with tmp vars when needed, refactoring