This really should be made a bit less naive, but for the moment it works as expected.