Seven minutes into the first presidential debate, the mood turned grim inside the room at the University of Denver where staff members for President Obama were following the encounter.

Aides monitoring focus groups watched as enthusiasm for Mitt Romney spiked. "We are getting bombed on Twitter," Stephanie Cutter, a deputy campaign manager, said while tracking the postings by analysts and journalists whom the campaign viewed as critical in setting perceptions.

By the time Obama had waded through a convoluted answer about health care -- "He's not mentioning voucher-care?" someone called out -- a pall had fallen over the room. When the president closed by declaring, "this was a terrific debate," his re-election team grimaced. There was the obligatory huddle to discuss how to explain his performance to the nation, and then a moment of paralysis: No one wanted to go to the spin room and speak with reporters.

Romney's advisers monitoring the debate flashed giddy smiles as their focus groups showed the same results.

"Boy, the president is off tonight," said Stuart Stevens, the senior Romney strategist, sounding mystified, according to aides in the room. Russ Schriefer, a senior adviser, immediately began planning TV spots based entirely on clips from the debate.

The Oct. 3 debate sharply exposed Obama's vulnerabilities and forced the president and his advisers to work to reclaim the campaign over a grueling 30 days, ending with his triumph Tuesday. After a summer of growing confidence, Obama suddenly confronted the possibility of a loss that would diminish his legacy and threaten his signature achievement, the health care law. He emerged newly combative, newly contrite and newly willing to recognize how his disdain for Romney had blinded him to his opponent's strengths.

After watching a videotape of his debate performance, Obama began calling panicked supporters to reassure them he would do better. "This is on me," the president said, again and again.

Obama, who had dismissed warnings about being caught off guard in the debate, told his advisers that he would now accept and deploy the pre-written attack lines that he had sniffed at earlier. "If I give up a couple of points of likability and come across as snarky, so be it," Obama told his staff.

As his campaign began an all-out assault on Romney's credibility and conservative views, the president soon was denouncing Romney's budget proposals as a "sketchy deal" and charging that the GOP nominee was not telling Americans the truth.

Obama recognized that to a certain extent, he had walked into a trap that Romney's advisers had anticipated: His antipathy toward Romney -- which advisers described as deeper than what Obama had felt for John McCain in 2008 -- led the president to underestimate his opponent as he began moving to the center before the debate audience of millions of TV viewers.

But as concerned as the White House was during the last 30 days of the campaign, its polls never showed Obama slipping behind Romney, aides said. The president was helped in no small part by the tremendous amount of money the campaign built up, which had permitted him to pound his rival before he had ever had a chance to fully introduce himself to the nation.

That was just one of several ways that Obama's campaign operations, some unnoticed by Romney's aides in Boston, helped save the president's candidacy. In Chicago, the campaign recruited a team of behavioral scientists to build an extraordinarily sophisticated database packed with names of millions of undecided voters. The ever-expanding list let the campaign find and register new voters who fit the demographic pattern of Obama backers and methodically track their views through thousands of telephone calls every night.

That allowed the Obama campaign not only to alter the very nature of the electorate, making it younger and less white, but also to create a portrait of shifting voter allegiances. The power of this operation stunned Romney's aides on election night, as they saw voters they never even knew existed turn out in places like Osceola County, Fla. "It's one thing to say you are going to do it: It's another thing to actually get out there and do it," said Brian Jones, a senior adviser.

In the last days of the campaign, Romney cast himself as the candidate that he may have wanted to be all along: Moderate in tone, an agent of change who promised bipartisan cooperation, sounding very much like Obama in 2008. But he could never overcome the harm that Obama's ads had done over the summer or the weight of the ideological baggage he carried from the primary. On Tuesday night, a crestfallen Romney and his family watched as the television networks showed him losing all but one battleground state.

By the end of the 30 days, after Air Force One carried Obama on an almost round-the-clock series of rallies, the president had reverted back to the agent of change battling the forces of the status quo, drawing contrasts between himself and Romney with an urgency that had been absent. Obama had returned, if not as the candidate that he was in 2008, as a man hungry for four more years to pursue his agenda in the White House.

As the summer came to a close, Romney's campaign was stuck in a debate over how to rescue his candidacy. Obama's attack on Romney's role at Bain Capital, the private equity firm he founded, was in full swing, the Democratic convention had been an unequivocal boost for the president, and a videotape had surfaced that caught Romney at a private fundraiser saying that 47 percent of the nation did not pay taxes, which reinforced Democrats' efforts to portray him as an elitist.

"We had struggled pretty dramatically in September," said Neil Newhouse, Romney's pollster. "The 47 percent remark came out, and that was on top of the bounce that Obama got from his convention, so needless to say September was not our best month. It showed in our data. It was grim."

There was, advisers decided, one last opportunity on the horizon: the presidential debate in Denver. Stevens argued that Obama's dislike of Romney would lead the president to underestimate him.

In August, Romney began testing one-liners on friends flying with him on his campaign plane. On issue after issue, Romney led discussions on how to frame his answers, to move away from the conservative tone of his primary contests in front of the largest audience he would have as a candidate.

Sen. Rob Portman of Ohio was recruited to play Obama, and he embraced the role, even anticipating how the president would open his first debate, which fell on his wedding anniversary. "I've got to tell you, tonight's a really special night," said Portman, playing Obama. "I see my sweetie out there."

Romney's advisers broke out in laughter when the real Obama opened with a similar line, and nodded approvingly when a very prepared Romney countered with a gracious response that even Democrats said put Obama off balance. Nothing had been left to chance: Romney put on full makeup and did his final practice in a room set up to replicate, down to the lighting and temperature, the hall where he would meet Obama.

Democrats advising Obama saw the same peril for the president that Romney's aides did. Ronald Klain, a Democratic strategist who has overseen debate preparation for candidates for nearly 20 years, warned Obama at his very first debate session, in mid-July, that incumbents almost invariably lose their first debate. "It's easier for a candidate to schedule the time to prepare; it's easy for the challenger to get away; the president has competing needs," Klain told Obama, according to aides who witnessed the exchange.

Ken Mehlman, who had managed Bush's campaign in 2004, ran into one of Obama's advisers, and warned him that presidents are not used to being challenged, and unlike candidates, are out of practice at verbal jousting. Romney had gone through 20 debates over the past year.

Obama showed no interest in watching the Republican debates. But his aides studied them, and concluded that Romney was a powerful debater, hard to intimidate and fast to throw out assertions that would later prove wrong or exaggerated. At one debate, Texas Gov. Rick Perry criticized Romney for having praised Education Secretary Arne Duncan days earlier. Romney flatly denied it, leaving Perry speechless.

At the White House, Obama's communications director, Dan Pfeiffer, took note of that moment, intending to mention it to Obama. He would later fault himself for failing to understand "the magnitude of the challenge" Romney's debate style presented.

Obama displayed little concern during several days of preparation in September. Klain and David Axelrod, a senior strategist, told Obama that he seemed distracted, but he shrugged them off. "I'll be there on game day," he said. "I'm a game-day player."

Shortly after the debate began, Obama's aides realized they had made their own mistakes in advising Obama to avoid combative exchanges that might sacrifice the goodwill many Americans felt toward him. In 90 minutes, Obama crystallized what had been gnawing concerns among many Americans about the president. He came across, as Obama's advisers told him later, as professorial, arrogant, entitled and detached from the turmoil tearing the nation. He appeared to be disdainful not only of his opponent but of the political process itself. Obama showed no passion for the job, and allowed Romney to explode the characterization of him as a wealthy job-destroying venture capitalist that the Obama campaign had spent months creating.

The voter-analysis database in Chicago noted a precipitous drop in perceptions of Obama among independents, starting that night and lasting for four days, long before the public polls picked it up. Voters who had begun turning to Obama were newly willing to give Romney another look.

What was arguably the most dismal night of Obama's political career could hardly have come at a worse time: Early voting was underway.

After the debate, Obama called Axelrod. He had read the early reviews on his iPad. "I guess the consensus is that we didn't have a very good night," Obama told Axelrod.

"That is the consensus," Axelrod said.

For the next 30 days, Romney and his advisers tried to capitalize on Obama's mistakes. And Romney continued his drift toward the center, softening his language on abortion and immigration from the positions that had defined him during the Republican primary. It was something that the White House had expected he would do in the summer. Perhaps most important, the debate gave him a swagger, confidence and presidential bearing that had been absent.

Romney soon recognized the scope of his accomplishment. He flew from Denver to Virginia for a rally the next day, and as the motorcade headed toward the event, there was so much traffic that Romney and his top advisers thought there must have been an accident. In fact, the roads were jammed with people on their way to see him.

It was clear that Hurricane Sandy was going to upend Obama's final week of campaigning, but aides were determined to squeeze in one more visit to Florida. It almost became a calamity.

To get ahead of the storm, the president flew to Orlando on Oct. 28, the evening before a morning event. But overnight, the storm intensified. Well before dawn, the Air Force One crew told the president's advisers that if he was going to beat the storm back to Washington, he had to leave at once. His aides blanched at the image of Obama stuck in sunny Florida as the storm roared up the Eastern Seaboard.

The White House announced the change of plans at 6:45 a.m. The president returned to the White House at 11:07 a.m. and went directly into the Situation Room, canceling his political events. The decision was costly to a campaign so dependent on organization: Obama used his rallies to collect supporters' telephone numbers and e-mail addresses.

Once the storm hit, it was more of a problem for Romney. It put him in the position of struggling to explain the skepticism he had expressed during the Republican primary about a federal role in disaster relief. Even worse, it pushed him off the stage.

Romney's aides broke out in a chorus of groans as they watched on TV as Gov. Chris Christie of New Jersey offered effusive praise of the president's handling of the storm. They viewed it as an act of disloyalty from a man whom they had expected to deploy that very weekend on Romney's behalf. The praise of Obama from a GOP governor and Romney surrogate came at the same time Romney had been portraying Obama as partisan and polarizing.

The same week, Obama's campaign released an ad in which another Republican, Colin Powell, endorsed Obama. The ad, aides said, produced a spike of support from independents.

Romney was finding Ohio, a state central to his victory, a stubborn target, as Obama benefited from the auto industry rescue he championed and that Romney had opposed. The Romney campaign sought to undermine Obama with an ad misleadingly implying that Jeep was moving jobs from Ohio to China. By every measure, the ad backfired, drawing attacks by leaders of auto companies that employed many of the blue-collar voters that Romney was trying to reach.

The futility of that effort was apparent outside the Jeep assembly plant in Toledo, which had just had a $500 million renovation for production of a new line of vehicles, a project requiring 1,100 new workers.

"Everyone here knows someone who works at Jeep," said Jim Wessel, a supply representative. He said no one would believe the ad. Speaking of Obama's efforts to rescue the auto industry, he said, "I can just tell you I'm glad he did it."

Romney was running out of states. He made an impulsive run on Pennsylvania. The candidate had spent little time or money there before roaring in during the campaign's final hours.

On the last weekend, Romney scheduled a rally in Bucks County. Supporters began arriving at 2 p.m. But Romney's plane was delayed, and as the hours rolled on -- and the temperatures dropped -- dozens of people were blocked by the Secret Service as they sought to leave. Romney arrived to a scene of angry, cold supporters.

That Tuesday, Romney lost the state by 5 percentage points and watched Obama hold a 50,000-vote lead in Florida -- a state that he had once been confident of winning.