Major derailment narrowly averted