Horribly complicated. (Warning - contains maths)