Trim codes, especially if they've been long term issues, can damage 02 sensors and cats, so I hope you haven't been ignoring stuff for a real long time.
Check for air leaks first. Hoses are inexpensive to fix, just a little time consuming to find.
Yes, I think that trim codes might be why you failed emissions. Read jfoj's sig link. Search for jfoj and read the link he has on 'solving misfires'
I'm so depressed. No one wants to come see me. :(
Mangofy your E46!