Turkish authorities rounded up nearly 3,000 suspected military plotters on Saturday and ordered thousands of judges detained after thwarting a coup by rebels using tanks and attack helicopters to try to topple President Tayyip Erdogan.
For several hours overnight on Friday violence shook Turkey's two main cities, as the armed faction which tried to seize power blocked a bridge in Istanbul and strafed the headquarters of Turkish intelligence and parliament in Ankara.
At least 265 people were killed. An official said 161 of them were mostly civilians and police officers, while the remaining 104 were coup supporters.
But the coup attempt crumbled as Erdogan rushed back to Istanbul from a Mediterranean holiday and urged people to take to the streets to support his government against plotters he accused of trying to kill him.
"They will pay a heavy price for this," said Erdogan, launching a purge of the armed forces, which last used force to stage a successful coup more than 30 years ago. "This uprising is a gift from God to us because this will be a reason to cleanse our army."
Among those detained were top military commanders, including the head of the Second Army which protects the country's borders with Syria, Iraq and Iran, state-run Anadolu news agency said.
Hundreds of soldiers were held in Ankara for alleged involvement in the coup, leaving police stations overflowing.
Some had to be taken under armed police escort in buses to a sports stadium. Reuters footage showed some of the detainees, handcuffed and stripped from the waist up, sitting on the floor of one of the buses.
The government declared the situation under control, saying 2,839 people had been rounded up, from foot soldiers to senior officers, including those who formed "the backbone" of the rebellion.
Authorities also began a major crackdown in the judiciary over suspected links to US-based cleric Fethullah Gulen, removing from their posts and ordering the detention of nearly 3,000 prosecutors and judges, including from top courts.
Erdogan has blamed the coup on supporters of Gulen, who he has frequently accused of trying to foment uprising in the military, media and judiciary.
Ten members of the High Council of Judges and Prosecutors and two members of the Constitutional Court have already been detained, officials said.
A successful overthrow of Erdogan, who has ruled the country of about 80 million people since 2003, would have marked another seismic shift in the Middle East, five years after the Arab uprisings erupted and plunged Turkey's southern neighbor Syria into civil war.
However, a failed coup attempt could still destabilize the NATO member and major US ally that lies between the European Union and the chaos of Syria, with Islamic State bombers targeting Turkish cities and the government also at war with Kurdish separatists.
US President Barack Obama expressed support for Turkey's government and urged parties on all sides of the crisis to avoid destabilizing the country and follow the rule of law. But his secretary of state, John Kerry, warned Turkish Foreign Minister Mevlut Cavusoglu that public suggestions of a US role in the plot were "utterly false" and harmful to relations.
Erdogan, who had been holidaying on the southwest coast when the coup was launched, flew into Istanbul before dawn on Saturday and told thousands of flag-waving supporters at the airport that the government remained at the helm.
A polarizing figure whose Islamist-rooted ideology lies at odds with supporters of modern Turkey's secular principles, Erdogan said the plotters had tried to attack him in the resort town of Marmaris.
"They bombed places I had departed from right after I was gone," he said. "They probably thought we were still there."
Erdogan's AK Party has long had strained relations with the military, which has a history of mounting coups to defend secularism although it has not seized power directly since 1980.
His conservative religious vision for Turkey's future has also alienated many ordinary citizens who accuse him of authoritarianism. Police used heavy force in 2013 to suppress mass protests demanding more freedom.
He commands the admiration and loyalty of millions of Turks, however, particularly for raising living standards and restoring order to an economy once beset by regular crises, which grew 4.8 percent year-on-year in the first quarter.
The violence is likely to hit a tourism industry already suffering from the bombings, and business confidence is also vulnerable.
In a night that sometimes verged on the bizarre, Erdogan frequently took to social media, even though he is an avowed enemy of the technology when his opponents use it and frequently targets Twitter and Facebook.
He addressed the nation via a video calling service, appearing on the smartphone of a CNN Turk reporter who held it up to a studio camera.
He also urged Washington to deport Gulen, who lives in self-imposed exile in the United States. The cleric, who once supported Erdogan but became a leading adversary, condemned the attempted coup and said he played no role in it.
"As someone who suffered under multiple military coups during the past five decades, it is especially insulting to be accused of having any link to such an attempt. I categorically deny such accusations," Gulen said in a statement.
Kerry said the United States was willing to help Turkey as it tries to identify those involved in the coup attempt, but made clear it would only act if there was evidence against Gulen.
Gunfire and explosions had rocked both Istanbul and Ankara through the night after soldiers took up positions in both cities and ordered state television to read out a statement declaring they had taken power. However, by dawn the noise of fighting had died down considerably.
About 50 soldiers involved in the coup surrendered on one of the bridges across the Bosphorus Strait in Istanbul after dawn on Saturday, abandoning their tanks with their hands raised in the air. Reuters witnesses saw government supporters attack the pro-coup soldiers who had surrendered.
By Saturday afternoon, CNN Turk reported that security forces had completed an operation against coup plotters at the headquarters of the military general staff. Security sources also said police detained about 100 military officers at an air base in the southeast.
Neighboring Greece arrested eight men aboard a Turkish military helicopter which landed in the northern city of Alexandroupolis on Saturday, the Greek police ministry said, adding that they had requested political asylum.
At one stage military commanders were held hostage by the plotters and by Saturday evening — 24 hours after the coup was launched — some operations against rebels were continuing.
Cavusoglu, the foreign minister, said soldiers at the Incirlik air base, used by the United States to launch air strikes on Islamic State targets in Syria, were involved in the attempt. He said Turkey would resume operations with the US-led coalition once the anti-coup operations were completed.
Lawmakers in hiding
The coup began with warplanes and helicopters roaring over Ankara and troops moving in to seal off the bridges over the Bosphorus, which separates Europe and Asia in Istanbul.
Turkish maritime authorities reopened the Bosphorus to transiting tankers after shutting the major trade route from the Black Sea to the Aegean for several hours for security and safety reasons.
In the early hours of Saturday, lawmakers hid in shelters inside the parliament building, which was fired on by tanks. An opposition deputy told Reuters that parliament was hit three times and people had been wounded.
When parliament convened later in the day, the four main political parties — running the gamut from Erdogan's right-wing Islamist-rooted AK Party to the left-of-center, pro-Kurdish Peoples' Democratic Party (HDP) — came together in a rare show of unity to condemn the attempted coup.
A Turkish military commander also said fighter jets had shot down a helicopter used by the coup plotters over Ankara.
Momentum turned against the coup plotters as the night wore on. Crowds defied orders to stay indoors, gathering at major squares in Istanbul and Ankara, waving flags and chanting.
"We have a prime minister, we have a chief of command, we're not going to leave this country to degenerates," shouted one man, as groups of government supporters climbed onto a tank near Ataturk airport.
Kerry said he had phoned the Turkish foreign minister and underlined "absolute support for Turkey's democratically elected, civilian government and democratic institutions".
Flag carrier Turkish Airlines resumed flights on Saturday, though some foreign carriers canceled weekend flights.
At the height of the action, rebel soldiers took control of TRT state television, which announced a countrywide curfew and martial law. An announcer read a statement on the orders of the pro-coup faction that accused the government of eroding the democratic and secular rule of law. Turkey would be run by a "peace council" that would ensure the safety of the population, the statement said.
Turkey is one of the main backers of opponents of President Bashar al-Assad in Syria's civil war and hosts 2.7 million Syrian refugees. It was a departure point last year for the biggest influx of migrants to Europe since World War Two.
Turkey has suffered numerous bombings and shootings this year, including an attack two weeks ago by Islamists at Ataturk airport that killed more than 40 people, as well as those staged by Kurdish militants.
After serving as prime minister from 2003, Erdogan was elected president in 2014 with plans to alter the constitution to give the previously ceremonial presidency far greater executive powers.