It seems the code I'd written so far was not correct.
The rectangle stuff is slightly more involved than it seemed.
I've corrected a lot of other stuff.
Currently I'm working on a small console program trying to get my algorimth working in that. Then I fit it into my main code.