FRANKLIN (Somerset) — An on-duty township police officer was behind the wheel of his police vehicle when he shot up heroin and nearly died from an overdose, prosecutors said Friday.

Matthew D. Ellery, 29, a resident of Middlesex Borough, has lost his job with the Franklin Township police department after admitting that he drove under the influence and was in possession of heroin.

As part of his plea deal, Ellery will avoid jail or prison by applying to the Drug Court program. He will have to remain clean for five years or else face a five-year prison sentence for the third-degree drug charge. He is scheduled to be sentenced in Superior Court in Somerville on Aug. 23.

The overdose happened months ago but officials kept it secret, announcing the guilty plea on Friday. Last month, NJ.com reported that he had been charged with DWI but officials declined to provide further information until now.

The investigation of the April overdose coincides with the abrupt resignations on June 30 of Police Chief Richard Grammar and Capt. Gregory Borlan. Grammar left his post just a year and six months after he was appointed to it. The Somerset County Prosecutor's Office took over the department, a move that happens when prosecutors have lost confidence in a department's ability to govern itself. Like the overdose, authorities are keeping the reasons for the resignations and takeover secret from the public.

Prosecutors said a fellow officer discovered Ellery about 1:08 a.m. April 7 after the department had been unable to reach him over police radio.

Police were dispatched to his last known location and found him passed out in his vehicle parked at a business address on Bennetts Lane.

The responding officer was also an emergency medical technician and could tell that Ellery was blue in the face, wasn't breathing and had no pulse.

Ellery was revived with two doses of Narcan, the opioid antidote that many police officers now carry.

As part of the plea deal, his driver's license will be suspended for seven months. He will not be allowed to work for the township police department but the prosecutor's announcement did not say that he would be banned from any other public or police employment in the state.

Sergio Bichao is deputy digital editor at New Jersey 101.5. Send him news tips: Call 609-359-5348 or email sergio.bichao@townsquaremedia.com.