A (not fully optimal, but simple) solution

For Issue #90.