Added most of the math. Unfinished, so will be amended later.