William Ayres, 79, faced life in prison after being charged four years ago with nine counts of performing lewd acts on seven boys during counseling sessions between 1991 and 1996.

The former president of the American Academy of Child and Adolescent Psychiatry also was accused of molesting more than 30 other victims on dates that are beyond the statute of limitations.

As the legal proceedings against Ayres dragged on for four years and two trials, his mental health declined. On Monday, prosecutors reluctantly conceded that he suffers dementia and is not competent to stand trial.

The failure to bring the case back to trial is a blow for prosecutors, who said the evidence against Ayres was overwhelming. Ayres admitted to performing physical exams in which the boys were naked from the waist down, but testified that nothing inappropriate happened.

Prosecutors were close to securing a conviction against Ayres in his 2009 trial, when 11 of the 12 jurors were in favor of conviction on four of the nine counts.

“We were within one juror’s vote,” San Mateo County District Attorney Steve Wagstaffe said Monday. “He would have been well into serving his prison sentence for the rest of his life.”

After the 2009 trial ended in a hung jury, prosecuting attorney Melissa McKowan said she felt “terrible for the victims.” She said she would retry the case.

But McKowan’s bid for a retrial was delayed after Ayres’ attorney said his client showed signs of dementia. That led to a trial to determine whether Ayres is mentally fit to stand trial, which ended in mistrial. Jurors deadlocked 8-4, with the majority saying he was incompetent.

At the time, prosecutors had argued that memory loss did not necessarily mean he could not participate in his own defense. They said he could testify at his own speed and keep a personal record to remind himself of what occurred during proceedings.

Wagstaffe said there was no other way around Ayres going to a mental hospital instead of prison. Every doctor evaluating Ayres testified that he suffered dementia, Wagstaffe said.

When Ayres next appears in court Sept. 7, a judge will determine which hospital Ayres will be living in.

Wagstaffe said he will recommend Ayres be sent to Napa State Hospital, a secured facility where he will be banned from interacting with the public.

Putting him in any less secure of a facility would “not accord with the level of seriousness of the charges,” the district attorney said.