Updated with shorter and more universal solution.