This fixes a longstanding bug with the plugin API. This commit is not complete, further polish is still needed.