Updated to include a) further explanation, b) some debug info, and c) a manual hack to fix it.
Do it totally programmatically - works OK now.