Martin Scorsese has been teetering on the edge of irrelevance for a decade now. With the plodding “Gangs of New York” and the uneven, episodic “The Aviator,” the director who made some of the finest fever dreams of the 1970’s (Taxi Driver), 1980’s (Raging Bull) and 1990’s (Goodfellas), was relegated to making bloodless, historical duds with stories that were well researched, but not well told. Some wondered if the man who was playing himself in American Express commercials and Saturday Night Live skits had lost his nerve. There were even whispered comparisons to Francis Ford Coppola’s late career crash.

Well, Scorsese’s not ready to buy a winery just yet. With “The Departed,” he has made his most vital, entertaining film since “Goodfellas” and easily one of the year’s best. Based on the excellent, if unfortunately titled, Japanese thriller, “Infernal Affairs,” the story concerns two moles on opposite sides of the law, one an undercover cop in the mob, the other a gangster who’s infiltrated the police.

Leonardo DiCaprio plays William Costigan, the undercover cop. Costigan’s target is Irish crime boss Frank Costello (Jack Nicholson), an old fashioned street tactician and veritable Boston institution. (To avoid confusion between the names Costigan and Costello, I will refer to the police office Costigan by his first name William for the remainder of this review.) Referred to by the police as a “rock star,” Costello’s credo is “if you want something, you gotta take it.” And, in his blood-shot eyes and feral smile, you see every drug, every dime and every woman he’s ever taken, along with the numbness and detachment that has resulted from their consumption. Costello only seems to come alive when he sees terror in the eyes of an enemy or an errant underling.

William can only ingratiate himself to Costello and his henchmen through acts of terrible brutality and deceit. As his sins pile up ever higher, William becomes consumed with guilt and paranoia, only holding himself together with a mixture of prescription pain killers and anti-anxiety meds. And there appears to be no end in sight. Costello is always one step ahead of William and the police, extending William’s tortuous assignment by months and then years.

Colin Sullivan (Matt Damon) plays the mole who’s giving Costello his competitive edge over the police. Played with sociopathic verve, Damon’s Sullivan glad hands his way up the ranks of the Massachusetts State Police. Beloved by his fellow cops even as he betrays them, Sullivan, unlike William, experiences no angst over the daily barrage of lies that life as a mole requires. He is a gifted liar and is pleased to have found a job that so perfectly matches his skill set.

When both the police and the gangsters realize that they have rats in their respective midsts, William and Sullivan each set out to find the other. The ensuing chess match gets bloody. Each man cleverly tries to lure the other out of the weeds, and each man only escapes detection through guile and sheer animal instinct.

Scorsese seems revitalized by his return to the world of desperate gangsters and brickbat violence. William Monahan’s script is delirious fun, with character detail and dialog that is both street-level authentic and uproariously funny. The audience with whom I saw this film laughed more than the audience with whom I saw “Talladega Nights.” The eclectic soundtrack features the kind of raucous, pounding rock (including the old Scorsese standby, “Gimme Shelter) which you’d expect to find in the dive bars where much of the film’s action takes place. And celebrated editor Thelma Schoonmaker keeps the pacing fast and fluid, while still allowing us to follow the story’s many twists and turns.

Which is why the end is so disappointing. For much of the film, Scorsese and Monahan transcend the cop and gangster genre, infusing the film and its characters with genuine soul. However, the ending is glib, punctuated by a pointless pile of dead bodies and a lot of “out of nowhere” story points. It was as if the writer of “Lucky Number Slevin” or some other Tarantino knock-off, was called in at the last minute to inject some style into the “old man’s” film. But all the ending does is betray the substance that preceded it.

Which is not to say that I wish Scorsese should return to making period dramas. After seeing this film, I now believe that he has some great films still left to make before he follows Coppola up to wine country.