local maxAmount = 50
local undoDesc = "Shorten selected notes randomly depending on note lengths"

local function sayMessage(message)
  if reaper.APIExists("osara_outputMessage") then
    reaper.osara_outputMessage(message)
  end
end

local editor = reaper.MIDIEditor_GetActive()
if not editor then return(0) end
local take = reaper.MIDIEditor_GetTake(editor)
if not take then return(0) end
local selectedCount = 0
local i = reaper.MIDI_EnumSelNotes(take, -1)
local OKorCancel
local dlgTitle

while i ~= -1 do
  selectedCount = selectedCount + 1
  i = reaper.MIDI_EnumSelNotes(take, i)
end

if selectedCount == 0 then
  sayMessage("No notes selected")
  return(0)
  elseif selectedCount == 1 then
  dlgTitle = "Shorten 1 note randomly depending on note lengths"
  else
  dlgTitle = "Shorten " .. selectedCount .. " notes randomly depending on note lengths"
end

repeat
  OKorCancel, maxAmount = reaper.GetUserInputs(dlgTitle, 1, "Maximum amount (in percentages of each note length)", maxAmount)
until OKorCancel == false or (OKorCancel == true and type(tonumber(maxAmount)) == "number" and tonumber(math.floor(maxAmount)) >= 0 and tonumber(math.floor(maxAmount)) <= 100)

if OKorCancel == false then
  return(0)
end
if maxAmount == false then
  sayMessage("No notes shortened")
  return(0)
end

maxAmount = math.floor(tonumber(maxAmount))

if maxAmount == 0 then
  sayMessage("No notes shortened")
  return(0)
end

reaper.Undo_BeginBlock()

local OK, selected, startPPQ, endPPQ, newEndPPQ, randomAmount
local startQN, endQN, lengthQN, newEndQN, newLengthQN
local shortenedCount = 0
i = reaper.MIDI_EnumSelNotes(take, -1)

while i ~= -1 do
  OK, selected, _, startPPQ, endPPQ, _, _, _ = reaper.MIDI_GetNote(take, i)
  if OK and selected then
    startQN = reaper.MIDI_GetProjQNFromPPQPos(take, startPPQ)
    endQN = reaper.MIDI_GetProjQNFromPPQPos(take, endPPQ)
    lengthQN = endQN - startQN
    randomAmount = math.random(0, maxAmount)
    if randomAmount > 0 and lengthQN > 0.01 then
      repeat
        newLengthQN = lengthQN - (lengthQN * (randomAmount / 100))
        if newLengthQN < 0.01 then
          newLengthQN = 0.01
        end
      until newLengthQN <= lengthQN
      if newLengthQN < lengthQN then
        newEndQN = startQN + newLengthQN
        newEndPPQ = reaper.MIDI_GetPPQPosFromProjQN(take, newEndQN)
        reaper.MIDI_SetNote(take, i, nil, nil, nil, newEndPPQ, nil, nil, nil, true)
        shortenedCount = shortenedCount + 1
      end
    end
  end
  i = reaper.MIDI_EnumSelNotes(take, i)
end

reaper.Undo_EndBlock(undoDesc, -1)

if shortenedCount == 0 then
  sayMessage("No notes shortened")
  elseif shortenedCount == 1 then
  sayMessage("1 note shortened")
  else
  sayMessage(shortenedCount .. " notes shortened")
end
