Inside Hillsborough castle around 10pm on Tuesday, just hours after he had flown from Downing Street to Belfast with the Northern Ireland talks teetering on the verge of collapse, Tony Blair received a poignant history lesson.

Lord Alderdice, the bearded leader of the centrist Alliance Party, brought his colleague Sir Oliver Napier to see the Prime Minister in his makeshift offices on the third floor of the Stormont building.

The room was already cluttered with draft treaties, notes and coffee cups. The team of six accompanying Blair were busy installing themselves, arranging meetings and taking briefings.

Alderdice introduced Blair to Napier who had served in the ill-fated 1974 power-sharing executive, brought down by loyalist political opposition backed up with paramilitary muscle and the Ulster Workers' Strike.

Napier told Blair about his experiences as a Minister in the executive and particularly of the deal which brought it into being. He recalled the experience of Brian Faulkner, the Ulster Unionist leader who headed it, and how he had been pressurised by Ted Heath into signing something he not could sell to his fellow Unionists. 'Faulkner went too far too quickly and was destroyed by Paisley,' Napier told Blair.

The parallels with the dilemma facing David Trimble that Tuesday evening were too obvious to spell out. He needed a package he could sell to his increasingly restive party. Blair should not repeat Heath's mistakes.

Napier's memory was all the more pressing because by that stage it seemed that the UUP were poised to reject the first draft of Senator George Mitchell's document. Trimble had studied it overnight and the negotiations had reached a nadir with his colleagues rejecting it out of hand. His deputy John Taylor colourfully declared that he would not touch the document 'with a 40-foot bargepole'. Trimble himself described it as a 'Sinn Fein wish list'. They even claimed large parts of the document had been kept from them by the Irish government, operating a pan-nationalist front with Sinn Fein.

On Tuesday morning, Trimble had rung Blair three times at Downing Street before faxing him a letter rejecting the deal. He had a host of complaints: the issue of consent had not been adequately conveyed; he was alarmed by its language regarding cross-border bodies, the kernel of the dispute between nationalists and unionists for 25 years.

The Unionists claimed the fine print showed the bodies would be free-standing with no accountability to any future Northern Ireland assembly - a key Sinn Fein demand.

Billy Hutchinson, the spokesman for the UVF-aligned Progressive Unionist Party, warned: 'We are talking about people going back to war.' Even the moderate Alliance Party was unhappy. Blair decided to leave Downing Street and head for Belfast to take charge. On arrival he spent two hours with Trimble before being given his history lesson by Napier.

In truth he probably did not need it. He had been preparing privately for weeks for the prospect of flying to rescue the talks along with Bertie Ahern, the Irish Prime Minister. As a result, he had not just immersed himself in the finer details of the possible agreement, he had also read widely on the recent Irish conflict. He also had by his side John Holmes, his youthful-looking private secretary, who had run all of John Major's Ireland policy from Downing Street and possessed an encylopedic knowledge of the drafts and redrafts of the proposals. On that first evening, Blair tried to reassure Alderdice and Trimble in turn about the Mitchell document. It contained only provisional proposals, much had been left for the parties to negotiate in the run-up to the midnight deadline on Thursday. After the meeting, Blair sat back with his colleagues, including Mitchell, and contemplated the marathon ahead.

Mitchell and Mo Mowlam, the Northern Ireland Secretary, told him to expect grandstanding from all the parties. 'If the media mini-Olympic village start reporting one side is winning, expect the other to start demanding meetings with you. None of it will bear much relation to the true state of the negotiations,' was the gist of their message.

Blair, who had already learnt to treasure the infinite patience and calm of Mitchell, said he was prepared for a bumpy ride.

It was agreed that Blair would operate from his room via the phone and in face-to-face meetings. He went outside only once in the three days, living on sandwiches and Mars Bars.

Mowlam, an irrepressible optimist, would wander the corridors, pop into the parties in other rooms, pick up intelligence and exude the necessary sense of momentum. Sometimes she threw her 'bloody wig' around, sometimes she banged the table.

Outside, the unseasonal icy winds and flurries of sleet and snow gave a sense of unreality. Strange episodes eased the tension, such as when groups of schoolchildren and musicians arrived at the gates with pleas for peace. One child pinned several yellow and green ballons on the gates through which the participants have passed for the last 22 months. It simply read: 'A peace plea from Patrick.'

It put some small moral pressure on the politicians. Every single political figure who emerged for a respite from the talks attempted to get their picture taken with children from a Protestant and Catholic school from Dundrum, Co Down, who were singing for peace outside the discussions. Gerry Adams even brought along a tray of drinks for the thirsty kiddies who happened to be positioned in front of the cameras.

As one acerbic American scribe noted: 'In Dayton, the Serbs, Croats and Muslims made peace in Bosnia because the threat of American B52 bombers loomed over their heads. In Belfast they've got to get agreement because they don't want to look like they've let these little kiddies down.'

By Wedneday morning the atmosphere had started to improve. Much of the day was spent discussing Strand Two - the shape of the North-South bodies, their powers and relationship to the Northern Ireland assembly.

Trimble had conceded they would be enshrined in law, but he wanted the assembly to be established first. The Irish were arguing for the opposite. There was also fundamental disagreement over Strand One - the shape, powers and structure of the Northern Ireland assembly.

The SDLP led by John Hume and Seamus Mallon were insisting on parallel consent - both nationalist and unionist - before any important decisions could be agreed. Late on Wednesday evening there was, according to Blair's team a crucial three-way meeting between Trimble, Blair and Ahern. The Irish Prime Minister had just returned to Stormont by helicopter from the funeral of his mother.

The meeting lasted less than 30 minutes. But two things happened: Ahern spoke directly to Trimble, looking him in the eye and assuring him that he wanted the best for Northern Ireland and Trimble agreed to split his delegation so half of them negotiated over Strand One and the other over Strand Two, speeding up the process for the final push.

As the parties arrived on Thursday morning, they knew the deadline was looming. The North-South bodies and the structure of the assembly remained to be settled. The UUP were chasing Irish officials around Stormont urgently seeking a meeting with Ahern and his ministers to discuss Articles Two and Three of the Republic's constitution, the constitutional claim to Northern Ireland.

Throughout the day, UUP delegates remained frustrated at Dublin's inability to meet them. Several, including David Brewster, expressed concern that the Irish were running away from discussions on the territorial claim.

Trimble, meanwhile, had gone to UUP headquarters in Glengall Street, Belfast, to consult his executive on progress. As he arrived he heard wild cheering and turned to wave to a crowd outside the Europa Hotel across the street. He need not have bothered - the screams were for teenage heart-throb Ronan Keating of Boyzone, who had just arrived for the Irish Rock and Pop awards.

Trimble told the 110-strong executive that Ahern had told him the IRA would allow Sinn Fein to attend the assembly. He also said he was accepting a Cabinet-based system for the assembly, as sought by the SDLP, instead of the committee-based system that the UUP had long favoured.

Meanwhile, those opposed to the entire process were organising a protest outside Stormont's gates. Several hundred loyalists led by Ian Paisley's Democratic Unionist Party attempted to march up to Castle Buildings. They were halted by RUC officers at Carson's statue, erected in memory of Ulster unionism's founding father.

Paisley insisted that, as a delegate to the talks, he was entitled to pass through the cordon. His journey to the press conference Portakabin was an uncomfortable one, however. He had to pass through a gauntlet of screaming, hostile supporters of the loyalist ceasefires. 'You didn't have to fight the war, Paisley,' they shouted. 'We should never have listened to you.'

Paisley, who was 72 on Monday, was pushed on to the defensive at this extraordinary press conference. As he ranted, on the stroke of midnight, the deadline, the press started to drift away. He seemed, for the moment at least, an anachronism, irrelevant to history in the making.

Then it was the turn of Martin McGuinness, Sinn Fein's chief negotiator, to sound apocalyptic. He counselled Blair to 'avoid going with the unionist agenda', his words illuminating the problems republicans inside Stormont foresee if they sign up to something less than a transitional agreement to a united Ireland.

McGuinness mentioned Blair four times in the course of his briefing, emphasising again and again that the Prime Minister should not buckle under unionist pressure. Blair had by now become convinced that Adams wanted a deal. Hume - who over the three days saw Blair frequently for brief five-minute updates - repeatedly stressed Sinn Fein's sincerity.

Early on Friday morning, the SDLP and the Ulster Unionists went into a long session to try to resolve their dispute over the nature of the assembly. They ended with a deal: the North-South body would be enacted by legislation in the Dail and Westminster. Between the time it was elected in June and started to sit, a shadow assembly in conjunction with the Irish government would agree six areas where powers could be devolved to the new North-South bodies.

The Irish believe they neutralised a potential unionist veto by the proviso that, if six cross-border bodies were not established, the assembly would not be allowed to function. It seemed like the last stumbling block. Hume returned to the SDLP to be hugged by his comrades, and fell asleep.

Mark Durkan, one of his negotiators, confessed that a number of devout Catholics in his delegation almost unwittingly broke the Good Friday ban on eating meat, when some sausage rolls were brought in after midnight.

There was a mood of celebration. Blair was informed at 5am that the deal was coming together. President Clinton was kept in touch by Mitchell.

Yet by lunchtime on Friday, with the broadcasters predicting a signing ceremony by 7am, the euphoria slid away. The word 'hitch' was heard.

John Hunter, a Trimble aide, emerged from Castle Buildings looking gloomy. 'The party is mixed about this document,' he said.

The 30-strong UUP delegation met to look at the final text. They faced the trauma of taking the plunge to end 30 years of conflict. John Taylor, who had his jaw ripped apart by IRA bullets, opened the two-hour meeting by saying he had 16 points of disagreement. Then the Lagan Valley MP Jeffrey Donaldson weighed in. He did not like the deal on decommissioning of terrorist weapons, or the promise to release IRA prisoners within two years.

Trimble spoke to Blair twice on the phone and took some of his most senior negotiators at 3.20pm to see Blair again. He asked what would happen if any office holder in the assembly had links with a group still indulging in violence. The Prime Minister refused to offer any more amendments. 'This is what is going into the plenary and this is it,' he said. 'If we renegotiate on one front, the nationalists will renegotiate on another.'

Even Alastair Campbell, Blair's press secretarty, pleaded with Trimble: 'If you don't accept this document, we will all be crucified. People will not understand.' It was close to a bust-up.

According Reg Empey, one of Trimble's closest confidants, the UUP were five minutes from walking out when Northern Ireland Office officials shoved a copy of a letter from Blair into his hands.

The letter reassured Trimble on two critical points: that politicians connected with paramilitary organisations which refused to hand over weapons would not hold office in any Northern Ireland government; and that, in the British Government's view, the process of decommissioning would have to begin immediately after the assembly came into being in June.

The letter was a tactical triumph for Blair. It enabled Trimble to outflank his opponents. Armed with the letter, he acted decisively and urged his party to accept the deal.

Contrary to media reports, this intervention by Blair saved the day, not the subsequent telephone call by Clinton at about 4.15pm. Blair asked Clinton to make the calls to the key leaders, including Trimble. As Mitchell explained, Clinton is a persuasive guy. He told Trimble: 'From where I am sitting people simply will not understand if this deal does not go through now.' If the unionist leader's backbone needed stiffening, Clinton helped.

Inside the plenary session Mitchell asked each of the parties in turn if they agreed with the terms in the document. All but two gave it their full endorsement.

Trimble said the UUP accepted it but he would have to report to his party's executive. Sinn Fein did not sign up or put their hands up in favour of the document. Adams said his party's ruling body the Ard Comhairle would have to discuss it first. At 5.26pm, the talks were adjourned sine die. The deal was done.

Then the propaganda battle between the parties began in earnest. Trimble, who was flanked by only one MP, Cecil Walker, insisted it had been a good day for the Union, before attacking 'the squalid dirty war of Sinn Fein'. Adams must assure supporters this is the staging post to a united Ireland. 'This is a phase in our struggle. That struggle must continue until it reaches a final goal,' he said.

He knows many inside and out of the Provisional IRA will accuse the Sinn Fein leadership of selling out basic republican goals. Sinn Fein will have to hold an extraordinary conference to overturn its own constitutional ban on entering 'partitionist assemblies'.

Discontent is growing within the party about how far Sinn Fein can go without recognising the existence of Northern Ireland, a state republicans have been trying to destroy since partition.

Yet Trimble's supporters fear an outbreak of 'stupid unionism' will save Sinn Fein from biting the bullet of consent. One figure close to Trimble said: 'If Willie Ross and Willie Thompson (the UUP MPs for East Londonderry and West Tyrone) force a split in the party then Trimble will lose and the referendum could be defeated. That will let Gerry Adams off the hook in facing up to the reality that Northern Ireland will still exist. It would be a tragedy if unionists failed to see the wood for the trees and rejected this out of hand.' Son of Sunningdale was born on Good Friday 1998 but an internal unionist coup against Trimble could make it as shortlived as its predecessor 24 years ago. Napier's grim warning could still have its relevance.