In 1808, the Portuguese court, fleeing from Napoleon troops which had invaded Portugal, established themselves in the city of Rio de Janeiro. After Joao VI returned to Portugal in 1821, his heir-apparent Pedro became regent of the Kingdom of Brazil. Following a series of political incidents and disputes, Brazil achieved its independence from Portugal on September 7, 1822. On October 12, 1822, Dom Pedro became the first Emperor of Brazil, being crowned on December 1, 1822. Bahia was the last area of Brazil to join the independent confederation; Some members in the elite remained loyal to the Portuguese crown after the rest of the country was granted independence. After several battles, mostly in Piraj?, the province was finally able to expel the Portuguese on July 2, 1823, known as Bahia Independence Day, a great popular celebration. In the state there is an ongoing discussion about the exact moment of Brazilian independence, because for almost all "baianos," it really happened in Bahia with the battles, and not on September 7, when the Emperor, Pedro I, declared independence.