On the first day of February 1979, an Air France plane landed at Tehran Airport. It was carrying an elderly Islamic cleric from Iran’s rural hinterland who had not been in his native land for 15 years. As he stepped down from the plane, dressed entirely in black, supported by a French flight officer, a thousand waiting admirers began to chant his name: Ruhollah Musavi Khomeini.
As a Mercedes van carried him towards the city centre, the streets were lined with people peering from windows and from rooftops, people packed on to building sites and into flats, people who had been up since dawn to claim a space by the roadside, people hanging off cranes and on to ledges, people screaming and shouting with ecstasy. Journalists estimated that there were perhaps five million people on the streets, the biggest crowd in human history.
Thirty years on, the return of the Ayatollah Khomeini and the ensuing Iranian Revolution looms as perhaps the central event of the late-twentieth-century world. The 76-year-old preacher was not an obvious candidate to become a historical icon: born to a family of clerics in the obscure, dusty town of Khomein, he had spent much of his life as a teacher and scholar, before being sent into exile in 1964 after denouncing the Shah's regime and his fealty to foreign interests. Yet he became the face of a revolution that toppled a corrupt, repressive monarchy, unleashed a devastating oil shock and global economic crisis, inspired a new brand of religious fundamentalism, and bequeathed an autocratic regime that, for all its manifest corruption, stagnation and brutality, still endures today. It was a turning point in the history of relations between the west and the Middle East, and between the United States and the Islamic world.
Yet there was nothing preordained about the way things worked out; indeed, the largely untold story of the revolution is that if a handful of people had made different choices, then the history of American-Iranian relations might have been much less tortured. And while nobody can expunge the record of three decades of hostility, the advent of a new administration in Washington does offer grounds for hope. Like every other American politician of his generation, Barack Obama has rattled his sabre in the direction of Tehran, but he has also talked of meeting Iranian leaders and even holding direct talks with President Ahmadinejad. Three decades on, it is time to bury the bitter legacy of the revolution and the hostage crisis. Nixon went to Beijing, Reagan to Moscow; is it too fanciful to picture Obama in Tehran?
The last American president to visit the Iranian capital was the ill-fated Jimmy Carter, who toasted the Shah on New Year's Eve 1977 as the world leader with whom he felt most "personal friendship". Iran, Carter said, was "an island of stability in one of the more troubled areas of the world". Even then the sentiment seemed dubious; now, it is quoted as a classic example of an American looking at the Middle East and seeing only what he wanted to see, not what was really happening. For it was only ten days after Carter's departure that a state newspaper published an inflammatory attack on the exiled Ayatollah Khomeini, provoking the first in a series of demonstrations and clashes that drove the Shah from his country and made Khomeini one of the most familiar and controversial figures on the planet.
Nothing in history is inevitable, but Iran was heading for crisis at the end of the 1970s. The Shah, Mohammad Reza Pahlavi, was a corrupt, indecisive man, more weak than wicked, a lover of fine wines and foreign women who dreamed of using his gigantic oil revenues to rebuild the Persian Empire. Elevated to the throne at the age of just 21 after the British ousted his father, he had become increasingly dependent on American aid, especially after he acquiesced, in a CIA-backed coup in 1953, to topple the nationalist prime minister Mohammad Mossadegh. In the aftermath of the 1973 oil shock, he spent more than $12bn on American arms and equipment. He wanted new factories and universities, grand boulevards and gleaming power plants, but the more money he spent, the more prices in the shops of Tehran soared beyond imagining. By the late Seventies, cities were buckling under the weight of thousands of rural peasants in search of his economic miracle. In Tehran's concrete nightmare, the streets were permanently blocked with traffic, overstuffed tower blocks groaned beneath the weight of hundreds of families and the electricity grid regularly broke down for four hours at a time. Amid the squalid shanty towns and the stinking sewers, frustration was inexorably turning to fury.
Looking back, the extraordinary thing is not that Iran slipped towards the last great ideological revolution of modern history, but that the Shah's American sponsors - who had installed one of the biggest CIA projects anywhere in the world, largely to monitor movements across the Soviet border - failed to realise what was happening. The intelligence failure in Iran was no less staggering than those in Vietnam and Iraq; indeed, given Iran's enormous strategic importance, it was perhaps even more unfathomable. At the American embassy - later the centre of the extraordinary hostage drama - only a handful of officials spoke Farsi, and most of their Iranian employees were not Shia Muslims but Armenian Christians. When a new ambassador, William Sullivan, arrived in the summer of 1977, he was struck by their total introversion. Sullivan had served in Laos and the Philippines; but in Iran, he said, "more than in any other country where I had lived and served, I felt myself insulated from and alien to my environment".
To anyone familiar with the histories of Vietnam and Iraq, the parallels are uncanny. And while a French diplomat predicted the Shah's downfall as early as 1976, and the Israelis began advising Jewish citizens to leave Iran in April 1978, the American embassy doggedly insisted that there was plenty of life left in the regime. In August, with Tehran's streets gridlocked with protesters, the CIA reported that Iran was "not in a revolutionary or even pre-revolutionary situation", while the Agency's ineffectual director, Stansfield Turner, personally assured Jimmy Carter that the Shah was more than capable of suppressing dissent. As late as 28 September, with the regime having passed the point of no return, the Defence InIntelligence Agency reported that "the Shah is expected to remain actively in power over the next ten years".
One man who did not agree, however, was the American ambassador, William Sullivan. In retrospect, Sullivan is one of the few characters to emerge from the whole sorry story with any credit. He could be wilful and arrogant, but, in stark contrast to the American officials who have been through Baghdad in recent years, he was no administration yes-man. The little-known story of Sullivan's efforts to change American policy in the crucial first days of the Iranian revolution - the point when things might have turned out differently - should be remembered as one of the great missed opportunities in modern American history.
At the beginning of November 1978, Sullivan sent a long cable to Washington under the ominous title "Thinking the Unthinkable". Jimmy Carter's friend, the Shah, was effectively finished, he said, and it was time for the administration to move on. Sullivan did not question the premise that the Americans should play a key role in the new Iran; its strategic location, vast oil reserves and long history of co-operation with the west made that inevitable. But he urged Carter to reach out to dissident elements in the military and moderate Islamic clerics, including, if need be, the mysterious Imam Khomeini, the most celebrated of the Shah's exiled opponents, then based in Paris. None of Carter's advisers knew anything about Khomeini, but there seemed no reason why the Americans should not befriend him. He might even, Sullivan thought, play the role of a Gandhi, a spiritual leader and voice for unity, in a new Iranian regime.
Whether Sullivan’s idea could have worked is one of the most compelling what-ifs of modern history. Hardened opponents of the revolution would no doubt argue that Khomeini not only had a long record of criticising the United States but was also determined, by whichever means possible, to install an Islamic fundamentalist regime. But whether this was always his intention, or was rather the product of the pressure of events, remains uncertain. For in Paris, where Khomeini gave 132 interviews to the world’s press in just a few months, he presented a much more moderate, even democratic image, and surrounded himself with secular, liberal advisers. Like his future adversary Ronald Reagan, he was always more pragmatic, more flexible, than his opponents realised. His goals, he told reporters, were “independence, democracy, tolerance, and progress”.
Sullivan was not the only American official calling for a closer relationship with the Ayatollah. At the end of December 1978, the state department's Iran specialist urged the administration to "enlarge our contacts" with the exiles in Paris. Astonishingly, his advice never reached the president. Determined to support the Shah until the end, the hawkish national security adviser Zbigniew Brzezinski made sure that his paper was never discussed and even froze the state expert out of policy meetings.
But the idea did not go away. In the first days of 1979, with the Shah preparing to flee Iran for a life of exile in California, Sullivan and his state department allies came up with a plan for the former US ambassador to Afghanistan, Theodore Eliot, to fly to Paris and open direct talks with Khomeini. Looking back, it seems an extraordinary idea, and one that could have changed the history of the Middle East. On 10 January, Carter's senior aides met in the Oval Office to approve or reject the idea. The meeting, one said later, was "rancorous" - and the winner was Brzezinski, who still hoped for a pro-American military coup to restore order, and persuaded Carter to veto the plan. Later that day, Carter read an interview Khomeini had given to Le Monde, translated by the National Security Council. He sent it back with one word at the top: "Nutty".
The immediate result of that crucial meeting was the overt rebellion of William Sullivan, the text of whose angry telegram deserves to be etched on Jimmy Carter's gravestone: "President has made gross and perhaps irretrievable mistake by failing to send emissary to Paris to see Khomeini . . . I can not rpt not understand the rationale . . . Failure to act immediately could permanently frustrate US national interests in Iran." In the days that followed, as Khomeini flew home and began to lay the foundations of his Islamic Republic, the decision looked increasingly foolish. In a final sign of Washington's estrangement from reality, Brzezinski was still trying to arrange a military coup weeks after Khomeini's return. On 11 February, with the Iranian general staff trapped in their bunker by revolutionary forces, an NSC aide called Sullivan and suggested that the time might be ripe to strike. Sullivan merely hung up on him. A few minutes later, Washington had a message from the embassy: "Army surrenders; Khomeini wins. Destroying all classified."
Given that the Iranian army was already falling apart, that the Tehran crowds had already taken Khomeini to their hearts, and that the ayatollahs were by far the outstanding focus of moral authority and opposition to the Shah in the late Seventies, the foundation of an Islamic republic was probably inevitable. But if Jimmy Carter had followed the state department's advice and sent an emissary to Khomeini, it is perfectly plausible that American-Iranian relations would have been different. At the very least, it would have strengthened the hand of the secular moderates surrounding the Ayatollah, and it would also have sent a powerful signal to Khomeini - a much more cautious and practical man than his reputation suggests - that Washington was not his implacable enemy. Above all, though, the world might well have been spared the stunning drama of the embassy hostage crisis, probably the decisive moment in defining ordinary American attitudes to Iran.
The roots of the hostage crisis lay in Carter’s belated decision to admit the Shah to the United States for medical treatment. The original plan had always been for the exiled monarch to fly to California, as was probably the only honourable option. Certainly his regime (like almost every other in the region) had been guilty of numerous human rights abuses, but he had long been a valued American ally, and Jimmy Carter had, after all, publicly hailed him as a personal friend. For months, though, Carter put him off, worried that his admission would infuriate Iranian opinion and jeopardise the safety of American diplomats in Tehran. Only when it emerged that the Shah was suffering from terminal cancer (and after a protracted lobbying campaign from the monarch’s old friend Henry Kissinger), did Carter change his mind, and allow the Shah to fly to New York for treatment.
When enraged student militants - acting without Khomeini's consent or, possibly, even knowledge - invaded the American embassy and took its staff hostage in November 1979, it was a pivotal moment in the history of the relationship between the United States and the Islamic world. Like the attacks of 11 September 2001, the hostage crisis was seen as a violation of American territory, a moment of innocence betrayed, of sacred territory invaded and despoiled. Like the 11 September attacks, it was a crisis made for television, with a story rich in suspense, sympathetic American heroes, fanatical foreign villains, and political conspiracy. Every night, the ABC special America Held Hostage counted the days of the hostages' captivity. Every night, the networks showed Iranian mobs shaking their fists, denouncing the Great Satan and setting light to the American flag. The hostages were heroes, the students were extremists, and that, as far as the networks were concerned, was all there was to it. It was a worldwide clash of good and evil, with an American cast of plucky underdogs and a super-villain who resembled an aged Emperor Ming of Mongo.
In retrospect, too, the hostage crisis looks like a key moment in the development of a new kind of American nationalism: injured, resentful, eager to lash out, eager to banish the humiliation of Vietnam and Tehran. In Beverly Hills, a worldwide symbol of leisure and luxury, crowds attacked Iranian students with baseball bats, putting some of them in hospital. In Riverside, California, an Iranian student was found dead after what the police called an "execution". "No more Iranian students will be permitted on these premises until the hostages are released," read a sign at the Mustang Ranch, a brothel near Reno, which suggests that not all Iranians shared their new leader's asceticism.
When Jimmy Carter ordered a botched helicopter mission to rescue the hostages in the summer of 1980 – the infamous debacle in the desert, from which his reputation never recovered – the course of American-Iranian relations was set. Outside the United Nations, Americans chanted “Bomb Iran”; in the streets of Tehran, Iranians chanted “Death to America”. In New York, stores sold Ayatollah dolls, marketed with special torture equipment; in Tehran, clerics gleefully exhibited the charred remains of American servicemen killed in the helicopter disaster. None of this was inevitable; but once it had happened, there was no turning back.
Even then, however, few people could have guessed that the bitterness would linger for another 30 years. Yet the truth is that while the Iranian regime remains corrupt, reactionary and repressive, the chance for a rapprochement is greater than ever. Many ordinary Iranians, while perfectly happy to chant patriotic anti-American slogans, admire what they see as the openness and enterprise of American society. In his new book, A World of Trouble: America in the Middle East, the journalist Patrick Tyler recalls being stopped at a roadblock on the night Khomeini died, 20 years ago. Iran was in a frenzy of mourning, and when Tyler saw a bearded soldier's AK47 tapping on his window he expected the worst. He wound down the window. "Excuse me, sir," the soldier said, "but if you were going to select the best American university to study electrical engineering, which one would you choose?"
Behind the inflammatory rhetoric of its increasingly unpopular president, Iran has a strikingly young, ambitious, well-educated population, eager for contacts with the west. Perhaps even more tellingly, it is in deep economic trouble, with runaway inflation, rising unemployment and endemic problems of corruption. It presents both a threat and an opportunity - and it is the latter that should compel President Obama's attention. Like every senior American politician, he has mouthed the ritual clichés about military action, if necessary, to halt Iran's nuclear programme. But he has also talked of "big carrots" as well as "big sticks", and of "improved relations" should the Iranians end their pursuit of nuclear weapons.
This would not, as some of the regime's critics claim, be a policy of appeasement. Yes, Iran has been a force for discord in the Middle East for far too long. Its intemperate threats against Israel deserve nothing but contempt, while its financial and moral support for Hezbollah and Hamas has undoubtedly played a part in the region's miserable cycle of provocation and retaliation. But the comparisons with Nazi Germany that one often hears from American critics are poorly made. Iran has no record of territorial expansionism, no long-stated ambition to swallow its neighbours. Its enmity with Israel is, in part at least, the natural rivalry of two middle-ranking regional powers, dressed up with the extravagantly sinister rhetoric that Iranian audiences have come to expect of their leaders. After all, leaving Iran out in the cold for 30 years has manifestly failed to do any good. After so many years of fruitless hostility, changing the record would not be appeasement, but sensible, sober diplomacy.
Obama’s direction should be clear. Unlike Jimmy Carter 30 years ago, he should be prepared to talk to everybody, both inside and outside the regime. And since no incoming president in living memory has taken office with more international goodwill, he should put it to profitable use. It is now more than three decades since an American president was in Tehran. And while the image of the American head of state shaking hands with the ayatollahs may seem unlikely, few people would have imagined that they would see Richard Nixon on the Great Wall of China and shaking hands with Chairman Mao, or Ronald Reagan in Red Square, exchanging jokes with Mikhail Gorbachev. Nothing would do more to coax the Iranian regime towards liberalisation, and nothing would do more to change America’s image in the Middle East, than for Barack Obama to follow their example, and to bury the bitter legacy of three decades ago, once and for all.
Dominic Sandbrook is the author, most recently, of "White Heat: a History of Britain in the Swinging Sixties". For more of his New Statesman essays visit www.newstatesman.com 
AFTER THE REVOLUTION: A TIMELINE OF THE ISLAMIC REPUBLIC
1980 22 September Saddam Hussein invades Iran commencing Iran-Iraq War.
1986 November So-called Iran-Contra scandal breaks. Almost brings down Reagan government.
1988 August Iran accepts ceasefire, ending Iran-Iraq War.
1989 Khomeini announces fatwa condemning Salman Rushdie after publication of the novel "Satanic Verses"
3 June Death of Ayatollah Khomeini. Ali Khamanei becomes Supreme Leader.
3 August Ali Akbar Rafsanjani elected president.
1995 US places sanctions on Iran; claims it sponsors terrorism.
1997 2 August Mohammad Khatami elected president.
2002 Opposition group exposes existence of secret nuclear facilities at Natanz and Arak.
In his State of the Union speech, George W Bush refers to Iran as part of an "axis of evil".
2005 24 June Mahmoud Ahmadinejad, Tehran's conservative mayor, elected president.
2006 UN imposes sanctions on Iran for failing to suspend uranium enrichment.