You are using the value in S, but overwriting it with the indexed value, doesn't seem right.