Major Thomas Weir was a preacher and captain of the town guard, a pillar of the community whose life ended in scandal - as an unrepentant sorcerer who was burned at the stake.

Ian Rankin, creator of Inspector Rebus, believes Major Weir could also be the real Dr Jekyll, principal character in one of Robert Louis Stevenson's most famous novels.

Rankin believes the tale of the duplicitous Weir, who was executed with his sister for making a pact with the devil, was one of the prime inspirations for The Strange Case of Dr Jekyll and Mr Hyde, after it was told to him as a child.

A BBC documentary, presented by Rankin, says the young Stevenson was horrified by tales of one of the notorious figures of the 17th century. Weir shocked Edinburgh society when, at 70, he revealed he had for decades practised incest, bestiality and sorcery.

Together with his sister, Jean, he was sentenced to be strangled and burned at the stake.

Stevenson's nanny, known as Cummy, used to read the Bible and old Covenanter tales to the child. Rankin believes the tale of the double life of Major Weir led Stevenson to conjure his own Dr Jekyll, the Edinburgh doctor who transformed into the murderous Mr Hyde.

Weir, from Carluke in South Lanarkshire, was an officer in the Covenanting army of James Graham, the Marquis of Montrose, and was respected for his powerful preaching - until he confessed to witchcraft.

Rankin said: "Stevenson had always suffered from nightmares.

"What made Cummy's bedtime stories so terrifying was they really happened - just outside his bedroom window on the haunted streets of Edinburgh."

As Covenanters, Thomas and Jean "made a great show of piety and godliness and excelled at prayer".

"At their interrogation," Rankin explained, "Jean sported the Devil's mark in the shape of a horseshoe on her forehead. They told the horrified Lord Provost they had met the Devil and made a pact with him 20 years previously."

Rankin, in the documentary to be shown on Saturday, also considers other inspirations for Dr Jekyll, including the graverobbers Burke and Hare, and cabinet maker and thief Deacon Brodie.

Rankin says his own creation, Inspector Rebus, is his own kind of Dr Jekyll: "He is allowed to have adventures which are closed to me. He can transgress, break taboos, be the maverick I never was and never will be.

"I owe a great debt to Robert Louis Stevenson. Without Jekyll and Hyde, I might never have come up with my own alter ego - Detective John Rebus."

Ian Rankin Investigates Dr Jekyll and Mr Hyde is on BBC4 on Saturday at 9.55pm.