Some refactoring and added north/east boundary checking