corrected infinite loop problem in calc_rail_direction