I am really stuck on this problem, and I figured you people could probably help me with it. I have a rectangle with width w and height h with a certain point p inside it. This point is given by the offsets x and y from the topleft of the square. In a picture:

Now, I rotate this rectangle by angle a. I draw the surrounding box around it. I want to know the new (x, y) coordinates of point p from the topleft of the surrounding box (or, the lenghts of the purple lines).

Notes: this is not homework, this is a programming problem I'm stuck on. In the images the angle a < 90, this is not necessarily the case. Also, the lengths of the surrounding box are already known, they need not be calculated.
I am refering to the picture below, where the rotation angle is denoted by $\alpha$.
We have for the new $x', y'$ if $0 \le \alpha \le 90$:: $$x' = BD = BC + CD = FE \cos(90-\alpha) + CD = (h - y) \cos(90-\alpha) + x \cos \alpha$$ $$y' = DK = DG + GK = DG + ML \cos (90 - \alpha) = y \cos \alpha + x \cos (90 - \alpha)$$
Using $\cos(90 - \alpha) = \sin \alpha$ we get $$x' = BD = (h - y) \sin \alpha + x \cos \alpha$$ $$y' = DK = y \cos \alpha + x \sin \alpha$$
ADDED. Let us denote this computation as $$(x', y') = F(x, y, h, \alpha), 0 \le \alpha \le 90$$ The meaning and the order of the parameters is relevant.
For other angles use the picture below
CORRECTION: The legend in the figures should be respectively: $\beta=\alpha-90,\beta=\alpha-180,\beta=\alpha-270$.
to deduce: $$(x', y') = F(h-y, x, w, \alpha-90), 90 \le \alpha \le 180$$ $$(x', y') = F(w-x, h-y, h, \alpha-180), 180 \le \alpha \le 270$$ $$(x', y') = F(y, w-x, w, \alpha-270), 270 \le \alpha \le 360$$