Duanne Olivier and Hashim Amla helped South Africa remain on top against Pakistan as momentum swung back and forth on an eventful day two of the third Test.
The Proteas endured a dismal start in the field after Pakistan resumed on 17-2, with four drops and a missed run out coming inside the opening hour in Johannesburg.
Paceman Olivier (5-51), who had match figures of 11-96 in the first Test, finally made the breakthrough, but Babar Azam (49 off 55) and Sarfraz Ahmed (50 off 40) lifted Pakistan before the tourists lost their last five wickets for just 16 runs.
South Africa looked in trouble at 45-5 inside 15 overs, but Amla (42 not out) maintained his composure to get his team to stumps without further loss, meaning they hold a lead of 212 runs.
The Proteas wasted a number of chances early on, with nightwatchman Mohammad Abbas (11) inexplicably dropped by Temba Bavuma at gully off Vernon Philander (3-43).
Dale Steyn – who later appeared to be struggling with his troublesome right shoulder – saw Imam-ul-Haq (43) and Abbas put down by Dean Elgar, after a touch off Theunis de Bruyn, and Quinton de Kock respectively.
South Africa's wicketkeeper was then unable to gather an outside edge from Imam, who was oblivious to Abbas attempting to snatch a run. The latter had to turn back but Kagiso Rabada failed to punish him, missing the stumps with his throw.
De Bruyn finally held on to an opportunity as Abba fell to Olivier, who removed Asad Shafiq for a three-ball duck in the same over.
Babar turned up the tempo in a fine knock that included 10 fours – half of which came from two Steyn overs – but Imam was unable to make it through to lunch unscathed.
Sarfraz shared a 78-run partnership for the sixth wicket until the Pakistan captain was taken at first slip by Amla, Babar then falling shy of his half-century to Olivier just four balls later.
Olivier was unable to complete a hat-trick after dismissing Faheem Ashraf (0) but Pakistan were skittled for 185 when Rabada (2-41) had Shadab Khan caught at gully for five.
Pakistan were unsuccessful with a review for lbw against Aiden Markram (21) but Sarfraz got it right in the next over, his challenge showing Elgar had edged Mohammad Amir (1-28) through to the wicketkeeper.
Markram went to Abbas in the first over after tea and, after another poor challenge from Sarfraz failed to get rid of Amla, Faheem (2-19) claimed the scalps of De Bruyn (7) and Zubayr Hamza (0) in the space of three balls.
The home team appeared in real troubl at that stage, yet Amla responded with back-to-back fours off Hasan Ali (0-27), who at one stage was forced to stop in his run-up due to a swarm of insects that bugged Pakistan in the field in the final session.
De Kock - who reached the close unbeaten on 34 - helped keep the score ticking over and the pair made it to the close with an unbeaten 42-run union that Pakistan will need to break early on day three.