I think you have missed to set $failed =1 between 548-552