A Ugandan judge ruled on Monday that opposition leader and presidential candidate Kizza Besigye had been illegally detained and freed him on bail, clearing the way for him to begin campaigning for next month's election.
Besigye, a top challenger to President Yoweri Museveni, faces twin trials on charges of treason and rape at the civilian High Court and terrorism and weapons offences at a military court-martial.
After High Court Judge John Katutsi freed him, 49-year-old Besigye said he would begin campaigning for the February 23 polls after assessing his situation.
"There is now every evidence to show that this government does not respect the rule of law," Besigye told reporters outside the court. "What I can say is that we shall do everything within our means to see this country returns to the democratic path."
His supporters took to the streets in celebration after the ruling, but police reacted quickly and fired tear gas to disperse them.
Besigye, who had registered his candidacy from behind prison bars, was due to address a rally in the capital Kampala later on Monday.
After the four-hour hearing, Katutsi ruled the military tribunal's authority to keep Besigye in prison had expired last month. "The applicant has been in illegal detention since December 2. His continued stay in prison is therefore illegal," Katutsi told the court.
The High Court had already agreed to grant Besigye bail after his civilian trial opened on December 19. Besigye has denied the charges. It was possible that the military court could order Besigye's re-arrest, since it has said it does not answer to the civilian High Court.
Britain and other donors have cut aid to the east African nation because of the arrest, detention and trial of Besigye, whose popularity looks certain to provide a tough challenge to Museveni in the election.
Besigye's Forum for Democratic Change (FDC) party says the government trumped up the charges to keep him from running against his former friend and ally.
The government denies the charge, and Museveni said he relishes the chance to beat Besigye at the polls once again.
Once Museveni's personal physician, including during the guerrilla war that brought him to power in 1986, Besigye was arrested on November 14.
He fled Uganda in 2001, saying the government was trying to kill him after he lost a violence-marred election to Museveni. The two allies first fell out in 1998, after Besigye published an article challenging Uganda's democratic credentials and accused the president of becoming the type of African autocrat Museveni had often mocked.
Museveni's image as a model African leader took a hit last year after his allies removed a constitutional term limit that would have mandated he step down once his second five-year term expired this year.