I think it would be worth moving this logic (from here, as far as the test whether the S-CSCF is the local cluster on line 2142) into a separate function that just returns a server name.  Not found can be indicated by returning a blank server name.  Otherwise it gets even harder to follow the logic in this routine.