aww,at 1000+ lines of code, without the underlying base tables and linked server(EDWGEARS),
that one is a little bigger scope than i can help with as a volunteer;
it would require substantial testing, i think.
the key, however is to remove the openquery stuff, query the linked server with direct commands, as a set based operation, instead of all those cursors.
you might get rid of the temp tables and replace them with teh direct CTE's as well;
this would be beyond the scope of how i volunteer here, sorry.
Lowell