You'll have to tweak your algorithm a bit to calculate the angle - currently you only record the absolute difference in position, but you need the relative difference (i.e. can be positive or negative depending on positioning).

    int dx = T.X - S.X; // difference in position
    int dy = T.Y - S.Y;

    if (dx > MapX / 2) // if distance is bigger than half map width, then looping must be closer
        dx = (dx - MapX) * -1; // reduce distance by map width, reverse 
    else if (dx < -MapX / 2) // handle the case that dx is negative
        dx = (dx + MapX) * -1;

    //Do the same for dy
    if (dy > MapY / 2)
        dy = (dy - MapY) * -1;
    else if (dy < -MapY / 2)
        dy = (dy + MapY) * -1;

    double dist = sqrt(dy*dy+dx*dx); // same as before
    double angle = atan2(dy,dx) * 180 / PI; // provides angle in degrees