added guard, and wrong indices use corrected