South Africa topped Group A with a 2-2 draw against Morocco on a dramatic night in the African Cup of Nations.
The result means Morocco bow out, while Cape Verde join Bafana Bafana in the last eight.
Morocco took the lead early on when Issam El Adoua nodded in from a corner, but South Africa levelled when May Mahlangu curled in from distance.
Morocco hit back again through substitute Abdelilah Hafidi, but Siyabonga Sangweni turned the game on its head again with a late equaliser that broke Morocco hearts.
Only victory against Morocco would have guaranteed hosts South Africa a place in the knockout phase, so things got off to a far from ideal start when slack marking allowed El Adoua to nip in and head Abdelaziz Barrada’s corner past the helpless Itumeleng Khune in goal.
Bafana Bafana reacted well to going behind and started to dominate – but experienced difficulty creating clear-cut opportunities.
In fact, the closest South Africa came in the first half was a shot by Bernard Parker that flashed across goal and past the post.
South Africa registered their first shot on target early in the second half when Thuso Phala bent a free-kick around the wall and forced Nadir Lamyaghri to punch away.
But Morocco started to see more of the ball in the second period and could have sewn the game up just before the hour when Youssef El Arabi was sent clean through on goal, but the striker’s attempted chip was saved brilliantly by Khune, who raced off his line to make the stop.
Just as Morocco were getting closer to securing the result they needed to progress, South Africa struck. Mahlangu found space on the edge of box and coaxed the ball into the far corner in some style.
Morocco reacted well to the equaliser and put their noses in front once again when the two substitutes combined to score their second, with Hafridi finishing Zakarya Bergdich’s cross.
But just as Morocco appeared to be going through, the game took another twist as Sangweni’s classy finish completed a thrilling finale and sent Bafana Bafana through.