added a lot of boundary checking things