Iran's President Mahmoud Ahmadinejad visits the Imam Ali shrine in Najaf, Iraq, last month. Credit: Reuters
Vilified abroad for his blistering attacks against the West, blamed at home for Iran's economic woes, and isolated from the supreme leader who groomed him for power, Mahmoud Ahmadinejad leaves the presidency with few friends and an uncertain future.
Iranians elected his opposite -- a mild-mannered, moderate member of the clerical establishment -- to replace him, doubtless hoping for better times than they endured for eight years under the caustic hardline outsider.
Ahmadinejad's abrasive rhetoric made him an easy target for Iran's opponents abroad, and the collapse of the economy under the weight of international sanctions and domestic mismanagement made him a magnet for blame at home.
But those hoping for a rapid improvement in the quality of life, swift rapprochement with the West or more transparency in the way Iran is ruled may soon find that its problems go deeper than the small man with the scruffy beard and ill-fitting suits.
Since his shock election victory in 2005, Ahmadinejad rose from near total obscurity to become the most visible actor on the Iranian stage, on the way pulling through a disputed re-election victory that rocked the nation to its core.
His final speech as president on Friday was vintage Ahmadinejad: "I swear to God that a ferocious storm is coming and it will uproot the Zionist entity," he declared on Quds Day, an annual event devoted to opposing Israeli rule over Jerusalem.
Mocked by progressive Iranians, he created a cult following among traditionalists and the working classes through his charisma, simple lifestyle and populist beliefs.
His name gives three times as many results in a Google search as that of his former sponsor, Supreme Leader Ayatollah Ali Khamenei, Iran's most powerful man.
But history, whether written at home or abroad, is unlikely to be kind. Within hours of the election victory of moderate cleric Hassan Rouhani, thousands of people gathered outside Rouhani's headquarters and across the city to celebrate, shouting "Ahmadi bye-bye."
"He is unlikely to exit the political scene gracefully, for grace has hardly been a hallmark of his eight years in office and is unlikely to be an adjective applied to the good doctor in the future," said New York-based Iranian-American author Hooman Majd who has met Ahmadinejad on several occasions.
On the international stage, he has shocked the Western world with his rhetoric, often during his annual appearances at the United Nations General Assembly, which have caused mass walkouts and public demonstrations.
Relishing the opportunity to discomfit Iran's detractors, he has alleged the U.S. government was behind the 9/11 attacks, denied homosexuality exists in Iran and lambasted Western leaders for being played by "deceitful Zionists."
"The president's irresponsible rhetoric on Israel, the Holocaust and other issues has deepened Iran's international isolation," said Shaul Bakhash, professor of history at George Mason University in Virginia.
"His embrace of the language of Holocaust denial, his prediction that Israel will be erased from map of history ... made it far easier for many to depict Iran as a radical state."
Ahmadinejad was groomed by Khamenei to take on the reformist movement - those advocating more social and political freedoms. His devout religious views, his common touch, his accessibility to young Iranians and connections to the military were assets.
His fans glorified him as a humble servant who shunned the trappings of power. Ahmadinejad, so the story goes, refused the presidential salary and went to work with a packed lunch.
With a poor background and a doctorate in engineering from a technology university rather than a background studying theology in Iran's ancient schools of Shi'ite Islam, his down-to-earth image contrasted with that of the elite members of the clergy.
He believed his popular mandate made him a counterweight to the unelected clerics and members of powerful old families.
"He wants to leave a legacy where he was the guy breaking the stranglehold of the mullahs," said Majd. "He believes an elected president should be allowed to govern. That's quite a popular sentiment among Iranians."
He relied on sharp wits, political courage and self-confidence: "He has a huge ego. He believes he's right and he is unafraid," added Majd.
But ultimately he overplayed the hand his mandate gave him, leading to a direct confrontation with Khamenei. The feud erupted in 2011 when Ahmadinejad sacked the intelligence minister but the supreme leader reinstated him.
Khamenei loyalists accused Ahmadinejad and his advisers of seeking to erode clerical authority -- activity denounced as a "deviant current". He was frozen out of decision-making and threatened with impeachment. In March last year he became the first president in the history of the Islamic Republic to be summoned by parliament for a grilling on his policies.
To the benefit of the clerics, the ruling system he leaves behind has fewer checks and balances than when he found it.
To give himself more room to push through his policies, Ahmadinejad dissolved the Plan and Budget Organization, a government body tasked with drawing up spending plans.
The electoral process was left bent and broken following the 2009 election. Reformists were sidelined, opposition leaders Mirhossein Mousavi and Mehdi Karoubi put under house arrest and parliament made compliant.
Those moves leave Khamenei controlling all levers of power.
"There was a group who participated in this ruination of the state and of course the chief beneficiary of the removal of accountability was Khamenei," said Ali Ansari, professor of history at St. Andrew's University in Scotland.
High oil prices meant that Iran enjoyed record revenues during Ahmadinejad's two terms. But the economy nevertheless faltered because of mismanagement, and ultimately crumbled under embargoes imposed in 2012 by the United States and European Union, which cut oil exports in half.
Dependent on oil to earn hard currency, Iran saw the rial fall and inflation soar, to 35 percent according to official figures, by some estimates double that.
In late 2010 he launched a program to withdraw generous subsidies in favor of cash handouts. A bold move to wean Iran off costly benefits, it led to soaring prices for food and fuel, bringing hardship for many and deep criticism from rivals.
"Ahmadinejad's erratic stewardship has left the Iranian economy in a shambles. His courage in taking the bull of subsidies by the horns will be lauded, while its poor implementation will be deplored," said Yasmin Alem, of the Atlantic Council's South Asia Center.
Arguably, in economic policy, he served as a scapegoat for a system that has deeper problems. The subsidies he cut would have been even more expensive to maintain under sanctions.
The sanctions themselves were a result of a nuclear standoff with the West that remains a fundamental state policy of Khamenei, although Ahmadinejad's deeply divisive hardline stance made negotiations tougher.
Ahmadinejad's reformist predecessor Mohamed Khatami had suspended uranium enrichment, a chemical process that can be used to make material for an atomic bomb.
Iran restarted enrichment within weeks of Ahmadinejad taking office in 2005, and has since maintained a "no compromise" stance. Tehran says it wants the uranium solely for peaceful purposes; U.N. Security Council members doubt it.
Washington has not ruled out military action over what it believes are attempts to develop atomic weapons capability, although it continues to pursue a diplomatic resolution.
Yet despite his confrontational rhetoric, Ahmadinejad also was accessible to the West. He made unprecedented and ultimately unsuccessful attempts to establish direct contact with two U.S. presidents, a move that was previously regarded as a taboo.
Approaches included meetings between an Ahmadinejad advisor and U.S. officials during his first term and a high-level meeting between deputy U.S. Secretary of State William Burns and Iran's top nuclear negotiator Saeed Jalili in 2009.
He has happily engaged with U.S. media, becoming a repeat guest of talk show host Larry King, with whom he would banter combatively in the studio. He seemed to relish the stir he would cause visiting the "Great Satan" for his annual appearances at U.N. headquarters in New York.
Ahmadinejad advocated a 2009 nuclear deal that came close to resolving the deadlock with the West through an agreement to swap fuel kept abroad. Ultimately it was shelved after criticism from both Iranian conservatives and reformists.
Some wonder what comes next for the man who defied Iran's enemies but also its leader. There is talk of him setting up a university but he may have to face the music first.
"There is some chatter his opponents will move against him once he formally relinquishes the presidency," said Ali Ansari. "But it would seem he is being protected by the supreme leader. I find it difficult to believe that he will fade away."