Implementing the S-DTW refinement step.