Crazy function: am I going nuts?

Hello all.
[LEFT]
[/LEFT]
During my first exploration into XML with actionscript with the purpose of building a dynamic application I have been dealing with the creation of some rather crazy functions. So much so that I am scared of looking at them and then I doubt of the whole efficiency of my workings.

Three loops and three conditionals all nested in a ‘for each’ loop can easily give me a headache (don’t know how about you) and I was wondering that there should surely be simpler ways of achieving what this function does.
Before this function there where several movieClips created dynamically, stored in an array, and given names according to each “Name” attribute of each xml node. All of these nodes represent the different buttons in a dynamic menu.

The parameter of the current target (the button when is clicked) is passed into this function. First the function compares all the xml’s attributes and if it finds a match for the name of the current target then it retrieves (thinking of it as a family tree) all of its cousins and their respective descendants. Then it compares these with the movieclip names in their initial array and if it finds any matches it will store them in a different array. Crazy if you ask me but I need it to be like so.

I would be grateful if someone could tell me if there is a simpler way of doing this or if there is not.

Thank you very much for your time!

Andres.

public static function getCousins(xml:XML,refArray:Array, endArray:Array, mc):void {
            for each (var attribute2:XML in xml..*) 
            {
                if ("mc_"+attribute2.@NAME==mc.name) 
                {
                    for (var i:int =0; i< attribute2.parent().children().length(); i++) 
                    {
                        if (attribute2.childIndex()!=i) 
                        {
                            for (var a:int = 0; a< attribute2.parent().children()*.descendants().length(); a++) 
                            {
                                for (var j:uint = 0; j<refArray.length; j++) 
                                 {
                                    if (refArray[j].name=="mc_"+attribute2.parent().children()*.descendants().@NAME[a]) 
                                    {
                                        endArray.push(refArray[j]);
                                    }
                                }
                            }
                        }
                    }
                }
            }

        }