added boundry checking code