IN THE middle of 2016 a suicide-bomber blew up a minibus full of judicial staff in Kabul. The injured were rushed to the Emergency Hospital in the Afghan capital. One was married to a nurse there, who was on duty when he arrived. He is now paraplegic. She is “coping”, says a colleague: “She’s one tough woman.”

It is striking how many of the hospital’s patients were targeted for upholding the law. Amir Muhammad, a policeman with shrapnel wounds, says the Taliban attacked his post and killed seven of his 14 fellow officers. “They had heavier weapons than us,” he explains.

The Taliban are as shrewd as they are brutal. Afghanistan is close to becoming a failed state again. To avert that catastrophe, the government must provide adequate security and establish something resembling the rule of law. But it is tricky to set up a functioning legal system when judges and police officers keep getting murdered. Moreover, the government can hardly claim to be keeping people safe when they fear being blown up on their way to work.

Since Barack Obama drastically reduced the number of American troops in Afghanistan, the Taliban have made alarming gains. NATO forces there fell from a peak of 132,000 in 2011 to around 13,000 today. Only about 60% of Afghans live in areas controlled by the government. Others live under Taliban control (about 10%) or in areas that are violently disputed.

Wherever they can, the Taliban replace the government’s justice with their own swifter, harsher (and, some say, less corrupt) variety. If two peasants quarrel over a piece of land, a Taliban official will hear both sides and make a ruling. Such rulings often stick, for no one doubts that the Taliban will enforce them.

The pull-out of foreign troops has made Afghanistan not only more dangerous, but poorer, too. By one estimate, the NATO mission cost almost $1trn between 2001 and 2014—more than six times as much as Afghanistan’s GDP over that period. Many Afghans sold stuff to and built things for the foreigners. Now that boom is over. Economic growth plunged from 14% in 2012 to 0.8% in 2015.

“Day by day we are losing our business,” says Ashad Wali Safi, who runs an electronics store in Kabul. The aid agencies that used to buy printers from him are gone. Security is “very bad”. (The previous day, a suicide-bomb had killed at least 30 people in a nearby mosque.) “Even in daytime, we don’t feel safe. At night? Forget it.”

Adding to the uncertainty, no one knows what Donald Trump’s Afghan policy will be. In the past he has said both that American troops should leave Afghanistan, and that they should “probably” stay. Afghans are nervous. “We hope this new American administration will be supportive too,” says Ashraf Ghani, the president.

Few things matter more than fixing failed states. Broadly defined, state failure provides “a general explanation for why poor countries are poor”, argue Daron Acemoglu of the Massachusetts Institute of Technology and James Robinson of the University of Chicago in “Why Nations Fail”. Life in a failed or failing state is short and harsh. Life expectancy in the bottom 16 countries on the Fragile States Index compiled by the Fund for Peace, a think-tank (see map), is 85% of the global average. Measured at purchasing-power parity, income per head is a miserable 21%.

There goes the neighbourhood

Lawless regions, such as the badlands of Pakistan and Yemen, act as havens for terrorists. And civil wars tend to spill across borders. The Rwandan genocide of 1994, for example, sparked an even deadlier conflagration in Congo.

In the most extreme form of state failure, in places like Somalia, the central government does not even control the capital city. In milder forms, as in Nigeria, the state is far from collapse but highly dysfunctional and unable to control all of its territory. Or, as in North Korea today or China under Mao Zedong, it controls all of its territory but governs in a way that makes everyone but a tiny elite much worse off.

This article will look at two main examples: an unambiguously failed state, South Sudan, and a state tottering on the brink, Afghanistan. It will argue that, as Mr Acemoglu and Mr Robinson put it, the key to understanding state failure is “institutions, institutions, institutions”. The world’s newest country, South Sudan has received billions of dollars of aid and the advice of swarms of consultants since seceding from Sudan in 2011, but has failed to build any institutions worthy of the name. Afghanistan faces a terrifying insurgency but has a president doing his best to restore order.

States are not wretched and unstable because of geography—if so, how to explain the success of landlocked Botswana? Nor is culture the main culprit: if so, South Koreans would not be more than 20 times richer than North Koreans. Some societies have “inclusive institutions that foster economic growth”; others have “extractive institutions that hamper [it]”. South Sudan is an extreme example of the latter.

Never look back

“Everybody I know is getting out,” says Joyce Mandi, as she mixes maize porridge for her six children at a bus stop in South Sudan. Around her, young men heave bags and mattresses onto the roof of a minibus. Ms Mandi is fleeing her village and heading for Kakuma, a refugee camp in neighbouring Kenya. Her husband has gone into the bush, she says, to fight the government.

The South Sudanese, who are mostly black African and non-Muslim, fought for half a century to secede from Sudan. Arab Muslims from the north used to oppress and enslave them. Perhaps 2m southerners died in the war of secession. But few think life has got better since then.

Those now in charge are former guerrillas from the Sudan People’s Liberation Army (SPLA), a group of tribal militias united only by hatred of the north. The first president, Salva Kiir, tried to hold the SPLA’s factions together by paying them off with petrodollars (oil is almost the only thing South Sudan exports). Alex de Waal of Tufts University estimates that in 2013 the government paid salaries for 320,000 soldiers, police and militiamen—more than a tenth of all men aged 15-54. Many of these soldiers did not exist: their pay was pocketed by the warlords supposedly commanding them.

But the state’s largesse did not buy loyalty. Instead, it encouraged the men with guns to demand more. Then the money ran out, thanks to collapsing oil prices and a suicidal game of chicken, in which the government stopped production to try to squeeze better terms from Sudan (which controls the pipeline through which South Sudanese oil is exported).

As his coffers emptied, Mr Kiir started flagrantly to favour his own Dinka tribe, South Sudan’s biggest, to stay in power. His vice-president, Riek Machar, who is from the Nuer tribe, the second-biggest, was forced out of government in July 2013 and went back to war later that year. A peace deal in 2015 quickly broke down. Some 3m South Sudanese—a quarter of the population—have fled their homes. Were it not for food aid, often dropped out of planes onto remote villages, hundreds of thousands would starve.

South Sudan failed to build institutions that transcended tribal loyalties or curbed the power of warlords. Torit, where Ms Mandi boarded that minibus to Kenya, is a good place to observe the hollowness of the country’s government. Though it is capital of one of South Sudan’s 28 states, it feels like a military outpost. Troops in “technicals”—pick-up trucks with mounted machine-guns—patrol the streets.

There are plenty of government buildings, including state ministries of education, culture and health. But none of them does much. Teachers were last paid in September, says Jacob Atari, the local education minister. Inflation of over 800% means their monthly salary of around 300 South Sudanese pounds is now worth less than $4. Over 70% of children are out of school, says Mr Atari.

Nowhere in South Sudan does the state do what it is supposed to. Only 27% of adults can read, according to the UN. Preventable diseases such as cholera, measles and malaria are rampant. The rule of law is a distant dream.

The country’s political system is in theory decentralised, but in reality the money flows through Juba, the national capital. And instead of being distributed to states, it is typically stolen or spent on weapons. Politics is a euphemism for armed battles over plunder. The warlord who wins can steal the oil and pay his troops. (Or, he can simply let them rob civilians.)

The fighting becomes tribal because warlords recruit by stirring up ethnic tension so that their kinsmen will rally to them. This creates a vicious circle. Lacking protection from other institutions, people seek it from their own tribe. Rather than demand evenhanded government, they back tribal leaders, knowing that they will steal and hoping they will share the spoils with their kin.

The splintering of South Sudan can be glimpsed in the “protection of civilians” camps maintained by the UN. One in Juba holds almost 40,000 people. At night, gunshots are common and aid workers refuse to venture inside. Most of the residents are Nuers, like Mr Machar, who have been stranded here since the civil war began. They are sure who is to blame. “Our tribe was killed by the government and so we came here,” says Kikany Kuol Wuol, a community chairman in the camp. “We cannot leave, we have nowhere to go. If our women just go outside to look for firewood they are raped.” When fighting broke out in Juba in July between Mr Machar’s forces and the government, it spread into the camp as UN peacekeepers withdrew. The problem, says Mr Kuol, is that: “This is a government only for Dinkas. The rest of us they want to starve to death.” Everyone in the camp supports Mr Machar, he says.

Mr Acemoglu and Mr Robinson are pessimistic about failed nations’ chances of turning around. Extractive institutions typically have historical roots. For example, the authors trace the failure of today’s Democratic Republic of Congo partly to the pre-colonial Kingdom of Kongo, where taxes were arbitrary (one was levied whenever the king’s beret fell off) and the elite sold their subjects to European slavers. Peasants therefore lived deep in the forest, to hide from slavers and tax-collectors. They did not adopt new technology, such as the plough, even when they heard of it. Why bother, when any surplus was subject to seizure? Modern Congolese farmers make similar complaints.

“Why Nations Fail” argues that “the politics of the vast majority of societies throughout history has led, and still leads today, to extractive institutions.” These tend to last because they give rulers the resources to pay armies, bribe judges and rig elections to stay in power. These rulers adopt bad policies not because they are ignorant of good ones but on purpose. Letting your relatives embezzle is bad for the nation but great for your family finances.

But failed states are not doomed to stay that way. Between 2007 and 2016, according to the Fragile States Index, 91 countries grew more stable and 70 grew shakier. Among those improving were giants such as China, Indonesia, Mexico and Brazil. The worst performers were mostly smaller, such as Libya and Syria.

Even states that have collapsed completely can be rebuilt. Liberia and Sierra Leone were stalked by drug-addled child soldiers a decade and a half ago; now both are reasonably calm. The key is nearly always better leadership: think of how China changed after Mao died. Many bad rulers continue deliberately to adopt bad policies, but they can be—and often are—replaced with better ones.

Instructions included

Afghanistan’s president since 2014, Mr Ghani is a former academic and author of a book called “Fixing Failed States”. His TED talk on fixing broken states has been viewed 750,000 times. Now he is trying to put his own theories into practice.

Yet he admits that rebuilding Afghanistan is more complex than he expected. The insurgents draw support from several sources: local grievances, tribal animosities, global Islamist networks, organised crime (Afghanistan is the world’s largest producer of opium) and the Pakistani security services. In 2015 Mr Ghani accused Pakistan of being in an “undeclared state of hostility” towards his country. Now he goes further. “In October it was almost a declared state of hostility,” he says. The Taliban enjoy havens in Pakistan’s lawless areas and, analysts suspect, direct help from Pakistani spooks, some of whom would rather have Afghanistan in chaos than see India gain a foothold there. Recent suicide-bombs in Kabul appear to have contained military-grade explosives, which Afghans assume came from over the border.

Mr Ghani has a clear idea of the state’s basic functions. First, it must uphold the rule of law. Second, it must secure a monopoly on the use of violence. The two are linked. As Sarah Chayes points out in “Thieves of State”, when people see the state as predatory, they are more likely to support insurgents. She cites the example of an Afghan who was shaken down nine times by police on a single journey, and vowed not to warn them if he saw the Taliban planting a bomb to kill them.

Mr Ghani justly takes credit for the fact that the Taliban did not overthrow the state after Mr Obama’s pull-out. “In 2015 we were in danger, because the global and regional consensus was that we would not be able to hold,” he says. Now, says General John Nicholson, the commander of the NATO forces in Afghanistan, the Taliban have been fought to a stalemate. They seized a big city, Kunduz, in 2015, but were driven out and have taken no more since. NATO air power combined with American-trained Afghan special forces pack “an offensive punch”, says General Nicholson. The Taliban cannot mass troops for fear of NATO bombs. However, they have “safety outside the country”.

Mr Ghani is less tolerant of corruption than was his predecessor, Hamid Karzai, and appears to have cleaned up customs and government procurement a fair bit. He has improved tax collection and promoted infrastructure projects, such as rail links and power plants, in the hope that Afghanistan will become a central Asian hub. (He notes with satisfaction that the Taliban have said they will not attack such schemes.) He promotes education for women, which was banned when the Taliban ruled Afghanistan in 1996-2001. To conservative Afghans who think this would lead to illicit mixing with men, he has a convincing response. “In the remote provinces, they are asking for women doctors,” he points out. How can they have female doctors if they do not allow their daughters to go to school?

Politics by other means in South Sudan Nonetheless, a survey by the Asia Foundation finds that only 29% of Afghans believe the country is moving in the right direction. This is largely because 70% fear for their safety—the highest level in over a decade. However, a slim majority (54%) say the army is getting better at providing security, while only 20% say it is getting worse. Public perceptions of corruption have barely budged since Mr Ghani came to power, with 89% of Afghans saying it is a problem in their daily life. More encouragingly, the share of those who had dealt with police and reported sometimes having to pay bribes is falling somewhat: from 53% in 2015 to 48% in 2016. Foreign donors warm to Mr Ghani. In October he convinced them to pledge $15bn over the next four years. Yet he is leery of how aid is dispensed. The flood of foreign cash that followed the American-led toppling of the Taliban government in 2001 often undermined the state or was wasted. Aid agencies paid salaries 20 times higher than the Afghan civil service, prompting the best officials to quit to work as drivers and interpreters. Mr Ghani has long argued that aid should flow through the national government, rather than support a parallel state that can pack up and go when donor fashions change. He may be getting his way: roughly half of aid now passes through the national budget, a share that is expected to rise. Even with a leader determined to make good choices, building an honest state is hard. Mr Ghani complains of inaccurate information. “There were three databases in the Ministry of Education: one for teachers, one for salaries, one for schools…they weren’t talking to each other.” Faulty records make it easier for money to vanish. Digital payments should help, he says—the police thought they had received a pay rise when the first experiments with mobile payments began, because commanders could no longer skim their wages. But there is a long way to go.

“A decade ago, if you went into a minister’s office, you’d see dust on the desk, no computer and the minister picking his toenails,” says a Western official in Kabul. “Now you have competent ministers and lots of young professional staff who keep in touch via WhatsApp and speak English. The bad news is that Ghani is still learning how to be a politician. Karzai would get on the phone with tribal leaders and chat about their fathers’ health [before talking business]. Ghani tries to book them for a ten-minute meeting, and hustles them out of the door before the tea is cold.”

This is a common criticism. Mr Ghani is good at retail politics (he won the disputed election in 2014 partly because he had spent so much time sitting in villages asking ordinary Afghans what they wanted). But he is a technocrat among warlords, some of whom have been made billionaires by the drugs trade. He rules in uneasy coalition with a “chief executive” with ill-defined powers: Abdullah Abdullah, the man he beat in 2014. His vice-president is a blood-spattered warlord. The president will struggle to build a clean state when so many bigwigs prefer it dirty, critics say.

Mr Ghani dismisses the charge. “If politics becomes all tactics, where would you produce change?” he asks. He insists that he bends over backwards to be respectful of tribal leaders, “but it cannot be at the expense of building institutions.” This is a crucial point. Countries whose stability depends on an individual strongman are brittle. Those that create inclusive institutions need never fail again.