
function ShowMessage(msg)
  reaper.ShowConsoleMsg(tostring(msg))
end
function SplitFilename(strFilename)
  return string.match(strFilename, "(.-)([^.]-[.-])([^.]+)$")

end

function main()
  reaper.Undo_BeginBlock()
  
  if reaper.CountSelectedMediaItems(0) > 0 then
    numSplitItems = getNumSplitItems()
    if numSplitItems == nil then
      return
    else
      splitCounter = 0
      for i = 1, (reaper.CountSelectedMediaItems(0)) do
        it = reaper.GetSelectedMediaItem(0, i - 1 + splitCounter)
        length = reaper.GetMediaItemInfo_Value(it, "D_LENGTH")
        split_position = reaper.GetMediaItemInfo_Value(it, "D_POSITION") + numSplitItems
    split_number = math.floor(length/numSplitItems)
        for j = 1,(split_number - 1) do
          it = reaper.SplitMediaItem(it, split_position)
          split_position = split_position + numSplitItems
          splitCounter = splitCounter + 1
        end
      end
    end
  else
      ShowMessage("Error: No Media Item selected.")
  end
  
  reaper.Undo_EndBlock("Split Items X measure/beat", -1)
end

function getNumSplitItems()
  title = "Split selected items every X measure/beat"
  num_inputs = 1
  captions_csv = "Interval"
  retvals_csv = "1.0"
  retval, retvals_csv = reaper.GetUserInputs(title, num_inputs, captions_csv, retvals_csv)
  if retval == true then
m1, m2, m3 = SplitFilename(retvals_csv )
OOO =  reaper.TimeMap2_beatsToTime(0,m3,m2)
    return OOO
  else
    ShowMessage("None or invalid number.")
    return nil
  end
end

reaper.PreventUIRefresh(1)
main()
reaper.PreventUIRefresh(-1)
reaper.UpdateArrange()
