rewrote some code, tidied other bits