Hi your code is write. You made a small logical mistake.. You forget to clear flag. I tried your code as it is with resenting flag. It was working good.
flag = 0;