Damn, the forum messes up Pascal code. The code in above post has some parts missing. I've tried both Pascal and Code tags and result is the same.

I've uploaded the code here.