Democrats and Republicans reached an agreement to fund the government — well ahead of the Friday shutdown deadline — in a deal announced late Sunday night.

Congressional leadership still has to sell the 1,600-page, $1 trillion budget to their rank-and-file members, who will now begin poring over the details of the plan — where they may find plenty to object to — before voting on it later this week.

But key pieces of the deal are beginning to emerge. Congress is set to allocate new funding to programs that have been clamoring for help — including Puerto Rico’s broken Medicaid system and pensions for retired coal miners — as well as a new infusion of funding for the military. Meanwhile, several proposals that President Donald Trump pushed for in the budget — particularly money for the border wall and steep cuts to federal agencies — were left out of the deal altogether.

Here are five winners from the flurry of dealmaking on Capitol Hill — and three losers.

Winner: coal miners

Since around 2012, it’s been clear that the pensions and health care benefits of 120,000 retired coal miners in Appalachia would vanish without federal help. The private fund that they counted on to pay those benefits has been slowly careening toward insolvency, as the coal mining industry that was supposed to pay into it collapsed. And Senate Majority Leader Mitch McConnell (R-KY) killed multiple bipartisan deals that would have allowed the federal government to step in and make up the difference.

The problem began reaching a crisis point last summer, when thousands of miners began receiving notices in the mail warning them that their benefits were about to expire. Congress provided temporary funding to the miners in December 2016, but it was far from clear that they’d be able to cover the health insurance that miners’ groups have long demanded.

Now it looks like they will. The budget deal provides funding for some of the Miners Protection Act, ensuring that the government will cover the healthcare costs for the rest of the miners’ lives by taking money from a fund set up to reclaim abandoned mines. An aide to Sen. Sherrod Brown (D-OH), who along with Sen. Joe Manchin (D-WV) has been most vocal in demanding federal help for the miners, confirmed that the deal includes what they were looking for.

Without the pensions, most miners would be living off Social Security, which runs about $1,500 a month. The average prices of their prescription drugs come close to $1,800, said Phil Smith, an official with the United Mine Workers of America, even as recent academic research confirmed that retired miners are far more likely to need medical care for black lung operations and cancer treatments.

“This is the most important thing to them. It’s not just the money they rely on to get Christmas presents, fill the car with gas, help send their grandkids to college. It’s the money they need to survive in the most literal sense,” said Adam Wells, a staffer at the advocacy organization Appalachian Voices, in an interview in December 2016. “It’s their No. 1 priority.”

Winner: Puerto Rico

The budget deal reached by congressional leadership on Sunday will also protect health care for about 900,000 Puerto Ricans who were at risk of losing it — a huge win for the island, whose health care system would face a crisis without federal intervention.

It all stems from Puerto Rico’s reliance on Medicaid, the federal government health insurance program for the poor.

For most states, the federal government covers close to 60 percent of the cost of Medicaid. When it comes to the island, Uncle Sam has traditionally been far stingier — providing funding that covers just 15 percent of the cost of Medicaid for Puerto Ricans.

That problem is compounded by the fact that nearly half of Puerto Rico’s residents are on Medicaid, even though you have to be poorer to qualify for Medicaid if you live in Puerto Rico than if you live on the mainland US. And deep poverty on the island — exacerbated by an economic crisis over the past few years — has made residents’ reliance on Medicaid worse, according to Edwin Park of the Center on Budget and Policy Priorities.

In 2010, the Affordable Care Act attempted to throw Puerto Rico a lifeline by giving it $8.3 billion to cover its Medicaid costs until 2019. But that money proved to be not anywhere close to enough, and the ACA’s funding for Puerto Ricans’ health care was set to begin running out at the end of this year. That, experts say, would have thrown the island’s entire medical system into a dire tailspin.

“Hospitals have been closing; they're closing floors; doctors are leaving; Medicaid funding is running out; and if you add on to it a large number of Zika cases, the whole system is under severe stress,” Park said in an interview. “If these funds run out, Puerto Rico will have deep cuts to its Medicaid program — which many experts say would cause their health care system to head [toward] collapse.”

Advocates for Puerto Rico had been seeking close to $500 billion, and instead came away with $295 billion, according to a House aide involved in the negotiations. Still, getting 60 percent of their request will allow the island to avoid the “Medicaid cliff” — and that will have to do for now.

President Trump has appeared to criticize efforts to fix the problem, tweeting “NO!” at one point about congressional Democrats’ demands. His own party’s congressional leaders have been openly contradicting him, with Sen. Marco Rubio (R-FL) telling reporters last week that he viewed helping Puerto Rico as a priority for Congress.

Winner: the military

President Trump proposed dramatically slashing spending for almost all federal agencies. The major exception was the Defense Department, to which Trump wanted to give a $30 billion increase in funding. That eye-popping number would have come on top of the $22 billion in additional funding that the military is already set to receive under previous legislation.

Trump didn’t get the entirety of his ask. But the new budget steers an additional $12.5 billion to the Defense Department, with the possibility of an additional $2.5 billion on the condition that the White House presents a plan to Congress to defeat ISIS, according to a senior congressional aide.

About $9 billion is expected to fund combat operations, including expensive new aircraft and ammunition, according to the Military Times. A smaller pot of money will help fund new visas for Afghan interpreters, after the upcoming expiration of visas for those who helped the American military with translation forced prompted bipartisan outrage. $50 million will go to fight opioid addiction among veterans, and the budget also includes $18 million for “consulting services” to address a scandal engulfing the Marine Corps of female soldiers who were reportedly photographed in the nude without their consent.

"The additional defense funding will accelerate the campaign to defeat ISIS and support ongoing operations in Afghanistan and address critical budget shortfalls," the Senate Appropriations Committee wrote in its summary of the agreement.

Of course, America already spends far more money on its military than any other country — more, in fact, than half the rest of the rest of the world spends combined.

Winner: science!

Scientists across the country sounded the alarm after Trump released an “anti-science budget” that would have decimated the National Institutes of Health, halved the size of the Environmental Protection Agency, and entirely eradicated federal programs to study climate change.

But the final budget deal in Congress doesn’t just reverse the funding cuts. In fact, at least in some important instances, Congress is actually set to increase science spending from its existing baseline.

For instance, after Trump looked to dramatically cut the NIH’s budget, the federal agency is now set to get a $2 billion funding boost — including an extra $400 million to research Alzheimer’s and an additional $476 million for the National Cancer Institute, according to the Atlantic.

Then there’s the EPA, which will see a 1 percent decrease in funding — not nothing, but far better than many feared. Science runs down some of the other extensive funding boosts for science and medical research in congressional leaders’ budget plan:

Research on antibiotic resistance goes up $50 million. The brain-mapping initiative called Brain Research through Advancing Innovative Neurotechnologies, launched by former President Barack Obama, receives $120 million, including $10 million from the Cures act. Another $160 million in new funding goes to the Precision Medicine Initiative (including $40 million from Cures for its 1-million person cohort study). And $300 million from Cures tagged for the National Cancer Institute is expected to fund former Vice President Joe Biden’s moonshot initiative.

Vox’s Julia Belluz and Brian Resnick have an additional rundown on the good news for scientists in the latest budget negotiations.

Winner: Planned Parenthood

After details of the budget deal started to emerge late Sunday night, few observers were particularly surprised to learn that Republicans had failed to execute their long-held objective of defunding Planned Parenthood.

Republicans’ inability to cut federal funding for the program was already an essentially foregone conclusion. Speaker Paul Ryan declared weeks ago that the Planned Parenthood fight belonged in the debate over health care. Democratic negotiators made clear that they wouldn’t back any compromise that gutted Planned Parenthood. Though he has said he wanted to eliminate the organization’s funding, President Trump didn’t put cutting Planned Parenthood into his budget.

It’s worth taking a step back to appreciate just how significant it is that the idea was dead on arrival with Congress and the White House from the beginning.

Back in September 2015, after 12 “sting” videos emerged purporting to show researchers discussing how to procure fetal organs for research, conservatives were outraged. Republicans in Congress then approved votes to defund Planned Parenthood eight separate times. Pro-choice advocates were under siege. And when Republicans seized the government in November 2016, it seemed like a near certainty that Planned Parenthood would be one of the first items on the chopping block.

But Republicans again ran into the obstacle they’ve run into again and again since taking Congress: It’s hard to pass anything with no buy-in from the minority party. And support for Planned Parenthood has become a unifying rallying cry for Democratic lawmakers, who almost universally vowed to vote against any budget deal that did not protect federal Planned Parenthood funding.

Perhaps Republicans will find another vehicle to use to defund Planned Parenthood. But for now, pro-life groups are left flailing, helplessly, against the tide:

Susan B Anthony List: It is incredibly disappointing that any GOP spending bill would contain continued funding for Planned Parenthood — Chad Pergram (@ChadPergram) May 1, 2017

Loser: President Trump

It’s worth taking stock of just how far the agreement from is from what Trump initially demanded.

Trump wanted billions to build a wall on the Mexican border. He didn’t get a dime for it. He wanted staggering reductions to medical and scientific research. Democrats successfully won a $2 billion increase in funding for the NIH.

Trump proposed cutting the EPA’s budget by 31 percent. He wanted to gut the State Department with a 29 percent cut, and weaken the Labor Department by reducing its budget by 21 percent. All three of the agencies will keep essentially their entire funding streams.

Democrats on the Hill say they were able to use their leverage — the ability to force a shutdown that would have been pinned on Republicans — to get what they wanted out of the deal.

"This budget agreement appears to bolster the main lesson Democrats should take from Trump's first 100 days: There is no downside to strongly fighting Trump with backbone,” said Adam Green, co-founder of the Progressive Campaign Committee.

And it is true that Democrats’ negotiating position allowed them to wring concessions from across the aisle. But it also appears to be the case that Republican leadership does not particularly care what its leader in the White House is demanding — or, at the least, is willing to buck those demands in the face of a tough budget negotiation.

Loser: the wall

In March, the White House requested roughly $1.5 billion to be tacked on to the Department of Homeland Security appropriation bill to be used for Trump’s proposed border wall.

That didn’t happen. Trump’s border wall received no funding at all in the 2017 budget, thanks to congressional Democrats standing firm against it.

Blocking wall funding in this bill is a big win for Democrats; the wall was one of Trump’s most central campaign promises and one of the few immigration fights he has to take up on Capitol Hill. But from the outset, Democrats made it clear that any attempt to fund the border wall would be met with uniform Democratic opposition — which would lead to a government shutdown.

And Republican legislators, desperate to avoid shutdown, were apparently willing to drop it — an early indication that Trump’s major campaign promise isn’t the top priority in Congress. Instead, Republicans negotiated other border security funding, to invest in technology, improve existing infrastructure, and fund detention and removal programs through Immigration and Customs Enforcement and Customs and Border Patrol. That way Republicans could still declare some wins on national security.

But for Trump, a win on pretty standard immigration enforcement spending is a harder sell than declaring victory on funding for his big, beautiful wall. For a moment in the final weeks of negotiations, it appeared the White House was going to play the tough guy with the wall.

When members of Congress returned to their districts in early April, the administration took a harder line on the shutdown deadline, saying funding for the wall was a “must.” Trump tweeted that Obamacare is in “serious trouble.” The president was seemingly hinting at a deal that Office of Management and Budget Director Mick Mulvaney suggested: For every dollar Republicans put toward Obamacare subsidies, Democrats would agree to a dollar for the border wall.

That deal went nowhere, and Trump backed down, saying wall funding could wait until the next round of negotiations in September. But at the end of the day, the politics of the wall remain the same in September, and it’s not likely Democrats will back down.

For now, Trump has just taken to Twitter to complain about Democrats obstructing his border wall dreams.

Loser: Paul Ryan’s small-government dreams

House Speaker Paul Ryan has spent more than a decade talking about the need to reduce the size of America’s federal government.

“We believe a renewed commitment to limited government will unshackle our economy and create millions of new jobs,” he said in 2011. More recently, Ryan has turned to similar rhetoric about “limited government” to try to sell his Obamacare repeal bill.

But even with unified Republican control of Congress and a Republican in the White House, Ryan isn’t just failing to shrink the deficit — he’s going to expand it.

The budget analysts at the Center on Budget and Policy Priorities are still crunching the numbers to figure out exactly what the new deal does to the deficit. But whatever the final number is, the final budget will almost certainly increase the deficit by adding almost $5 billion in non-defense spending and the additional $12 billion for the military.