THANKS to a film (“City of God”) made in 2002, Cidade de Deus, a rundown housing project in the suburbs of Rio de Janeiro, became an internationally known symbol of the lawless urban squalor that has blighted Brazil's most glamorous city for decades. The Comando Vermelho, a heavily armed gang of drug traffickers, dominated the lives of the 60,000 or so residents of Cidade de Deus and its surrounding favelas (the Brazilian term for the tightly packed self-built slums of the poor). The gangsters, some of them teenagers, could impose their reign of terror thanks to the brutal incompetence of the police and the venal indifference of the authorities.

Some of these problems are repeated across Brazil's cities. But they are particularly acute in Rio de Janeiro, which has suffered chronic misgovernment and decline since the capital moved to Brasília in 1960. Ahead of Rio's bagging of the 2016 Olympic games last autumn, rivals muttered about its criminal violence. In the week before the Olympic committee's decision, the New Yorker magazine ran a chilling account of a Rio drug lord and his fief.

But Rio is undergoing a renaissance, one which even holds out hope for the 1m of the city's 6m residents who live in favelas. Last year the police took control of Cidade de Deus—this time for keeps, they say. A force of 318 officers, backed by 25 patrol cars, is based in a new community-police station in a side street between two fetid, litter-strewn drainage channels. The result has been dramatic. In 2008 there were 29 murders in Cidade de Deus. So far this year there has been just one, and it involved a beating rather than a firearm, says José Beltrame, the security secretary in the Rio state government who is in charge of policing in the city. Other crime has fallen too.

Many residents are appreciative. “It was horror before,” says Jeanne Barbosa, who runs a small bar on the ground floor of her house. “Bodies would be thrown out of passing cars, and there were kids with revolvers.” Her niece was killed as she walked home, by a stray bullet from a firefight between the police and traffickers. “Now the children can play in the street.” A dreadlocked unemployed welder who gives his name as Sérgio is more sceptical. He says the police commit abuses. His friend, who has the blank stare of a crack addict, adds with deranged precision: “89% of them are corrupt.”

The police station in Cidade de Deus is one of eight, known as UPPs or Pacifying Police Units, set up in Rio's favelas since late 2008. They are part of an ambitious strategy by Mr Beltrame to restore law and order. This starts with better intelligence work. To minimise abuses, the police who staff the UPPs are newly recruited and specially trained. He has assigned targets to the whole force. By getting the city and federal governments to chip in with bonuses, he has managed to double the salaries of front-line policemen.

The police's objective is not so much to abolish the drug trade as to drive the armed gangs from the streets, and thus to open the way for other branches of the state. The gangs condemn favela residents to a life outside the law: electricity and satellite television are pirated; few residents have property deeds; and their jobs are in the informal economy, as are the minibuses that take them to work. The authorities are trying to consolidate security with legality and infrastructure. On May 31st Cidade de Deus gained its first health clinic. Next door, the city government is building a subsidised restaurant. Nearby, two young women are signing up residents for the electricity company, which offers new fridges and energy-saving light bulbs as an incentive to submit to higher bills.

So far the plan is little more than an experiment, albeit a promising one. The UPPs cover only around 140,000 people. The traffickers are lying low and have hidden their weapons, but they have not disappeared. The police must still overcome the mistrust of the community, says Tião Santos of Viva Rio, an NGO. The police in both Rio and São Paulo are still too trigger-happy: Human Rights Watch, a campaign group, recently noted that between them they kill more than 1,000 civilians a year.

City of the unholy trinity

Most of Rio's 1,000-odd favelas are still more or less controlled by three trafficking gangs or by criminal militias set up by rogue police and firemen. But even in some of these places there is hope. Take Vigário Geral, a small favela where 21 people were massacred by a police death-squad in 1993. On a recent visit, the footbridge over the railway that leads there was guarded by two young men, one with a bulky revolver tucked ostentatiously into the top pocket of his jacket. But back in the 1990s there were a dozen youths with rifles guarding the bridge, says José Júnior of AfroReggae, an NGO which has just opened a large cultural centre in Vigário Geral, financed by government and private companies.

Boosted by falling crime rates (see chart), Mr Beltrame, a former federal police chief, plans to install 40 UPPs covering 500,000 people over the next four years. By then he hopes Rio's murder rate will be similar to that of São Paulo, which reformed its police in the 1990s.

If he has a good chance of achieving this, it is because Rio is enjoying “a magic moment [in which] everything is conspiring in its favour,” says André Urani, an economist who studies the city. The economy is growing strongly and creating jobs. Rio is the hub for Brazil's offshore oil, but it is also attracting new industries. After decades of populism and political conflict, public management in the state is being transformed. Sérgio Cabral, the state governor, and Eduardo Paes, the mayor, are both allies of Brazil's president, Luiz Inácio Lula da Silva (all three turned up to open the clinic in Cidade de Deus). So federal money is pouring into the city. The state government, having cleaned up its chaotic finances, has room to borrow.

The extra funds will pay for an upgrade of the city's transport system for the 2014 World Cup (the final will be played in Rio's Maracanã stadium) and for the Olympics. Having secured the games with a conservative bid that put most of the events in well-heeled Barra and Copacabana, the authorities are now tweaking the plan. Mr Paes wants to revamp the seedy port area by getting private developers to build accommodation there for the 20,000 journalists who will cover the games. Some of the new money is also going on installing the paving, lighting and sewerage that turn favelas into neighbourhoods.

There is still much to do. Complexo do Alemão, an agglomeration of favelas spread over hillsides in the north of the city, is dotted with new housing projects and the concrete pillars of a 5km (3 mile) cable car that by later this year should link it to the suburban railway network. One of its muddy streets of small shops boasts a branch of Banco Santander, opened last month—the first bank inside a Rio favela. Guilherme Nicolas, the branch manager, hopes to sign up 10,000 customers. But he says most residents earn less than 1,000 reais ($600) a month, and some want loans to buy food. Insecurity and poverty have gone hand in hand in Rio. A safer city has a better chance of becoming a less socially divided one.