Glamorgan 137 and 235 for 9 (van der Gugten 58*, Lloyd 54, Miles 4-47, M Taylor 4-71) lead Gloucestershire 354 (J Taylor 112, Charlesworth 72, van der Gugten 4-66) by 18 runs
When Timm van der Gugten joined Kieran Bull, with Glamorgan 150 for 8 and 32 overs still to play, Gloucestershire were contemplating a win within three days, a 45-minute drive up the M4, and a well-earned day off after outplaying Glamorgan for most of the game.
The Glamorgan tailenders, however, had other ideas as they resisted Gloucestershire's bowlers for the next 28 overs, with Bull showing commendable application in occupying the crease for 135 balls over nearly three hours. They shared a partnership of 73 for the ninth wicket before Bull was out for 30, but van der Gugten saw out the day unbeaten on a career-best 58.
Although the visitors should win easily enough on Thursday morning - the new ball is due in five overs - Glamorgan have avoided a fourth defeat by an innings, with a slender lead of 18 runs.
Gloucestershire had resumed their first innings on 284 for 6. Jack Taylor scored the two runs he needed to reach his seventh first-class century, before his seventh-wicket partnership of 155 with Ben Charlesworth was ended when the 17-year-old was caught at slip off van der Gugten for a composed 72.
Taylor then became van der Gugten's fourth victim when he was caught behind the wicket for 112, an innings that lasted 214 balls, with 14 fours and a six, while the bowler completed a splendid morning's spell of 10-6-12-2.
After Craig Miles and David Payne had further punished a tired Glamorgan attack, who were handicapped by a side injury to Ruaidhri Smith, the visitors were all out for 354, with Glamorgan facing four overs before lunch.
They swiftly descended to 6 for 3, as Miles, who is leaving Gloucestershire for Warwickshire at the end of the season, demolished the top order. He took three wickets in ten balls without conceding a run to leave Glamorgan reeling, having started their second innings 217 runs adrift.
Connor Brown was out first ball, then three balls later Miles trapped Tom Cullen leg before, and in his second over, he dismissed Kiran Carlson who collected a pair. Miles then dismissed Stephen Cook shortly after lunch, with Glamorgan on 34 for 4 and heading for yet another defeat within three days.
David Lloyd counterattacked with a brisk 54 from 59 balls with nine fours, but there was little resistance as Cooke and Wagg both departed cheaply. Smith emulated Lloyd with his attacking approach, and with Bull an able partner, the eighth-wicket pair put on 49, before Smith, who had struck seven fours in an enterprising innings was caught behind to give Matt Taylor a fourth wicket.