Some code imporvments and tests