Quick solution off the top of my head (and not having actually read the code) would be when accessing an array element, instead just writing [x], write [(x+size)%size]. The %size will take care of positive wraparound, and adding size would wrap from the lower boundary. (Relatedly, I'm guessing you're going from [1] to [size-1] to deal with edge cases -- with this modulus arithmetic you wouldn't have to do that.)