This fixes #1378.

We should refactor the whole thing, but for now it works.