cleaned up code and fixed the checking