Merge Mat's solution.