Bug-fixes to get a partially working implementation. More work needed to check state is correct throughout