I can't actually work on the script and find what's up with it right now, so I know I'm not going to be a great help, but I'm trying.

If the pointer goes to (p) instead of (t), then it seems as if you are saving the Y location, but not the X location. That, or you are passing your X location the wrong variable (that of the corner).
Since you are finding a path to (t), then you already have those values... I'd make sure that your new target ends up having the same values.
Just as a note... If you go from just point to point individually, you won't always find the shortest path (in most cases, you won't). That's why I mentioned trying to complete the path first and see which is the shortest.
So things don't get out of hand, I'd set a limit for how many "waypoints" to check, though. For example, you might want to limit the number of objects you'll try to pass when finding the shortest distance to 5 or 10. If there are more objects in the way, then take the shortest distance to there and repeat. The reason being, that you need to store data on all the paths to find which is the shortest. And for every object you encounter, you are adding another 2 paths.
Example using an outline (best way to show it here, I think):
1. Start
1.1 Left of Object #1
1.1.1 Left of Object #2 after going left of Object #1
1.1.1.1 Left of Object #3 after going left of Object #2
1.1.1.2 Right of Object #3 after going left of Object #2
1.1.2.1 Left of Object #3 after going right of Object #2
1.1.2.2 Right of Object #3 after going right of Object #2
Etc.
As you can see, this gets exponentially difficult, the more objects you try to check at once. It becomes a matter of which is more important --- Best path or Fewest calculations.
By doing more than one point at a time, you will get a better path. The greater number of points at a time, the better the path.
However, more points also equals more data to store and compare. 5-10 limit should work best for giving an quality route without getting too crazy with path data.
Btw, for calculating the distance, I'd use geometry... SIN/COS/TAN for caluclating the hypoteneus.

That makes it much easy to get distance from point to point using X/Y points.