I wrestled with this problem for a long time before I found the solution, so I'm posting it here.