WASHINGTON -- For John McCain, a lifetime of courage, contradictions and contrarianism came down to one vote, in the middle of the night, in the twilight of his career.

The fate of U.S. President Donald Trump's long effort to repeal Barack Obama's health care law hung in the balance as a Senate roll call dragged on past 1 a.m. on a July night in 2017.

Then came McCain -- 80 years old, recently diagnosed with brain cancer, his face still scarred from surgery, striding with purpose toward the well of the Senate.

The Arizona Republican raised his right arm, paused for dramatic effect and flashed a determined thumbs-down, drawing gasps from both sides of the aisle.

Trump's health care bill was dead. McCain's lifelong reputation as free thinker, never to be intimidated, was very much alive.

It was the capstone of a political career that had taken McCain from the House to the Senate to the Republican presidential nomination, but never to his ultimate goal, the White House.

McCain, who faced down his captors in a Vietnamese prison of war camp and later turned his trademark defiance into a political asset, died Saturday. He was 81.

With his irascible grin and fighter-pilot moxie, McCain won election to the House from Arizona twice and the Senate six times. But twice he was thwarted in his quest for the presidency. His upstart bid for president in 2000 took flight in New Hampshire only to be quickly flattened in South Carolina.

Eight years later, he fought back from the brink of defeat to win the GOP nomination, only to be overpowered by Democrat Obama in the general election. McCain had chosen a little-known Alaska governor as his running mate for that race, and in the process helped turn Sarah Palin into a political celebrity.

After losing to Obama in an electoral landslide, McCain returned to the Senate determined not to be defined by a failed presidential campaign in which his reputation as a maverick had faded. In the politics of the moment and in national political debate over the decades, McCain energetically advanced his ideas and punched back hard at critics -- Trump not least among them.

Scion of a decorated military family, McCain embraced his role as chairman of the Senate Armed Services Committee, pushing for aggressive U.S. military intervention overseas and eager to contribute to "defeating the forces of radical Islam that want to destroy America."

Asked how he wanted to be remembered, McCain said simply: "That I made a major contribution to the defence of the nation."

Taking a long look back in his valedictory memoir, "The Restless Wave," McCain wrote of the world he inhabited: "I hate to leave it. But I don't have a complaint. Not one. It's been quite a ride. I've known great passions, seen amazing wonders, fought in a war, and helped make a peace. ... I made a small place for myself in the story of America and the history of my times."

Throughout his decades in Congress, McCain played his role with trademark verve, at one hearing dismissing a protester by calling out, "Get out of here, you low-life scum."

McCain stuck by the party's 2016 presidential nominee, Trump, at times seemingly through gritted teeth -- until the release a month before the election of a lewd audio in which Trump said he could kiss and grab women. Declaring that the breaking point, McCain withdrew his support and said he would write in "some good conservative Republican who's qualified to be president."

He had largely held his tongue earlier in the campaign when Trump questioned McCain's status as a war hero by saying: "He was a war hero because he was captured. I like people who weren't captured."

McCain, with unusual restraint, said that was offensive to veterans, but "the best thing to do is put it behind us and move forward."

But by the time McCain cast his vote against the GOP health bill, six months into Trump's presidency, the two men were openly at odds. Trump railed against McCain publicly over the vote, and McCain remarked that he no longer listened to what Trump had to say because "there's no point in it."

Unafraid of contradictions, McCain himself had campaigned against Obama's health care law, but voted against its repeal because Republicans had flouted what he called the "old way of legislating," with full-fledged debate, amendments and committee hearings on the final bill.

In his final months, McCain did not go quietly, frequently jabbing at Trump and his policies from the remove of his Hidden Valley family retreat in Arizona. He opposed the president's nominee for CIA director because of her past role in overseeing torture, scolded Trump for alienating U.S. allies at an international summit, labeled the administration's zero-tolerance immigration policy "an affront to the decency of the American people" and denounced the Trump-Vladimir Putin summit in Helsinki as a "tragic mistake" in which Trump put on "one of the most disgraceful performances by an American president in memory."

On Aug. 13, Trump signed into law a $716 billion defence policy bill named in honour of the senator. Trump signed the John S. McCain National Defence Authorization Act in a ceremony at a military base in New York -- without one mention of McCain.

Over a 31-year career in the Senate, McCain became a standard-bearer for reforming campaign donations. He railed against pork-barrel spending for legislators' pet projects and cultivated a reputation as a deficit hawk and an independent voice. He even attacked senators' own perks of office, such as free, up-close parking spots at Washington airports.

But faced with a tough GOP challenge for his Senate seat in 2010, McCain disowned chapters in his past and turned to the right on a number of hot-button issues, including gays in the military, immigration and climate change.

When the Supreme Court in 2010 overturned the campaign finance restrictions that he had worked so hard to enact, McCain said he was disappointed, but he seemed resigned to their demise.

"I don't think there's much that can be done, to tell you the truth," he said. "It is what it is."

After surviving the 2010 election, McCain wasn't about to roll over on any number of other issues. During a long and heated 2011 debate in Congress over the federal debt, McCain dismissed conservatives' arguments against raising the government's borrowing limit as "bizarro" and foolish. In a 2014 hearing, he lit into Secretary of State John Kerry for "talking strongly and carrying a very small stick -- in fact, a twig" on foreign policy.

Obama's vice-president, Joe Biden, offered his own summation for a senator whom he described as "quixotic."

"I think John's legacy is that he never quits," Biden said in a 2015 interview.

Over a lifetime in politics, McCain's anti-authoritarian streak was both his greatest asset and Achilles' heel.

Often disinclined to follow the herd, McCain achieved his biggest legislative successes when making alliances with Democrats. He also piled up a full repertoire of over-the-top wisecracks, and had enough flare-ups with colleagues to cement a reputation as a hothead. Some questioned whether he had the right temperament to be president.

McCain's challenge always was to strike the right balance, offering himself both as a rabble-rouser and a reliable Republican standard-bearer.

John Sidney McCain III's history as a Vietnam POW for 5 1/2 years after being shot out of the sky at age 31 was a powerful part of his back story as the son and grandson of four-star admirals.

When his Vietnamese captors offered him early release as a propaganda ploy, McCain refused to play along.

"Now it will be very bad for you, Mac Kane," they told him, and they were true to their word.

McCain returned home from his years as a POW on crutches and unable to lift his arms. Never again could he raise them above his head.

He once said he'd "never known a prisoner of war who felt he could fully explain the experience to anyone who had not shared it."

Indeed, he seemed more at ease joking about his incarceration than analyzing it.

More than once he quipped after a distasteful experience: "That's the most fun I've had since my last interrogation."

In his darkest hour in Vietnam, McCain's will was broken and he signed a confession that said, "I am a black criminal and I have performed deeds of an air pirate."

For all of that, though, McCain defied his guards. To his captors, just as to his superiors back at the U.S. Naval Academy in Annapolis, Maryland, he was exasperating.

"He had to carry a different burden than most of us and he handled it beautifully," Orson Swindle, a former POW cellmate, once said. "He didn't need any coping mechanism; that's just built into him."

Even in prison, McCain played to the bleachers, shouting obscenities at his captors loudly enough to bolster the spirits of fellow captives. Appointed by the POWs to act as camp "entertainment officer," a "room chaplain" and a "communications officer," McCain imparted comic relief, literary tutorials, news of the day, even religious sustenance.

Bud Day, a former cellmate and Medal of Honor recipient, said McCain's POW experience "took some great iron and turned him into steel."

McCain once said that Vietnam "wasn't a turning point in me as to what type of person I am, but it was a bit of a turning point in me appreciating the value of serving a cause greater than your self-interest."

It taught him, he said, "that if you put your country first, that everything will be OK."

Still, a predilection for what McCain described as "quick tempers, adventurous spirits, and love for the country's uniform" was encoded in the family DNA.

His father and grandfather, the Navy's first father-and-son set of four-star admirals, had set such a low standard for behaviour at the Naval Academy that John Sidney McCain III's self-described "four-year course of insubordination and rebellion" got little more than a yawn from his family.

Speaking of his father, McCain once pronounced himself "little short of astonished by the old man's reckless disregard for the rules."

And yet for all the raucous tales of misconduct, the midshipmen of the McCain family abided by the school's honour code not to lie, cheat or steal.

McCain's Vietnam experience gave him new confidence in himself and his judgment. But it did not tame his wild side, and his first marriage was a casualty. McCain blamed the failure of the marriage on "my own selfishness and immaturity" and has called it "my greatest moral failing."

One month after divorcing his first wife, Carol, McCain married Cindy Hensley, 17 years his junior.

McCain's war story made him a celebrity in Washington. When he became the Navy's liaison to the Senate, he quickly established friendships with some of the younger senators, who would stop by his office, put their feet up, and chew over the events of the day. The experience opened McCain's eyes to the impact that politicians could have, and to the notion that he could be one of them.

His marriage to Cindy, the daughter of a wealthy beer distributor in Arizona, helped clear the path forward. In one day, McCain signed his Navy discharge papers and flew west with his new wife to his new life. By 1982, he'd been elected to the House and four years later to an open Senate seat. He and Cindy had four children, to add to the three from his first marriage. Their youngest child was adopted from Mother Teresa's orphanage in Bangladesh.

McCain set about establishing a conservative voting record and a reputation as a tightwad with taxpayer dollars. But just months into his Senate career, he made what he called "the worst mistake of his life." He participated in two meetings with banking regulators on behalf of Charles Keating, a friend, campaign contributor, constituent and savings and loan financier who was later convicted of securities fraud.

The S&L situation simmered for a few years, but eventually boiled over, and McCain got burned.

As the industry collapsed, McCain was tagged as one of the Keating Five -- five senators who, to varying degrees, were accused of trying to get regulators to ease up on Keating. McCain was cited for lesser involvement than the others by the Senate ethics committee, which faulted his "poor judgment."

But to have his honour questioned, he said, was in some ways worse than the torture he endured in Vietnam. He spent years trying to live down the taint.

Another move McCain would eventually say he regretted came earlier in his career as a lawmaker when in 1983 he voted against establishing Martin Luther King Jr. Day as a federal holiday. In doing so he followed the political tradition of Arizona, which was the last state to recognize the holiday for the slain civil rights leader.

In the 1990s, McCain shouldered another wrenching issue, the long effort to account for American soldiers still missing from the war and to normalize relations with Vietnam.

"People don't remember how ugly the POW-MIA issue was," former Democratic Sen. Bob Kerrey, a fellow Vietnam veteran, later recalled, crediting McCain for standing up to significant opposition. "I heard people scream in his face, holding him responsible for the deaths of POWs."

Few politicians matched McCain's success as an author. His 1999 release "Faith Of My Fathers" was a million-seller that was highly praised and helped launch his run for president in 2000. His most recent bestseller and planned farewell, "The Restless Wave," came out in May 2018.

My heart is broken. I am so lucky to have lived the adventure of loving this incredible man for 38 years. He passed the way he lived, on his own terms, surrounded by the people he loved, in the the place he loved best. — Cindy McCain (@cindymccain) August 26, 2018

My deepest sympathies and respect go out to the family of Senator John McCain. Our hearts and prayers are with you! — Donald J. Trump (@realDonaldTrump) August 26, 2018

A man who served his country up until his last days...a true patriot and American hero. RIP, John Sidney McCain III. #selflessness #service #hero #FlyNavy pic.twitter.com/rLjFgXnv9x — flynavy (@flynavy) August 26, 2018

Words cannot express the sorrow I feel at John McCain’s passing. The world has lost a hero and a statesman. Cindy and the McCain family have lost a loving husband and father. I have lost a wonderful friend. — Jeff Flake (@JeffFlake) August 26, 2018

John McCain was my friend. I will remember the good times. My family and I send prayers for Cindy and the McCain family.

- Sarah Palin and family pic.twitter.com/KRvcIQ99cA — Sarah Palin (@SarahPalinUSA) August 26, 2018

I will need some time to absorb this, but I want Cindy —and the entire McCain family — to know they are in my prayers. — Lindsey Graham (@LindseyGrahamSC) August 26, 2018

Our hearts are with John’s wife, Cindy, his children, and his grandchildren. This Congress, this country mourn with them. — Paul Ryan (@SpeakerRyan) August 26, 2018

Karen and I are praying for Senator John McCain, Cindy and their family this weekend. May God bless them all during this difficult time. — Vice President Mike Pence (@VP) August 25, 2018

Tonight we say goodbye to a true hero. A man who never sought accolades. A patriot who fought everyday for American freedom and dignity. A warrior of strength, a patriot of heart, and a man of conviction. There will never be another John McCain. May he rest in peace. pic.twitter.com/B3FjQnDToH — Nikki Haley (@nikkihaley) August 26, 2018

Senator John McCain was an American patriot and hero whose sacrifices for his country, and lifetime of public service, were an inspiration to millions. Canadians join Americans tonight in celebrating his life and mourning his passing. — Justin Trudeau (@JustinTrudeau) August 26, 2018

STATEMENT BY FORMER U.S. PRESIDENT JIMMY CARTER ON THE PASSING OF SENATOR JOHN MCCAIN pic.twitter.com/dcuUIJp8tK — The Carter Center (@CarterCenter) August 26, 2018

Our statement on the passing of Senator John McCain: pic.twitter.com/3GBjNYxoj5 — Barack Obama (@BarackObama) August 26, 2018

John McCain believed that every citizen has a responsibility to make something of the freedoms given by our Constitution, and from his heroic service in the Navy to his 35 years in Congress, he lived by his creed every day. https://t.co/946T7PnG53 — Bill Clinton (@BillClinton) August 26, 2018