selected_items_count = reaper.CountSelectedMediaItems(0)

reaper.Undo_BeginBlock()

-- INITIALIZE loop through selected items
for i = 0, selected_items_count-1  do
  item = reaper.GetSelectedMediaItem(0, i) -- Get selected item i

  take = reaper.GetActiveTake(item)

  preserve = reaper.GetMediaItemTakeInfo_Value(take ,"B_PPITCH")

  if preserve == 0 then
    
    oldpitch = reaper.GetMediaItemTakeInfo_Value(take, "D_PITCH")
    rate = reaper.GetMediaItemTakeInfo_Value(take, "D_PLAYRATE")
    newRate = 1
    newPitch = (((12/math.log(2)) * math.log(rate)) + oldpitch)
    reaper.SetMediaItemTakeInfo_Value(take, "D_PITCH", newPitch)
    reaper.SetMediaItemTakeInfo_Value(take, "B_PPITCH", 1)

  end

end -- ENDLOOP through selected items

reaper.Undo_EndBlock("Change Rates to Pitch and Preserve Pitch", -1)