hi... i just did some math & programming 2 help u...
that''s my result function :
bool Intersect(Line l1, Line l2, Vector & out)
{
float h1, h2;
float i1, i2;
float S1X, S1Y, S2X, S2Y;
float E1X, E1Y, E2X, E2Y;
float m1, m2;
float sx, sy; // intersection x & y
S1X = l1.start.x; S1Y = l1.start.y;
E1X = l1.end.x; E1Y = l1.end.y;
S2X = l2.start.x; S2Y = l2.start.y;
E2X = l2.end.x; E2Y = l2.end.y;
float swap;
if (S1X > E1X) // if start > end, swap ''em
{
swap = E1X; E1X = S1X; S1X = swap;
swap = E1Y; E1Y = S1Y; S1Y = swap;
}
if (S2X > E2X) // if start > end, swap ''em
{
swap = E2X; E2X = S2X; S2X = swap;
swap = E2Y; E2Y = S2Y; S2Y = swap;
}
h1 = E1Y-S1Y; h2 = E1X-S1X;
i1 = E2Y-S2Y; i2 = E2X-S2X;
// S1Y + m1*(x-S1X) = S2Y + m2*(x-S2X);
if ( (h2==0.0f) && (i2 == 0.0f))
{
return false; // if h2 & i2 == 0, both lines are parallel to y-axis... no intersection.
}
bool calced = false;
if (h2==0.0f) // if line #1 parallel to y-axis, calc special
{
m2 = i1/i2;
sx = S1X; sy = S2Y+m2*(sx-S2X);
calced = true;
}
if (i2==0.0f) // if line #2 parallel to y-axis, calc special
{
m1 = h1/h2;
sx = S2X; sy = S1Y+m1*(sx-S1X);
calced = true;
}
if (!calced) // if not calced before, calc now...
{
m1 = h1/h2;
m2 = i1/i2;
if (m1==m2) return false; // if m1 & m2 are equal, lines are parallel or equal... no intersection.
sx = (S2Y - m2*S2X - S1Y + m1*S1X) / (m1-m2);
sy = S1Y+m1*(sx-S1X);
}
if (!( ((sx <= E1X) && (sx >= S1X)) && ((sx <= E2X) && (sx >= S2X)) ) )
return false; // if intersection not within lines'' "borders"
out.x = sx;
out.y = sy;
return true;
}
didn''t check it for all cases but i think it should work for all possible pair of lines

you can of course optimize this function... i just wrote it down quickly & for (semi-) good understandability

hope, this helps you !