By Scott Malone

BOSTON (Reuters) - Massachusetts' top court on Thursday overturned the conviction of a homeless man who had been found guilty of criminal trespassing for sleeping in a mixed-use building during the winter of 2014, ruling he had a legal right to argue that there was no safer alternative.

David Magadini, a 67-year-old homeless man, was repeatedly arrested by police in Great Barrington, in the state's hilly west, for sleeping in the mixed-use commercial building to escape frigid cold.

He was eventually convicted of trespassing after a trial in which a judge overruled his lawyers' request that the jury be informed of the "necessity defense," which can excuse a person for a reasonable violation of a law to preserve his or her life.

"The judge erred in denying the defendant's request for an instruction on the defense of necessity," Geraldine Hines, associate justice of the Massachusetts Supreme Judicial Court, wrote in Thursday's unanimous decision.

Hines noted that Magadini had been arrested during nighttime hours in the winter months, when the town regularly had temperatures below 0 degrees Fahrenheit (-17.8 C).

"There appears to be little question that the weather conditions on the dates of the offenses in February and March presented a 'clear and imminent danger' to a homeless person," Hines wrote.

The court upheld Magadini's conviction in connection with another trespassing incident, which occurred at midday in June in a ice cream shop's restroom.

The state had argued that his conviction was proper, and that he had created a danger to himself by refusing to move out of a city where he could not afford to live and had been banned from a local homeless shelter.

"Today's landmark ruling affirmed that our law does not permit the punishment of the homeless for simply being homeless," said Jessie Rossman, an attorney for the American Civil Liberties Union, which had acted in support of Magadini in the case.

Traditionally, courts apply the necessity defense to the choices that a person could make at the time he or she chooses to break the law, she said.

"We've never looked to see if someone could make different life choices to avoid getting to that position in the first place," Rossman said in a telephone interview.

David Capeless, the district attorney for Berkshire County who brought the case, said he was disappointed with the ruling.

"We thought the judge had done the right thing, but the Supreme Judicial Court has reinvented the case law in this," Capeless said in a telephone interview.

The number of homeless people in Massachusetts has about doubled since 1990, according to the Massachusetts Coalition for the Homeless.

Homeless populations are difficult to measure, but according to the U.S. Department of Housing and Urban Development there were 21,135 homeless people in Massachusetts at the beginning of 2015.

(Reporting by Scott Malone; Editing by Toni Reinhold)