NEW YORK (AP) — A man who has been arrested 30 times for impersonating a transit worker, stealing buses and trains and driving their routes has taken a plea deal that's sending him to a mental health facility, not prison, for his latest escapade.

Darius McCollum had been charged with criminal impersonation and grand larceny in his most recent arrest, a 2015 case in which he was caught behind the wheel of a Greyhound bus.

On Monday, he said he was not criminally responsible by reason of mental disease or defect. He will be evaluated by psychiatrists, who will determine whether he is dangerously mentally ill, mentally ill or not mentally ill. If he is deemed dangerous, he will be confined in a secure facility for at least six months. If not, he could be sent to a clinic, where he would be able to see his mother.

"I commandeered a bus," McCollum said in court, admitting he posed as a U.S. Department of Homeland Security officer twice — both times the Greyhound workers believed him.

McCollum, 52, has been diagnosed with an autism spectrum disorder, which often includes repetitive behaviors and a difficulty with impulse control. He is obsessed with buses and trains. He befriended engineers and pilots and first started hanging around the subway system as a child.

He has memorized every subway line and every stop and can recite them on request. He knows mechanical details about how the subway trains and buses work, and he often knows how to fix problems.

McCollum often would dress up as a transit worker just to be around trains. He wanted to work for the Metropolitan Transportation Authority, but transit officials have long said they would not hire someone who had stolen a train, as he did at age 15 from Penn Station to the World Trade Center.

Doctors who evaluated McCollum in his most recent case found he lacked the ability to understand the problem with his behavior.

"The plea is in the best interest of justice, your honor," Assistant District Attorney Christopher Myco said.

Despite McCollum's many convictions over the years, he'd never been sent to a mental health facility for treatment. His lawyer Sally Butler said this will be his first opportunity to really get help.

"This will keep him out of the criminal system for the rest of his life," she said, adding he wrote her a note after the plea that said: "They finally got it right."

McCollum's capers have been the stuff of newspapers and magazines for decades. A documentary about his life, "Off the Rails," was released in 2016 to positive reviews.

A feature film, tentatively titled "Train Man," was sold to a financer but is in limbo. Julia Roberts was attached to star as Butler, who has been McCollum's attorney since his last guilty plea after a 2010 arrest for stealing a Trailways bus.

Butler also is something of a caretaker for McCollum, who has only his 91-year-old mother.

More From WIBX 950