Fix top-ordering to work properly in the presence of loops