tidying code and corrected a couple of bugs