complete rehaul; tidied and tested code