Brazil's ex-President Luiz Inácio Lula da Silva will be jailed while he appeals against a graft conviction, the Supreme Court has ruled.
He is facing 12 years in jail on charges of accepting a bribe but had asked to remain free during his appeal.
Lula claims the charges are politically motivated, and designed to prevent him from running for president in October.
He has a lead in opinion polls. His Workers' Party said the ruling was a "tragic day for democracy and Brazil".
The Supreme Court judges ruled against him by six to five after a marathon session, which ended in the early hours of Thursday.
Lula watched the ruling at the Metalworker's Union, where his supporters held an upbeat concert. The 72-year-old former president is likely to remain free until paperwork for his arrest is completed.
Lula served as president between 2003 and 2011. Despite his lead in the polls, he remains a divisive figure.
Up to 20,000 people protested in São Paulo on Tuesday calling for his immediate imprisonment, while supporters also rallied in large numbers in a rival demonstration.
Lula has described the battle against his conviction and prison term as a continuation of his fight against Brazil's military rule, which came to an end in 1985.
"I did not accept the military dictatorship and I will not accept this dictatorship of the prosecutors," he told a gathering of supporters on Monday.
Under a 2010 Brazilian law called "clean slate law", no one convicted of a crime upheld on appeal can run for elected office for at least eight years.
That law would rule Lula out from running for the presidency in October. However, exceptions have been made to the law before.
The decision as to whether Lula can stand for president will rest with the Superior Electoral Court (TSE).