I don't even understand what's happening here.  But your replacement code looks substantially simpler.