Cast layer as integer to make sure sorting behaves correctly

This resolves #674.

Supercedes #992.