working version.  unit tests need to be tidied up