Uganda's constitutional court has ruled that opposition leader Kizza Besigye and 22 co-accused cannot be tried for terrorism by a military court.
Kizza Besigye is seen as the first credible challenger to the president
The judges said these charges could only be heard in the High Court. Dr Besigye is also facing rape and treason charges in a civilian court.
Dr Besigye is seen as the president's main challenger in February's election.
The court also ruled that the deployment of troops at the High Court last November was unconstitutional.
Dr Besigye, who was arrested in November last year, shortly after returning from exile, says the charges against him are politically motivated.
If found guilty of the two remaining charges, Dr Besigye would be barred from the elections.
Moses Adriko, president of the Uganda Law Society, which took these complaints to the Constitutional Court, said it was still possible for civilians to be court-martialled.
"The door is still open for the state to bring other charges, but definitely not on terrorism and firearms charges," he told the BBC's Focus on Africa programme.
Kizza Besigye was once a political ally of President Museveni
The court also reversed an earlier decision that the General Court Martial was subordinate to the High Court, ruling that both courts were now on an equal footing.
Mr Adriko said that this was a cause for concern.
"We think there is some uncertainty in the law and we would like the position of the hierarchy of our courts restated authoritatively by the Supreme Court," he said.
In the light of the ruling, Mr Adriko called for all 22, who were imprisoned on the orders of the military, to be freed.
The panel of five judges also considered the incident last November when soldiers in black T-shirts and wielding machine-guns surrounded the High Court where men accused of treason with Dr Besigye were appearing.
Although they were granted bail, the suspects opted to return to prison, fearing the armed men, who had not identified themselves.
The court upheld the Law Society's complaint that this was an assault on the independence of the judiciary and cautioned the executive arm of government, saying it should not to allowed to happen again.
Dr Besigye, who has been out on bail for the last month, is viewed as the first credible challenger to President Yoweri Museveni, who has been in power for 20 years.
These will be the first multi-party elections since Mr Museveni took power.