added checks to avoid array out of bound access