Fixed most of the bugs in logic so that a schedule is now appropriately generated. Note that the ordering is not very clean