After months of legal wrangling and political melodrama, Pakistan’s Supreme Court ruled narrowly Thursday that Prime Minister Nawaz Sharif could keep his job but ordered a further investigation into charges that he and his family had hidden assets through offshore tax havens.

In a split decision, three justices found there was not enough evidence of financial or other misdeeds to remove the premier from office, though two members disagreed. All five raised questions about the source of funds for several London apartments owned by the Sharif family, which was never fully explained in court.

Sharif and his supporters greeted his narrow reprieve with visible joy and relief. His adult daughter Maryam, whose financial role in the apartments was a focus of the case, tweeted photos of family and aides hugging and grinning. TV news footage showed supporters dancing and giving away candy.

“We are grateful to God for granting us this victory,” Defense Minister Khawaja Asif told journalists outside the Supreme Court. “It happened because millions of Pakistanis were praying for their prime minister, their true leader.” He vowed that Sharif, 67, would win election in 2018.

The caustically worded, 540-page ruling fell short of disqualifying Sharif from office, as his opponents had sought. It allows him to lead his party, the Pakistan Muslim League-N, to compete in elections. But it left him politically diminished, his party vulnerable and the odor of shoddy financial practices in the air, creating a perfect target for opponents.

Pakistani Prime Minister Nawaz Sharif inspects a Bosnian army honor guard during a visit to Sarajevo in December. (Amel Emric/AP)

“Nawaz Sharif isn’t off the hook yet, but given how concerned the government was about Sharif getting disqualified, it could have been much worse,” said Michael Kugelman, a Pakistan expert at the Woodrow Wilson International Center for Scholars in Washington. “The government received a fairly hard slap on the wrist, but ultimately it survived.”

Imran Khan, the opposition leader and former cricket star who was Sharif’s principal accuser, issued a statement congratulating the court but demanded that Sharif step down, saying he has “no moral authority” to remain as prime minister.

The court’s skepticism was reflected in the opening lines of the verdict, which referred to the epigraph in Mario Puzo’s novel “The Godfather” — “Behind every great fortune there is a crime.” It added the full original quote, from French novelist Honoré de Balzac, which said that the secret behind great but unaccounted fortunes is “a crime that was never found out, because it was properly executed.”

[Pakistan’s political drama moves from streets to courtroom]

The Sharif case, the ruling said, “revolves around that very sentence.” The court order listed a number of questions about the Sharif family’s finances that it said “need to be answered.” The Sharifs and their attorneys presented numerous versions of how various properties had been bought and sold.

The court’s decision brought an orderly ending to the year-long political and legal circus that has consumed the nation since last April, when Pakistan was cited in the “Panama Papers,”a trove of leaked documents, as one of several countries whose leaders were said to have hidden assets offshore. Sharif denied the charges and vowed in an emotional speech that he would “resign immediately” if found guilty of wrongdoing.

The legal petition against Sharif was spearheaded by Khan, who led boisterous street rallies calling for his ouster. In October, he threatened to shut down the capital with swarms of protesters but backed off after the high court agreed to take up the case.

Meanwhile, the mood through dozens of legal hearings veered from confrontational to comic. Khan denounced Sharif as a liar and a crook. Sharif produced a letter from a friendly Persian Gulf prince swearing that he had paid for the London apartments. Justices rolled their eyes, asked sharp questions and quoted Shakespeare.

“There are two different money trails before us,” Justice Asif Saeed Khosa noted during a recent hearing. “How did the money go from Jeddah and then to London? How did the money go from Dubai to London and then Qatar?”

Thursday’s ruling included a list of similar issues that the justices instructed investigators to pursue. They asked how Sharif’s then-young children could have purchased the London properties in the 1990s, whether the letters from the Qatari prince were “a myth or a reality,” and what was the source of “huge sums” the Sharifs described as gifts.

Sharif, a three-time premier who won praise for pushing economic development and reaching out to archrival India, has seen his efforts overshadowed by the corruption case as well as a surge in Islamist terrorist attacks and worsening confrontations with India.

Beyond the feud between Sharif and Khan, there was a larger issue at stake: a power struggle between the executive and the judiciary that gave the public hope for change in a weak democratic system that has often been undermined by the army.

Millions of Pakistanis, poor and powerless, wanted to see corruption punished and the courts act with independence, but many held out little hope. “Nothing will come out of this drama,” predicted a person using the nickname “asad” whose comment was in a list of online responses to a Dawn newspaper chronology of the case last week. “This is an exercise in futility.”

Yet here was a also sense of unease about what would happen if Sharif were forced to step down. Even his detractors did not want to see another military coup or risk souring relations with a new and unpredictable administration in Washington.

With Sharif still in office but chastised, analysts called Thursday’s ruling a victory for Pakistani democracy, with a prime minister enduring a long legal process and all sides accepting the verdict. “Given the deep legacy of military rule in Pakistan, this isn’t something to take lightly,” Kugelman said.

Read more:

Pakistan’s surprisingly candid readout of Trump’s call with prime minister

‘Nothing here but dust’: What Afghan deportees face after years in Pakistan

Pakistan’s prime minister is defying the clerics — very carefully

Today’s coverage from Post correspondents around the world

Like Washington Post World on Facebook and stay updated on foreign news