replace k with sample_index
fix off-by-one error