Code now compiles, runs - more or less happy with the structure, though it could be a bit more clear.

Signed-off-by: Ian Bell <ian.h.bell@gmail.com>