Turning back from the brink: Detecting an impending regime shift in time to avert it