Some refuctoring and tests