cleaned up the code to make where() work, some basic refactoring