while (flag == 0);

should be replaced by
marker = TRUE;
for (timer=maxtime; timer!=0; timer--)
PET_THE_PUPPY; // a macro to stroke the watchdog
if (flag == 1)
{
  marker = FALSE;
  break;
)
if (marker)
{
  error();
}