By Yannis Behrakis

IDOMENI, Greece (Reuters) - Police in Macedonia fired tear gas and stun grenades at desperate migrants stranded for days at the Greek border and who are demanding passage to western Europe, as soldiers began erecting a metal fence to keep them out.

Macedonia, along with other Balkan countries on the migrant route, began turning away "economic migrants" nearly two weeks ago. Human rights groups have criticized the decision, under which only Syrians, Iraqis and Afghans are allowed through.

The new restrictions triggered days of protests from Iranians, Pakistanis, Moroccans and others, stranded in squalid tent camps on the border. Some Iranians have sewn their lips shut. One man on Saturday threw himself on railway lines before the police, screaming and flailing.

Saturday's violence broke out after one migrant, believed to be a Moroccan, was electrocuted and badly burned when he climbed on top of a train wagon.

An angry crowd surged towards lines of Macedonian police and began throwing stones, a Reuters photographer at the scene said.

The police responded with tear gas and stun grenades, driving the crowd back, a Reuters photographer at the scene said. Some officers threw stones.

In a surge that began about 18 months ago, migrants have been flowing across Balkan borders, having landed by boat in Greece from Turkey.

Human rights groups say international conventions require countries to treat asylum requests on merit, not on the basis of nationality.

Earlier on Saturday, Macedonian soldiers began driving metal poles around 3 meters high into the cold, muddy ground, building a barrier similar to that erected by Hungary on its southern border.

European Union member Hungary in September and October sealed its southern border to migrants, calling them a threat to the security, prosperity and "Christian values" of Europe.

But the Macedonian government said it had no intention of sealing its border completely. A government spokesman said the aim of the fence was "to direct the inflow of people towards the controlled points for their registration and humane treatment."

Story continues

"We would like to underline that the border will remain open," said spokesman Aleksandar Gjorgjiev. "We will allow passage for the people who come from war-affected regions as we have done thus far."

Macedonia, Serbia and Croatia say they began filtering the migrants after Slovenia, further along the route, announced it would start doing the same.

The number of migrants making the journey to Europe rose dramatically this year compared to 2014, although the influx shows signs of decreasing as winter approaches.

Germany expects roughly 1 million refugees and migrants to arrive this year alone.

(Additional reporting by Kole Casule in SKOPJE; Writing by Matt Robinson; Editing by Raissa Kasolowsky)