By Lesley Wroughton, Matt Spetalnick and Yeganeh Torbati

VIENNA/WASHINGTON (Reuters) - The first glimpse of a secretly negotiated U.S.-Iran prisoner exchange came on Saturday in a flurry of early morning electronic filings in federal courts from New York to California as prosecutors dropped sanctions violations cases against more than half a dozen Iranians.

The low-key legal steps were followed by Iran's announcement via state media that it was freeing four Iranian-Americans, including Washington Post journalist Jason Rezaian and Christian pastor Saeed Abedini and Amir Hekmati, a former U.S. Marine. Hours later, Secretary of State John Kerry said they had all been released and would soon be on their way home.

The prisoner swap was choreographed to coincide with a high-level diplomatic gathering in Vienna that sealed the end of a decade of international sanctions on Iran in return for meeting its commitment to curb its nuclear program.

The deal, a major step toward overcoming acrimony standing in the way of any further rapprochement between longtime foes Washington and Tehran, was the culmination of months of diplomatic contacts, secret talks and legal maneuvering.

And, according to an account pieced together by Reuters on previously unreported Obama administration deliberations, the prisoner exchange came close to falling apart because of a threat by Washington in December to impose fresh sanctions on Iran for recent ballistic missile tests.

The nuclear deal signed on July 14 between Iran and world powers was trumpeted by the White House as a signature foreign policy achievement by President Barack Obama. But he also faced criticism for refusing to make the accord contingent on Iran's release of Americans known to be held by Iran.

In public comments, Obama had insisted as recently as mid-December that linking the Americans' fate directly to the nuclear negotiations would have encouraged the Iranians to seek additional concessions.

U.S. officials who recounted the complex process that led to the prisoner deal stuck to that assertion but acknowledged that the nuclear deal had opened up a channel of communication about the American detainees that they were eager to use.

BEHIND-THE-SCENES CONTACTS

Iranian Foreign Minister Javad Zarif and Kerry, who developed a close rapport during months of unprecedented talks hammering out last year's nuclear deal, played crucial roles in clinching the prisoner deal, U.S. officials said.

In particular, a conversation with Zarif and Iranian President Hassan Rouhani's brother in Vienna once the nuclear deal was reached last year helped spur efforts toward a prisoner deal, U.S. officials said.

But much of the diplomatic heavy lifting was handled by Brett McGurk, a State Department envoy with broad Middle Eastern experience. He conducted 14 months of secret negotiations with an unnamed Iranian representative that accelerated in the aftermath of the nuclear accord, the officials said.

"We have been raising these American prisoners for some time and the nuclear talks gave us the opportunity to raise it face to face," a senior U.S. official said, adding that the U.S. side would always carve out time to discuss the prisoners on the margins of the nuclear talks.

"The Iranians said they wanted a goodwill gesture on our part as a reciprocal measure. They gave us over time a list of Iranians, mostly dual nationals, that were either imprisoned or convicted or charged in our courts," the official said. "We whittled down the list to exclude anyone that was charged with crime related to violence, with terrorism."

The Swiss government, which handles U.S. consular matters in Tehran because of a lack of diplomatic relations between the United States and Iran, helped mediate, said a senior administration official in Washington.

But there were some bumps and missteps along the road to Saturday's prisoner announcement.

The day before the Obama administration was due to slap new sanctions on Iran late last month over the ballistic missile tests that violated a United Nations ban, Zarif warned Kerry the move could derail the prisoner deal, U.S. officials told Reuters.

Kerry and other top aides to Obama, who was vacationing in Hawaii, convened a series of conference calls and concluded they could not risk losing the chance to free Americans held by Tehran.

At the last minute, the administration officials decided to delay a package of limited and targeted sanctions, the officials said.

Asked whether Obama was involved in the decision to delay the sanctions, a senior U.S. administration official said: "This absolutely requires the president's approval and this is something he was briefed on regularly over many months."

Another Obama aide told reporters on a conference call on Saturday that the United States expects to impose new sanctions "designations" over the missile tests but declined to say when.

"SAEED IS RELEASED"

While discussions about the prisoners was occurring, another dual U.S.-Iranian citizen, Nosratollah Khosravi-Roodsari, was detained by the Iranians. "We insisted that he be in the mix as well," a U.S. official said.

In the end, Iran agreed to release Rezaian, the Post's Tehran bureau chief held in an Iranian prison for about 18 months; Abedini, 35, an Iranian-American pastor from Idaho; the former Marine Hekmati; and Khosravi-Roodsari, about whom little is known.

A fifth prisoner, American student Matthew Trevithick, was released separately and left Iran, but "logistical steps" still had to be worked out before the others could be flown out together, a senior administration official said.

"It is confirmed: Saeed is released from Iranian prison," Abedini's wife, Naghmeh Abedini, wrote on Twitter even before official U.S. confirmation. The couple had regularly traveled to Iran on Christian mission work. He was setting up an orphanage in the country in 2012 when he was detained.

Robert Levinson, a former FBI agent and DEA agent, who disappeared in Iran since 2007, was not on the list. U.S. officials have believed for several years that Levinson died in captivity. Iranian officials had repeatedly denied any knowledge of his disappearance or whereabouts.

"Iran has also committed to continue cooperating with the United States to determine the whereabouts of Robert Levinson," a U.S official said.

Obama pardoned three Iranians charged with sanctions violations as U.S. authorities moved to drop charges or commute prison sentences for five other men, according to court records and people familiar with the matter.

Iranian officials met recently with some of the prisoners held in the United States to see if they would be willing to return to Iran if a swap was arranged, said a person familiar with the cases. It was not known how many of them if any would go back.

The men pardoned were Bahram Mechanic, Tooraj Faridi, and Khosrow Afghahi, according to Mechanic's lawyer, Joel Androphy. They were accused in 2015 of shipping electronics to Iran. Mechanic and Afghahi were being held without bail in Houston, while Faridi was out on bail. All three are Iranian-American dual citizens and had pleaded not guilty.

Prosecutors filed legal motions to abandon other sanctions-related cases in courts in New York, Houston, Los Angeles and Boston.

More From Missoula Current