Editing a subrange of a wave automatically

I am trying to design a script that allows the user to select a subrange of data points on a graph (using cursors) and set all data points, bounded by the cursors, equal to the average value of those points. I am having a hard time finding a way to edit a subrange in an automated fashion, so any help would be much appreciated. Thank you in advance!
Here is a solution.

NOTE: This is not undoable.

Also I have tested it only briefly.

Read the code to see how it works and to make sure that it does what you want.

Menu "TracePopup"
    "Replace Wave Between Cursors With Mean Value", ReplaceBetweenCursorsWithMean()
End

// ReplaceBetweenCursorsWithMean()
// Replaces all values between cursor A and cursor B with the average value.
// WARNING: THIS IS NOT UNDOABLE
// Create a graph. Put cursor A and cursor B on a trace in the graph.
// Right-click and choose "Replace Wave Between Cursors With Mean Value"
// from the trace popup menu.  
Function ReplaceBetweenCursorsWithMean()
    Wave/Z wA = CsrWaveRef(A)
    if (!WaveExists(wA))
        Abort "Put cursors A and B on the wave"
    endif
    Wave/Z wB = CsrWaveRef(B)
    if (!WaveExists(wB))
        Abort "Put cursor A and B on the wave"
    endif
    if (!WaveRefsEqual(wA, wB))
        Abort "But both cursor A and B on the same wave"
    endif
   
    // NOTE: This assumes that this function was invoked by right-clicking a trace
    // not from the command line or from some other procedure.
    GetLastUserMenuInfo             // Sets S_traceName
    String traceName = S_traceName
    Wave/Z clickedWave = TraceNameToWaveRef("", traceName)
    if (!WaveRefsEqual(wA, clickedWave))
        Abort "You must right-click the wave to which the cursors are attached"
    endif
   
    Variable startPoint = pcsr(A), startX = pnt2x(wA,startPoint)
    Variable endPoint = pcsr(B), endX = pnt2x(wA,endPoint)
    Variable numPoints = (startPoint - endPoint) + 1
   
    if (endPoint < startPoint)
        Variable temp = startPoint
        startPoint = endPoint
        endPoint = temp
    endif

    Variable avg = sum(wA, startX, endX) / numPoints
    wA[startPoint, endPoint] = avg
End