I don't know why the flag is changing on every single iteration.  It shouldn't and I think it is in the calculate_metric method().