y.append(dy)

    i3_data.applyXYDriftCorrection(dx,dy)
    if xy_success:
        # Add current to master
        xymaster += i3_data.i3To2DGridAllChannelsMerged()

    # Z correlation
    dz = old_dz
    if correct_z and xy_success:

        xyzcurr = i3_data.i3To3DGridAllChannelsMerged(z_bins,
                                                      uncorrected = True)

        # Do z correlation
        [corr, fit, dz, z_success] = imagecorrelation.zOffset(xyzmaster, xyzcurr)

        # Update Values
        if z_success:
            old_dz = dz
        else:
            dz = old_dz
            
        dz = dz * 1000.0/float(z_bins)

        if z_success:
            i3_data.applyZDriftCorrection(-dz)
            xyzmaster += i3_data.i3To3DGridAllChannelsMerged(z_bins)
    
    z.append(dz)
        i3_data.loadDataInFrames(fmin = j)
        step_step = 2*step
    else:
        i3_data.loadDataInFrames(fmin = j, fmax = j + step)
        step_step = step

    # Apply XY drift correction.
    i3_data.applyXYDriftCorrection(driftx[index], drifty[index])

    # Z correlation
    dz = old_dz

    xyzcurr = i3_data.i3To3DGridAllChannelsMerged(z_bins,
                                                  uncorrected = True)

    [corr, fit, dz, z_success] = imagecorrelation.zOffset(xyzmaster, xyzcurr)

    # Update Values
    if z_success:
        old_dz = dz
    else:
        dz = old_dz
            
    dz = dz * 1000.0/float(z_bins)
    
    if z_success:
        i3_data.applyZDriftCorrection(-dz)
        xyzmaster += i3_data.i3To3DGridAllChannelsMerged(z_bins)

    driftz[index] = dz