Substitute Bruno Zita Mbanangoye netted a brilliant last-minute free-kick to earn African Nations Cup co-hosts Gabon a stunning victory over Morocco and a place in the quarter-finals while dumping their opponents out.
In a frantic finale, Gabon had looked to have claimed the win as two goals in three minutes late on through Pierre-Emerick Aubameyang and Daniel Cousin saw them overturn a first-half deficit to lead 2-1 heading into injury time.
However, Morocco captain Houssine Kharja, who had earlier given his side a 24th-minute advantage, coolly rolled home a 90th-minute penalty to level up the scores and seemingly earn his side a vital draw.
There was still one late twist though as deep into stoppage time Gabon earned a free-kick to the left of the area and Mbanangoye stepped up to curl a superb effort inside the near top corner and send the home fans wild at the Stade de Angondje in Libreville.
The result means Gabon and Tunisia - who beat Niger 2-1 earlier today - are through to the last eight after winning both of their Group C matches so far, while Morocco and Niger bid an early farewell.
Morocco saw an early chance sliced wide by defender Michael Chretien but they took the lead soon after when Kharja picked up a good pass from Younes Belhanda on the edge of the area, turned inside his marker and drilled a low shot into the corner.
That goal separated the teams at the break but Gabon came close to an equaliser almost immediately after the interval when half-time replacement Cousin saw his effort parried by Nadir Lamyaghri.
Try as they might though it was beginning to look as though Gabon would end up empty-handed, until 13 minutes from time they drew level through Aubameyang.
The St Etienne striker, who scored one and set up the other in Gabon's 2-0 win over Niger on Monday, slammed home an unstoppable volley from the near the penalty spot after Morocco defender Jamal Alioui had been unable to get any distance on a clearing header.
That sparked scenes of joy in the stands but it was to get better for the hosts two minutes later as they took the lead.
Aubameyang turned provider with a pass inside to Cousin, whose turn on the spot wrong-footed marker Mehdi Benatia and allowed him the space to drill a low left-foot past stranded goalkeeper Lamyaghri.
Levy Madinda had a great chance to kill the game off for Gabon in the 85th minute but he blazed over from 10 yards out, and it looked as though that miss would prove costly as Morocco drew level in the 90th minute from the penalty spot.
With his side facing elimination, Kharja showed remarkable composure in the circumstances to slot home his spot-kick after Belhanda's shot struck the hand of Charly Moussono in front of goal.
However, that goal proved irrelevant moments later as Mbanangoye, an 84th-minute replacement, netted his brilliant free-kick to seal the win for Gabon.