Morocco captain Mbark Boussoufa scored in the last minute to secure a 1-0 win over South Africa as his side took top spot in Group D at the Africa Cup of Nations with a 100 percent record.
It was a third successive one goal victory at the tournament for Morocco, who had already qualified for the last 16 and finished ahead of the Ivory Coast with South Africa third.
The Ivorians are in the knockout stage after beating Namibia 4-1 but South Africa must wait to see if they can reach the last 16 by finishing among the four best third-placed teams.
Boussoufa hammered home from close range after the South African defence failed to clear a 90th minute free kick.
As the top team in the group, Morocco will play a third-placed side in the first of the knockout games on Friday.
They finished with nine points ahead of Ivory Coast on six, South Africa on three and Namibia with none.
The game started at a languid pace as both sides adopted a cautious approach and were not prepared to be too expansive, lest they open up chances for the other.
It took more than 30 minutes for the first real effort as Percy Tau's shot for South Africa went narrowly wide.
But in the second half Morocco were much livelier and struck the woodwork as they began to pile on the pressure when flying fullback Achraf Hakimi hit a stinging shot from outside the penalty area that cannoned off the bar in the 64th minute.
There were also half chances for striker Youssef En-Nesyri, who first put a header wide and then went round the goalkeeper but hit the ball into the side netting from a tight angle.
Boussoufa's last-gasp goal mirrored Morocco's opening game when they beat Namibia thanks to an own goal in the last minute.