It's very hard to read the code, because the formatting is terrible. Anyway, the key problem is that you are building the array inside a loop:
a[i] = wireOriginX
a[i] = wireOriginY
but the order of the loop is completely dependent on the database - you just have a foreach loop over the instances. That seems a very dangerous and illogical thing to do.
A far better approach would be to have a function which allowed you to find the coordinates of a particular pin on a particular named instance - something like:
) ; defun getPinPositions
This returns a has of pin positions for a particular master, indexed by pin name. I'd probably then keep a hash of all these hash tables indexed by cellView. You can then look up the location of a particular pin name in a particular cellView, and transform it (using dbTransformPoint) using the transform of the instance of that cellView, and do the same for the other instance and pin you're trying to connect to.
That way you can then describe your wiring as a set of connections from pin A of I1 to pin B of I2 and so on. No need for any assumed orders of the database.
Sorry for a not particularly complete example - I wanted to outline the principle. I think your code at the moment has too many assumptions hard coded in - better to try to make it more generic - give yourself the ability to create wires between pairs of named instance/pin combinations, and you'll find it much easier.