local SCRIPT_TITLE = '..Harmonies'

--[[

lua file name: HarmonyPanel.lua

Copy selected groups to a new track and transpose all included notes
Add only one track or multiple tracks depending on user selection.

1/ Transpose all notes in current key scale -7 to +7 (C, D.. to B)
2/ Display current key scale found in selected group(s)
3/ Use current track to duplicate new track (to keep track voice)
4/ Generate AI retakes for each new group harmony
5/ Panel display introduced with Synthesizer V version 2.1.2

Update: Minor updates
		 4 - Add negative harmony option
		 5 - Major update: Prior use user scale choice (ComboBox) than scale found (or not)
			 and update outer scale checkbox is added
		 6 - Add check box: major scale only detection and detection property in scalesReference
		 7 - Add check box: update selected groups only in user selected scale (no new track)
		 8 - Add synchronize unlinked groups
		 9 - Minor update
		10 - Add multiple group creation after dropping chords notes from DAW
		11 - Add rotating voicing with presets, thanks to Enkerli (forum2 Dreamtonics)
		12 - Update scale list (same as Dreamtonics combobox)
		13 - Minor update
		14 - Add ismain in groupref function
		
Notice: Works only with script panel 
		introduced with Synthesizer V version >= 2.1.2

2025 - JF AVILES
--]]

function getClientInfo()
	return {
		name = SV:T(SCRIPT_TITLE),
		-- category = "_JFA_Panels",
		author = "JFAVILES",
		versionNumber = 14,
		minVersion = 131329,
		type = "SidePanelSection"
	}
end

-- Generated by JFA TranslateScripts.lua
function getTranslations(langCode)
	return getArrayLanguageStrings()[langCode]
end

-- Generated by JFA TranslateScripts.lua
function getArrayLanguageStrings()
	return {
		["en-us"] = {
			{"Track scale test", "Track scale test"},
			{"1 note", "1 note"},
			{"Selected", "Selected"},
			{"Apply", "Apply"},
			{"Generate harmonies", "Generate harmonies"},
			{"Major", "Major"},
			{"Track H", "Track H"},
			{"2 notes", "2 notes"},
			{"3 notes", "3 notes"},
			{"Octaves", "Octaves"},
			{"Fixed", "Fixed"},
			{"Negative", "Negative"},
			{"Rotating", "Rotating"},
			{"Basic (Scale Steps)", "Basic (Scale Steps)"},
			{"Brecker Voice-Steal", "Brecker Voice-Steal"},
			{"Brecker Chromatic", "Brecker Chromatic"},
			{"Constant Fifth + Rotating", "Constant Fifth + Rotating"},
			{"Chromatic Clusters", "Chromatic Clusters"},
			{"Mixed Mode Demo", "Mixed Mode Demo"},
			{"Version", "Version"},
			{"author", "author"},
			{"minEditorVersion", "minEditorVersion"},
			{"Select at least one group!", "Select at least one group!"},
			{"Natural minor", "Natural minor"},
			{"Harmonic minor", "Harmonic minor"},
			{"Melodic minor", "Melodic minor"},
			{"Major pentatonic", "Major pentatonic"},
			{"Minor pentatonic", "Minor pentatonic"},
			{"Major blues ", "Major blues "},
			{"Minor blues", "Minor blues"},
			{"Dorian", "Dorian"},
			{"Phrygian", "Phrygian"},
			{"Lydian", "Lydian"},
			{"Mixolydian", "Mixolydian"},
			{"Locrian", "Locrian"},
			{"Ionian", "Ionian"},
			{"Aeolian", "Aeolian"},
			{"Whole tone", "Whole tone"},
			{"Octatonic", "Octatonic"},
			{"Japanese", "Japanese"},
			{"Chinese", "Chinese"},
			{"Chinese 2", "Chinese 2"},
			{"Indian", "Indian"},
			{"Hungarian major", "Hungarian major"},
			{"Groups", "Groups"},
			{"No common scale key found!", "No common scale key found!"},
			{"groups", "groups"},
			{"group", "group"},
			{"No scale key found!", "No scale key found!"},
			{"Track: ", "Track: "},
			{"Error: No scale key found!", "Error: No scale key found!"},
			{"Error: Position into scale error!", "Error: Position into scale error!"},
			{"No group selected!", "No group selected!"},
			{"Select a group first (only one)!", "Select a group first (only one)!"},
			{"Synchronize unlinked groups", "Synchronize unlinked groups"},
			{"Update notes in selected scale", "Update notes in selected scale"},
			{"Drop notes from DAW", "Drop notes from DAW"},
			{"Action2: Synchronize groups", "Action2: Synchronize groups"},
			{"Action3: Drop from DAW", "Action3: Drop from DAW"},
			{"Major scales only detection", "Major scales only detection"},
			{"Action1: Select a scale and type", "Action1: Select a scale and type"},
			{"Select a key scale", "Select a key scale"},
			{"Key scale type", "Key scale type"},
			{"Update scale selected groups", "Update scale selected groups"},
			{"Transpose (-7 to +7)", "Transpose (-7 to +7)"},
			{"Get current voice for new tracks", "Get current voice for new tracks"},
			{"Update notes outer scale", "Update notes outer scale"},
			{"Harmony type", "Harmony type"},
			{"Synchronize similar groups", "Synchronize similar groups"},
			{"Generate group", "Generate group"},
			{"Detection: Select a group", "Detection: Select a group"},
		},
	}
end

-- Define a class  "NotesObject"
NotesObject = {
	hostinfo = nil,
	osType = "",
	osName = "",
	hostName = "",
	languageCode = "", 
	hostVersion = "",
	hostVersionNumber = 0,	
	displayVersion = true,	-- display version
	displayAuthor = false,	-- display author
	allScalesActive = false,			-- true to list all scales
	isDetectionMajorScaleOnly = true, 	-- detection limited to major scale
	isUpdateNotesOuterScale = true, 	-- Update notes outer scale
	isSynchronizeGroup = false, 		-- Synchronize group unlinked
	isDropNotesFromDAW = false, 		-- Drop notes after drag from DAW
	trackTestActive = false,			-- Add track button to generate samples notes in scale
	trackTest = nil,					-- track to test harmonies
	trackTestTitle = SV:T("Track scale test"), -- track to test harmonies
	majorScale = "Major",
    scales = {},
	errorMessages = {},
	keyNames = {},					-- {"C", "Db", "D", ...
	currentKeyNames = {},			-- {"C", "Db", "D", ...
	posKeyInScale = 0,
	keysInScale = {},
	relativeKeys = {},				-- {{"C","Am"},{"Db","Bbm"},{"D","Bm"},
	transposition = {},
	transpositionRefLabel = 1,		-- {Label = SV:T("1 note"), Position = 8, RefData = {"+7", "+6", "+5",...
	transpositionRefPosition = 2,	-- Position = 8,
	transpositionRefData = 3,		-- RefData = {"+7", "+6", "+5",...
	pitchSelected = "",				-- Selected: 0 or 1 or +3, +5 etc.
	pitchSelectedLabel = SV:T("Selected") .. ": ",
	pitchSelectedType = "pitch",
	isOnlyOneKeyFound = false,
	isTrackKeyFound = false,
	posKeyInScaleForm = 0,
	SEP_KEYS = "/",
	keyScaleChoice = {},
	keyScaleSelected = "",
	keyScaleTypeSelected  = 1,		
	keyScaleTypeTitleSelected  = "",
	keyScaleTypeValuesSelected = {0,2,4,5,7,9,11}, -- default major
	trackNameHarmony = "",
	isTrackClone = true,			-- Clone track to keep voicebank
	isUpdateCurrentGroup = false,	-- Update current groups only
	isFixed = false,
	isNegativeHarmony = false,
	firstNegativeNote = 0,
	isRotating = false,					-- Rotating mode
	isRotatingScaleQuantize = true,		-- Scale-quantize rotating chords
	isRotatingScaleSteps = true,		-- Use scale steps instead of chromatic semitones for rotating
	rotatingPresets = {},				-- Voicing presets 
	rotatingPresetSelected = 1,			-- Default position
	rotatingCustomPattern = {},			-- Default to Basic
	rotatingIntervals = {},				-- Parse to new format
	newTrackRef = nil,
	tracks = {},
	outputLevelDefaultValue = 0,
	isCurrentVoiceTrack = true,
	languageOverride = "", 		-- Language override (Empty string => disabled)
	retakes = true, 			-- Enable AI retakes
	newDurationRetakes = true,	-- AI retakes
	newPitchRetakes = true,		-- AI retakes
	newTimbreRetakes = true,	-- AI retakes
	defaultKeyFoundMessage = "",
	groupsSelected = {},
	scalesList = {},
	controls = {}, -- controls panel
	applyButtonText = SV:T("Apply"),
	applyButtonValue = nil,				-- button
	generateGroupButtonValue = nil,		-- button
	statusTextValue = nil,				-- text panel
	colors = {},
	currentColorPos = 0,
	currentColor = "",
	infosToDisplay = "",
	harmonyList = {},
	displayMultiplePitchChoice = false,
	transpositionSelected = 0,
	numTracks = 0,
	groupSource = nil,
	currentSeconds = 0,
	currentSecondsDisplay = "",
	currentTrackNumber = nil,
	processing = 0,
	stopProcess = false,
	stopProcessOK = false,
	newDAWTrack = nil,
	linkNotesActive = true,
	trackTarget = nil,
	initialTrackName = "",
	initialTrack = nil,
	lyricsException = {},
	defaultLabelInfoText = SV:T("Generate harmonies"),
	debug = false,
	resultDebug = "",
	logs = {}
}

-- Constructor method for the NotesObject class
function NotesObject:new()
    local notesObject = {}
    setmetatable(notesObject, self)
    self.__index = self
	
	self:getHostInformations()
	self.keyScaleTypeSelected  = 0 -- SV:T("Major")
	self.trackNameHarmony = SV:T("Track H")
	
	self.keyNames = {"C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"}
	self.currentKeyNames = {"C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"}
	self.relativeKeys = {{"C","Am"},{"Db","Bbm"},{"D","Bm"},{"Eb","Cm"},{"E","Dbm"},{"F","Dm"},
					{"Gb","Ebm"},{"G","Em"},{"Ab","Fm"},{"A", "Gbm"},{"Bb","Gm"},{"B", "Abm"}}
					
	self.transposition = {
		{SV:T("1 note"),  8, {}},
		{SV:T("2 notes"), 2, {"+1,+3", "+2,+5", "+2,+4", "+3,+5", "+3,+6", "-2,-5", "-3,-5"}},
		{SV:T("3 notes"), 1, {"+2,+5,+7", "+1,+3,+5", "+2,+3,+5", "-2,-5,-7"}},
		{SV:T("Octaves"), 4, {"+3,+5,+7", "+2,+7", "-7"; "-7,+7", "-3,-5,+7"}},
		{SV:T("Fixed"),  1, {"Fixed"}},
		{SV:T("Negative"),  1, {"Negative"}},
		{SV:T("Rotating"),  1, {"Rotating"}}
	}
	
	-- Preset rotating chord patterns (using new notation)
	self.rotatingPresets = {
		{name = SV:T("Basic (Scale Steps)"), pattern = "2 | 3,4,2,5 | -2,-3,4"},
		{name = SV:T("Brecker Voice-Steal"), pattern = "0 | 7 (C3-C5) | -5,-3,-4,-1 (G2-G4)"},
		{name = SV:T("Brecker Chromatic"), pattern = "0 | 7c (C3-C5) | -8c,-5c,-7c,-1c (G2-G4)"},
		{name = SV:T("Constant Fifth + Rotating"), pattern = "7 | 3,4,-3,-4 | -5,5,2,-2"},
		{name = SV:T("Chromatic Clusters"), pattern = "3c,-8c,5c | 7c,-5c | 2c,3c,4c,5c"},
		{name = SV:T("Mixed Mode Demo"), pattern = "3,4c,-2 | 7,-5c,3 (C3-C5)"}
	}

	-- Current rotating intervals (will be set from preset or custom input)
	self.rotatingPresetSelected = 1
	
	self.rotatingCustomPattern = self.rotatingPresets[1].pattern  -- Default to Basic
	self.rotatingIntervals = self:parseRotatingPattern(self.rotatingCustomPattern)  -- Parse to new format

	self.colors = self:getColors()
	self.scales = self:getScalesData(self.allScalesActive) -- Init activated scales or all	
	self.keyScaleChoice = self.keyNames
	
	self.controls = self:getControls()
	self:initializeControlsValues()
	
	-- Initialize rotating pattern input
	self.controls.rotatingCustomInput.value:setValue(self.rotatingCustomPattern)

	self.pitchSelected = "0"
	self.harmonyList = self:getHarmonyList()
	
	-- SV:T("Selected") .. ": " .. pitchSelected
	self.controls.transpositionSelected.value:setValue(self.pitchSelectedLabel .. self.pitchSelected)
	self.transpositionSelected = 0
	
	self.applyButtonValue = SV:create("WidgetValue")
	self.generateGroupButtonValue = SV:create("WidgetValue")
	self.statusTextValue = SV:create("WidgetValue")
	self.statusTextValue:setValue("")
	self.statusTextValue:setEnabled(false)
	
	self:setControlsCallback()
	self:setButtonApplyControlCallback()
	self:setButtonGenerateGroupControlCallback()

	-- load combox data
	self:getComboLists()

	local infos = getClientInfo()

	self.infosToDisplay = ""
	if self.displayVersion then
		self.infosToDisplay = self.infosToDisplay .. SV:T("Version") .. ": " ..  infos.versionNumber
		if self.displayAuthor then
			self.infosToDisplay = self.infosToDisplay .. " - " .. SV:T("author") .. ": " .. infos.author
		end
	end
	-- self.infosToDisplay = self.infosToDisplay .. SV:T("minEditorVersion") .. ": " ..  infos.minEditorVersion
	self:addTextPanel(self.infosToDisplay)
	self:addTextPanel(self.defaultLabelInfoText .. "...")
	
	self.defaultKeyFoundMessage = SV:T("Select at least one group!") .. "\r"
	self.lyricsException = {"+", "++", "-", "br", "'", ".cl", ".pau", ".sil"}
	
	-- Register arrangement selection callback
	self:registerArrangementSelectionCallback()
	
    return self
end

-- Register arrangement selection callback
function NotesObject:registerArrangementSelectionCallback()
	
	-- Register selection callback to load parameters when selection changes
	SV:getArrangement():getSelection():registerSelectionCallback(function(selectionType, isSelected)
		self.groupsSelected = self:getSelectedGroups()
		
		if #self.groupsSelected > 0 then
			local keysInfos = self:getGroupKeyScale()
			
			if #keysInfos.keyScaleFound <= 0 then
				-- No comon key scale found
				self.controls.scaleKeyFound.value:setValue(keysInfos.scaleKeyResult)
			end
			self:setGroupSource()
		end
	end)
	
	-- Register clear selection callback
	SV:getArrangement():getSelection():registerClearCallback(function(selectionType)
		-- No group selected in arrangement view
		self.controls.scaleKeyFound.value:setValue(self.defaultKeyFoundMessage)
	end)
end

-- Set group source selected
function NotesObject:setGroupSource()
	self.groupsSelected = self:getSelectedGroups()
	if #self.groupsSelected == 1 then
		self.groupSource = self.groupsSelected[1]
		self.groupSourcePosSeconds = self:getTimeAxis():getSecondsFromBlick(self.groupSource:getOnset())
		self.groupSourceNumNotes = self.groupSource:getTarget():getNumNotes()
		self.currentTrackNumber = self:getCurrentTrack():getIndexInParent()
	else
		self.groupSource = nil
	end
end

-- Get scales data
function NotesObject:getScalesData(allscalesActive)
	local scales = {}
	
	local scalesReference = {
		-- KeyScale type, Intervals
		{name = SV:T("Major"), 				val = {0,2,4,5,7,9,11},		active = true,	detection = true},
		{name = SV:T("Natural minor"),		val = {0,2,3,5,7,8,10},		active = true,	detection = true},
		{name = SV:T("Harmonic minor"),		val = {0,2,3,5,7,8,11},		active = true,	detection = false},
		{name = SV:T("Melodic minor"),		val = {0,2,3,5,7,9,11},		active = true,	detection = false},
		{name = SV:T("Major pentatonic"),	val = {0,2,4,7,9},			active = true,	detection = true},
		{name = SV:T("Minor pentatonic"),	val = {0,3,5,7,10},			active = true,	detection = false},
		{name = SV:T("Major blues "),		val = {0,2,3,4,7,9},		active = true,	detection = true},
		{name = SV:T("Minor blues"),		val	= {0,3,5,6,7,10},		active = true,	detection = false},
		{name = SV:T("Dorian"),				val = {0,2,3,5,7,9,10},		active = true,	detection = false},
		{name = SV:T("Phrygian"),			val = {0,1,3,5,7,8,10},		active = true,	detection = false},
		{name = SV:T("Lydian"),				val = {0,2,4,6,7,9,11},		active = true,	detection = false},
		{name = SV:T("Mixolydian"),			val	= {0,2,4,5,7,9,10},		active = true,	detection = false},
		{name = SV:T("Locrian"),			val	= {0,1,3,5,6,8,10},		active = true,	detection = false},
		{name = SV:T("Ionian"),				val = {0,2,4,5,7,9,11},		active = false,	detection = false},
		{name = SV:T("Aeolian"),			val	= {0,2,3,5,7,8,10},		active = false,	detection = false},
		{name = SV:T("Whole tone"),			val = {0,2,4,6,8,10},		active = true,	detection = false},
		{name = SV:T("Octatonic"),			val = {0,1,3,4,6,7,9,10},	active = true,	detection = false},
		{name = SV:T("Japanese"),			val	= {0,1,5,7,8}, 			active = false,	detection = false},
		{name = SV:T("Chinese"),			val	= {0,2,4,7,9}, 			active = false,	detection = false}, 
		{name = SV:T("Chinese 2"),			val	= {0,4,6,7,11}, 		active = false,	detection = false},
		{name = SV:T("Indian"),				val	= {0,1,3,4,7,8,10},		active = false,	detection = false},
		{name = SV:T("Hungarian major"),	val = {0,3,4,6,7,9,10},		active = false,	detection = false}
	}
	
	-- loop to active scales
	for i = 1, #scalesReference do
		if allscalesActive or scalesReference[i].active then
			table.insert(scales, scalesReference[i])
		end
	end

	return scales
end

-- Display message box
function NotesObject:show(message)
	SV:showMessageBox(SV:T(SCRIPT_TITLE), message)
end

-- Get string format from seconds
function NotesObject:secondsToClock(timestamp)
	return string.format("%02d:%06.3f", 
	  --math.floor(timestamp/3600), 
	  math.floor(timestamp/60)%60, 
	  timestamp%60):gsub("%.",",")
end

-- Get host informations
function NotesObject:getHostInformations()
	self.hostinfo = SV:getHostInfo()
	self.osType = self.hostinfo.osType  -- "macOS", "Linux", "Unknown", "Windows"
	self.osName = self.hostinfo.osName
	self.hostName = self.hostinfo.hostName
	self.languageCode = self.hostinfo.languageCode
	self.hostVersion = self.hostinfo.hostVersion
	self.hostVersionNumber = self.hostinfo.hostVersionNumber
end

-- Clear internal logs
function NotesObject:logsClear()
	self.logs = {}
end

-- Get object properties (debug only)
function NotesObject:getObjectProperties(obj, level)
	local result = ""
	local level = level or 0
	local maxLevel = 3
	level = level + 1
	
	if obj ~= nil then
		for k, v in pairs(obj) do
			if obj[k] ~= nil then
				result = result .. "(level: " .. level .. ") " .. k .. "=" .. tostring(v) .. "\r"
				if type(v) == "table" then
					-- result = result .. ", size:" .. #v .. ": "
					if level < maxLevel then
						result = result .. self:getObjectProperties(v, level) .. "\r"
					else
						result = result .. "\r"
					end
				end
			end
		end
	end
	return result
end
	
-- Get selected groups
function NotesObject:getSelectedGroups()	
	return SV:getArrangement():getSelection():getSelectedGroups()
end

-- Get current track
function NotesObject:getCurrentTrack()
	return SV:getMainEditor():getCurrentTrack()
end

-- Get timeAxis
function NotesObject:getTimeAxis()
	return self:getProject():getTimeAxis()
end

-- Get project
function NotesObject:getProject()
	return SV:getProject()
end

-- Get scale selected
function NotesObject:getScaleSelected()
	
	self.keyScaleSelected	= self:getkeyScaleChoiceFromPos(self.posKeyInScaleForm)
	self.posKeyInScale		= self:getKeyPosInKeynames(self.keyNames, self.keyScaleSelected) -- C = 1	

	self.keyScaleTypeSelected		= self.controls.scaleKeyType.value:getValue() + 1
	self.keyScaleTypeTitleSelected 	= self.scales[self.keyScaleTypeSelected].name
	self.keyScaleTypeValuesSelected	= self.scales[self.keyScaleTypeSelected].val

	self.currentKeyNames = self:copyTable(self.keyNames)
	
	-- Rotate table content, start note to new key
	self:shiftTable(self.currentKeyNames, self.posKeyInScale - 1) -- C = 1 - 1 = 0
	self.keysInScale = self:getKeysInScale(self.currentKeyNames)
end

-- Get group key scale 
function NotesObject:getGroupKeyScale()
	local scaleKeyResult = "" -- To display key scale found in TextArea
	local keyScaleFound = ""
	local keyFoundDisplay = ""
	local keyScaleFoundTrack = ""
	
	local trackName = ""
	if self:getCurrentTrack() ~= nil then
		trackName = self:getCurrentTrack():getName() .. " - "
	end
	scaleKeyResult = scaleKeyResult  .. trackName .. SV:T("Groups") 
						.. " (" .. #self.groupsSelected .. ")" .. "\r"	
	
	local keysInfosNew = self:getKeysInfos() -- check key scale in notes
	
	keyScaleFound		= keysInfosNew.keyScaleFound
	keyFoundDisplay		= keysInfosNew.keyFoundDisplay
	keyScaleFoundTrack	= keysInfosNew.keyScaleFoundTrack
	
	if #keyScaleFound > 0 then
		scaleKeyResult = scaleKeyResult  .. keyFoundDisplay .. "\r"
	else
		scaleKeyResult = scaleKeyResult  .. SV:T("No common scale key found!") .. "\r"
	end
	-- Display key scale found in TextArea
	self.controls.scaleKeyFound.value:setValue(scaleKeyResult)
	
	local keysInfos = { 
		keyScaleFound		= keyScaleFound,
		keyFoundDisplay		= keyFoundDisplay, 
		keyScaleFoundTrack	= keyScaleFoundTrack,
		scaleKeyResult		= scaleKeyResult
	}

	return keysInfos
end

-- Create a new track
function NotesObject:createTrack()
	local newTrack = SV:create("Track")
	newTrack:setDisplayColor(self.currentColor)
	
	self:getProject():addTrack(newTrack)
	return newTrack
end

-- Clone track from track reference
function NotesObject:cloneTrack()
	local newTrack = self.newTrackRef:clone()
	newTrack:setDisplayColor(self.currentColor)
	self:getProject():addTrack(newTrack)
	return newTrack
end

-- Get harmony list
function NotesObject:getHarmonyList()
	local resultList = {}
	for iList = 1, #self.transposition do
		table.insert(resultList, self.transposition[iList][self.transpositionRefLabel])
	end
	return resultList
end

-- Get rotating preset names list
function NotesObject:getRotatingPresetList()
	local resultList = {}
	for i = 1, #self.rotatingPresets do
		table.insert(resultList, self.rotatingPresets[i].name)
	end
	return resultList
end

-- Convert note name to MIDI pitch number
-- Examples: "C3" -> 48, "Db4" -> 61, "G#2" -> 44
function NotesObject:noteToPitch(noteName)
	if noteName == nil or #noteName < 2 then
		return nil
	end

	local noteMap = {C=0, D=2, E=4, F=5, G=7, A=9, B=11}

	-- Parse note letter
	local letter = noteName:sub(1,1):upper()
	local basePitch = noteMap[letter]
	if basePitch == nil then
		return nil
	end

	-- Parse accidentals and octave
	local pos = 2
	local accidental = 0

	if noteName:sub(pos,pos) == "#" or noteName:sub(pos,pos) == "♯" then
		accidental = 1
		pos = pos + 1
	elseif noteName:sub(pos,pos) == "b" or noteName:sub(pos,pos) == "♭" then
		accidental = -1
		pos = pos + 1
	end

	-- Parse octave number
	local octaveStr = noteName:sub(pos)
	local octave = tonumber(octaveStr)
	if octave == nil then
		return nil
	end

	-- Calculate MIDI pitch: octave * 12 + note + accidental
	-- C0 = 12, C1 = 24, C2 = 36, C3 = 48, C4 = 60, etc.
	return (octave + 1) * 12 + basePitch + accidental
end

-- Parse custom rotating pattern from text input
-- Format: "intervals1 | intervals2 | intervals3"
-- Examples:
--   "5,-7,4 | -8,3,2,0,-4 | 7,-5,3"  (scale steps)
--   "3c,-8c,5c | 7c"  (chromatic semitones)
--   "4,7 (C3-C4) | 2,-2,5 (C2-C5)"  (with voice ranges)
--   "3,4c,-2 | 7,-5c (C3-C5)"  (mixed modes with range)
function NotesObject:parseRotatingPattern(patternText)
	local patterns = {}
	if patternText == nil or #patternText == 0 then
		return nil
	end

	-- Split by pipe separator
	local trackPatterns = self:split(patternText, "|")

	for _, trackPattern in ipairs(trackPatterns) do
		trackPattern = self:trim(trackPattern)

		-- Parse optional voice range at end: (C3-C4) or (C3,C4)
		local minPitch, maxPitch = nil, nil
		local rangePattern = trackPattern:match("%(([^%)]+)%)")

		if rangePattern then
			-- Remove range from pattern
			trackPattern = trackPattern:gsub("%s*%([^%)]+%)", "")

			-- Parse range: "C3-C4" or "C3,C4"
			local lowNote, highNote = rangePattern:match("([^%-,]+)%-([^%-,]+)")
			if not lowNote then
				lowNote, highNote = rangePattern:match("([^,]+),([^,]+)")
			end

			if lowNote and highNote then
				minPitch = self:noteToPitch(self:trim(lowNote))
				maxPitch = self:noteToPitch(self:trim(highNote))
			end
		end

		-- Parse intervals with optional 'c' suffix
		local track = {intervals = {}, minPitch = minPitch, maxPitch = maxPitch}
		local intervalStrs = self:split(trackPattern, ",")

		for _, intervalStr in ipairs(intervalStrs) do
			intervalStr = self:trim(intervalStr)

			-- Check for 'c' suffix (chromatic)
			local isChromatic = false
			if intervalStr:sub(-1) == "c" or intervalStr:sub(-1) == "C" then
				isChromatic = true
				intervalStr = intervalStr:sub(1, -2) -- Remove 'c'
			end

			local value = tonumber(self:trim(intervalStr))
			if value ~= nil then
				table.insert(track.intervals, {value = value, isChromatic = isChromatic})
			end
		end

		if #track.intervals > 0 then
			table.insert(patterns, track)
		end
	end

	return (#patterns > 0) and patterns or nil
end

-- Get track list
function NotesObject:getTracksList()
	local list = {}
	local formatCount = "%3d"
	local iTracks = self:getProject():getNumTracks()
	
	for iTrack = 1, iTracks do
		local track = self:getProject():getTrack(iTrack)
		local numGroups = track:getNumGroups() - 1
		local format = formatCount .. " " .. SV:T("groups")
		if numGroups < 2 then
			format = formatCount .. " " .. SV:T("group")
		end
		table.insert(list, track:getName() .. " (" .. string.format(format, numGroups) .. ")" )
	end
	return list
end

-- Get scale from title
function NotesObject:getScaleFromTitle(scaleSearch)
	local scale = {}
	for key, scale in ipairs(self.scales) do
		if scaleSearch == scale.name then
			scale = self.scales[key]
		end
	end
	return scale
end

-- get scale Key Found in choice format
function NotesObject:getKeyScaleChoice(keyScaleFound)
	local choice = {}
	if string.find(keyScaleFound, self.SEP_KEYS) == nil then
		table.insert(choice, keyScaleFound)
	else
		choice = self:split(keyScaleFound, self.SEP_KEYS)
	end
	return choice
end

-- Get keys data infos
function NotesObject:getKeysInfos()
	local keyScaleFound = ""
	local keyFoundDisplay = ""
	local keyScaleFoundTrack = ""		

	-- Check groups selected
	if #self.groupsSelected > 0 then
		
		-- Group selected
		keyScaleFound = self:getScaleGroup(self.groupsSelected)
		
		-- Track notes to check
		keyScaleFoundTrack = self:getScaleTrack(self.groupsSelected)
		
		keyFoundDisplay = keyScaleFound
		
		self.isOnlyOneKeyFound = false
		self.isTrackKeyFound = false

		if string.find(keyScaleFound, self.SEP_KEYS) == nil then
			self.isOnlyOneKeyFound = true
		end

		if keyScaleFound == "" then
			keyFoundDisplay = SV:T("No scale key found!")
		else
			
			if #keyScaleFoundTrack > 0 then
				if keyScaleFound ~= keyScaleFoundTrack then
					keyFoundDisplay = keyScaleFound .. "\r" .. SV:T("Track: ") .. keyScaleFoundTrack
					self.isTrackKeyFound = true
				end
			end
		end
	end
	
	local keysInfos = { 
			keyScaleFound = keyScaleFound,
			keyFoundDisplay = keyFoundDisplay, 
			keyScaleFoundTrack = keyScaleFoundTrack
		}
	return keysInfos
end

-- Get next measure Position
function NotesObject:getNextMeasurePos(current_time, timeMeasureBar)
	local notesLength =  16
	local newtime =  current_time
	local current_time_Int = math.floor(current_time)
	
	local new_next_time = current_time_Int
	local maxTime = notesLength * 10
	for i = 1, maxTime do
		if current_time <= new_next_time then
			newtime = new_next_time
			break
		end
		new_next_time = timeMeasureBar * (i + current_time_Int)
	end
	return newtime
end

-- Get current project tempo
function NotesObject:getProjectTempo(seconds)
	local tempoActive = 120
	local blicks = self:getTimeAxis():getBlickFromSeconds(seconds)
	local tempoMarks = self:getTimeAxis():getAllTempoMarks()
	for iTempo = 1, #tempoMarks do
		local tempoMark = tempoMarks[iTempo]
		if tempoMark ~= nil and blicks >= tempoMark.position then
			tempoActive = tempoMark.bpm
		end
	end
	return math.floor(tempoActive)
end

-- Get last group
function NotesObject:getLastGroup(track)
	local lastGroup = nil
	local numGroups = track:getNumGroups()
	if numGroups > 1 then
		lastGroup = track:getGroupReference(numGroups)
	end
	return lastGroup
end

-- Generate group for test only
function NotesObject:findTrackTest(title)
	local trackFound = nil
	local numTracks = self:getProject():getNumTracks()
	
	for iTrack = 1, numTracks do
		local track = self:getProject():getTrack(iTrack)
		if string.find(track:getName(), title) ~= nil then
			trackFound = track
			break
		end
	end
	return trackFound
end

-- Get first mesure after first note (or next position + n)
function NotesObject:getFirstMesure(notePos, nextPos)
	local measurePos = 0
	local measureBlick = 0
	local measureFirst = self:getTimeAxis():getMeasureAt(notePos) + nextPos
	local checkExistingMeasureMark = self:getTimeAxis():getMeasureMarkAt(measureFirst)
	
	if checkExistingMeasureMark ~= nil then
		if checkExistingMeasureMark.position == measureFirst then
			measurePos = checkExistingMeasureMark.position
			measureBlick = checkExistingMeasureMark.positionBlick
		else 
			self:getTimeAxis():addMeasureMark(measureFirst, 
						checkExistingMeasureMark.numerator, 
						checkExistingMeasureMark.denominator)
			local measureMark = self:getTimeAxis():getMeasureMarkAt(measureFirst)
			measurePos = measureMark.position
			measureBlick = measureMark.positionBlick
			self:getTimeAxis():removeMeasureMark(measureFirst)
		end
	else
		-- Temporary measure mark addition
		self:getTimeAxis():addMeasureMark(measureFirst, 4, 4)
		local measureMark = self:getTimeAxis():getMeasureMarkAt(measureFirst)
		measurePos = measureMark.position
		measureBlick = measureMark.positionBlick
		self:getTimeAxis():removeMeasureMark(measureFirst)
	end
	return measureBlick
end

-- Get group reference in blick group source position
function NotesObject:getGroupRef(track, blicksPos)
	local groupRefFound = nil
	local numGroups = track:getNumGroups()
	
	-- All groups except the main group
	for iGroup = 1, numGroups do
		local groupRef = track:getGroupReference(iGroup)
		if not groupRef:isMain() then
			local blickSeconds = self:getTimeAxis():getSecondsFromBlick(groupRef:getOnset())
			
			-- Get group on timing pos
			if blicksPos >= groupRef:getOnset() and blicksPos <= groupRef:getEnd() then
				groupRefFound = groupRef
				break
			end
		end
	end						
	return groupRefFound
end

-- Get next group start position
function NotesObject:getNextGroupStartPosition(track, gapInSecond, measureBarTime)
	local startPosition = 0
	local lastGroup = self:getLastGroup(track)

	if lastGroup ~= nil then
		local lastGroupPosition = self:getTimeAxis():getSecondsFromBlick(lastGroup:getEnd())
		if lastGroupPosition ~= nil then
			local checkGroup = self:getGroupRefTime(track, lastGroupPosition)
			if checkGroup ~= nil then
				startPosition = self:getNextMeasurePos(lastGroupPosition + gapInSecond, measureBarTime)
			end
		end
	end
	return startPosition
end

-- Generate group for test only
function NotesObject:generateGroupForTestOnly()
	-- Create group of notes in a new track
	-- with selected scale and scale type
	local startPosition = 0
	local duration = SV.QUARTER -- self:getTimeAxis():getBlickFromSeconds(0.1)
	local BPM = self:getProjectTempo(0)
	local BPM_ratio = 120 / BPM
	local measureBarTime = BPM_ratio / 16
	local gapInSecond = BPM/60

	-- Find existing group in track test
	self.trackTest = self:findTrackTest(self.trackTestTitle)
	
	if self.trackTest == nil then
		self.trackTest = self:createTrack()
		self.trackTest:setName(self.trackTestTitle)
		
		self.currentColor = self:getNewColor(self:getCurrentTrack())
		self.trackTest:setDisplayColor(self.currentColor)
	else
		startPosition = self:getNextGroupStartPosition(self.trackTest, gapInSecond, measureBarTime)
	end
	
	-- Create group
	local noteGroup = SV:create("NoteGroup")
	local scaleKeys = self.keyScaleTypeValuesSelected
	local notePitch = 60 + self.posKeyInScaleForm
	
	local timePos = 0
	local firstNote = nil
	local lastNote = nil
	-- self:show("#scaleKeys: " .. #scaleKeys .. ", scaleKeys: " .. table.concat(scaleKeys, ",") )
	
	for iKeyType = 1, #scaleKeys do
		local new_next_time = self:getNextMeasurePos(timePos, measureBarTime)  -- Get next measure position
		local notePitch = notePitch + scaleKeys[iKeyType]
		local key = self.keyNames[notePitch % 12 + 1]
		local note = SV:create("Note")
		note:setPitch(notePitch)
		note:setOnset(self:getTimeAxis():getBlickFromSeconds(new_next_time))
		note:setLyrics(key)
		note:setDuration(duration)
		noteGroup:addNote(note)
		timePos = self:getTimeAxis():getSecondsFromBlick(note:getEnd())
		
		if iKeyType == 1 then
			firstNote = note
		end
		lastNote = note
	end
	noteGroup:setName(self.keyScaleSelected .. " " .. self.keyScaleTypeTitleSelected)
	self:getProject():addNoteGroup(noteGroup)
	
	-- Add group reference to project new track
	local newGrouptRef = SV:create("NoteGroupReference", noteGroup)
	
	-- Define start & end group length
	local startPositionBlicks = self:getTimeAxis():getBlickFromSeconds(startPosition)
	local endPositionBlicks = lastNote:getOnset() + lastNote:getDuration() - firstNote:getOnset()
	-- New end position to next bar
	local newEndPosition = self:getFirstMesure(endPositionBlicks, 1) - 10
	newGrouptRef:setTimeOffset(startPositionBlicks)
	newGrouptRef:setTimeRange(startPositionBlicks, newEndPosition) -- v2.1.1

	self.trackTest:addGroupReference(newGrouptRef)
	
end

-- Duplicate and transpose notes
function NotesObject:duplicateNotes(groupsSelected)
	local trackChoice = 0
	local numGroups = 0
	local pitchTarget = self.pitchSelected

	self.currentColor = self:getNewColor(self:getCurrentTrack())
	self.isFixed = (pitchTarget == "Fixed")
	self.isNegativeHarmony = (pitchTarget == "Negative")
	self.isRotating = (pitchTarget == "Rotating")
	
	local pitchTargets = self:split(pitchTarget, ",")
	if #pitchTargets > 1 then
		isMultipleTracks = true -- force for "build your own"
	end

	-- For rotating mode, create multiple tracks (one per interval array)
	if self.isRotating then
		isMultipleTracks = true
		pitchTargets = {}
		for i = 1, #self.rotatingIntervals do
			table.insert(pitchTargets, "Rotating_" .. i)
		end
	end

	if string.len(self.keyScaleSelected) == 0 then
		self:show(SV:T("Error: No scale key found!"))
		return -1
	end
	if self.posKeyInScale < 0 then
		self:show(SV:T("Error: Position into scale error!"))
		return self.posKeyInScale
	end
	
	local formatCount = "%3d"
	local iTracks = self:getProject():getNumTracks()
	
	if not self.isUpdateCurrentGroup then
		if self.isTrackClone then
			self.newTrackRef = self:cloneTrackReference(self:getCurrentTrack(), self:getCurrentTrack():getName())
		end
	end

	-- Only one track to add
	if not isMultipleTracks then
		
		local newGroupRefs = self:groupLoop(groupsSelected, self.isFixed, pitchTarget, self.posKeyInScale, nil)
		-- New track
		if not self.isUpdateCurrentGroup then
			local track = nil
			
			if self.isTrackClone then
				track = self:cloneTrack()
			else
				track = self:createTrack()
			end
			local trackNumber = iTracks + 1
			track:setName(self.trackNameHarmony .. trackNumber .. " (" .. pitchTarget .. ")")

			for iGroupRef = 1, #newGroupRefs do
				track:addGroupReference(newGroupRefs[iGroupRef])
				numGroups = numGroups + 1
			end
		end
	else
		-- add multiple tracks
		for iTrack = 1, #pitchTargets do		
			pitchTarget = self:trim(pitchTargets[iTrack])
			self.isFixed = (pitchTarget == "Fixed")
			self.isNegativeHarmony = (pitchTarget == "Negative")
		
			local newGroupRefs = self:groupLoop(groupsSelected, self.isFixed, pitchTarget, self.posKeyInScale, iTrack)
			local track = nil
			
			if self.isTrackClone then
				track = self:cloneTrack()
			else
				track = self:createTrack()
			end
			local trackNumber = iTrack + 1
			track:setName(self.trackNameHarmony .. trackNumber .. " (" .. pitchTarget .. ")")
			
			for iGroupRef = 1, #newGroupRefs do
				track:addGroupReference(newGroupRefs[iGroupRef])
				numGroups = numGroups + 1
			end
		end
	end
	
	if not self.isUpdateCurrentGroup then
		if self.isTrackClone then
			self:deleteClonedTrack()
		end
	end

	return numGroups
end

-- Clone track to keep current track voice
function NotesObject:cloneTrackReference(trackRef, trackName)
	local newTrack = trackRef:clone()
	local iGroups = newTrack:getNumGroups()
	local color = self:getNewColor(self.trackTarget)
	newTrack:setDisplayColor(color)
	
	if iGroups > 1 then
		-- Delete groups
		while iGroups > 1 do
			local groupRef = newTrack:getGroupReference(iGroups)
			local index = groupRef:getIndexInParent()
			if groupRef ~= nil and not groupRef:isMain() then
				newTrack:removeGroupReference(index)
				iGroups = newTrack:getNumGroups()
			end
		end
	end
	
	newTrack:setName(trackName)
	self:getProject():addTrack(newTrack)

	return newTrack
end

-- Create track target
function NotesObject:createTrackTarget(name)
	local newTrackTarget = SV:create("Track")
	local color = self:getNewColor(self.trackTarget)
	newTrackTarget:setDisplayColor(color)
	
	local newTrackIndex = self:getProject():addTrack(newTrackTarget)
	newTrackTarget = self:getProject():getTrack(newTrackIndex)
	newTrackTarget:setName(name)
	return newTrackTarget
end

-- Delete track reference
function NotesObject:deleteClonedTrack()
	local result = false
	if self.newTrackRef ~= nil then
		local index = self.newTrackRef:getIndexInParent()
		self:getProject():removeTrack(index)
		result = true
	end
	return result
end

-- Loop into groups to duplicate & transpose notes
function NotesObject:groupLoop(groupsSelected, isFixed, pitchTarget, posKeyInScale, iTrack)
	local newGroupRefs = {}
	self.firstNegativeNote = 0
	
	for _, refGroup in pairs(groupsSelected) do
		-- local groupName = refGroup:getTarget():getName()
		local noteGroup = refGroup:getTarget()
		local groupRefTimeoffset = refGroup:getTimeOffset()
		
		local newNoteGroup = nil
		if self.isUpdateCurrentGroup then
			-- Update current group
			newNoteGroup = noteGroup
		else
			-- Clone source group
			newNoteGroup = noteGroup:clone()
		end
		local selectedNotes = newNoteGroup:getNumNotes()
		
		if selectedNotes >= 0 then
		
			-- Duplicate transposed notes into a new track to create
			-- Tranpose notes
			local firstNote = newNoteGroup:getNote(1)
			local lastNote = newNoteGroup:getNote(selectedNotes)
			local firstNotePitch = firstNote:getPitch()
			for iNote = 1, selectedNotes do
				local note = newNoteGroup:getNote(iNote)
				
				-- Rotating option
				local rotatingTrack = nil
				local currentPitchTarget = pitchTarget
				local rotatingData = nil
				local intervalObj = nil
				local voiceMinPitch = nil
				local voiceMaxPitch = nil

				-- For rotating mode, get the interval object from the track
				if self.isRotating then
					local rotatingTrack = self.rotatingIntervals[iTrack]
					local arrayIndex = ((iNote - 1) % #rotatingTrack.intervals) + 1
					intervalObj = rotatingTrack.intervals[arrayIndex]
					currentPitchTarget = intervalObj.value
					voiceMinPitch = rotatingTrack.minPitch
					voiceMaxPitch = rotatingTrack.maxPitch
					rotatingData = {intervalObj = intervalObj, voiceMinPitch = voiceMinPitch, voiceMaxPitch = voiceMaxPitch}
				end

				-- Get new pitch
				local notePitch = self:getNewPitch(isFixed, firstNotePitch, note:getPitch(),
													currentPitchTarget, posKeyInScale, rotatingData)

				note:setPitch(notePitch)
			end
			
			local newGrouptRef = refGroup
			if not self.isUpdateCurrentGroup then
				self:getProject():addNoteGroup(newNoteGroup)
				
				-- Add group reference to project new track
				newGrouptRef = SV:create("NoteGroupReference", newNoteGroup)
				
				-- Adjust time offset
				newGrouptRef:setTimeOffset(groupRefTimeoffset)
			
				-- Adjust time range & voice attributes
				newGrouptRef:setTimeRange(refGroup:getOnset(), refGroup:getDuration())
				newGrouptRef:setVoice(refGroup:getVoice())
				
				if #self.languageOverride > 0 then
					-- Update notes language
					self:updateNotesLanguageOverride(newNoteGroup)
				end
				-- AI retakes
				if self.retakes then
					-- Update AI retakes
					self:updateAIRetakes(newNoteGroup)
				end
			end
						
			table.insert(newGroupRefs, newGrouptRef)
		end
	end

	return newGroupRefs
end

-- Update notes language override
function NotesObject:updateNotesLanguageOverride(newNoteGroup)
	
	for iNote = 1, newNoteGroup:getNumNotes() do
		local note = newNoteGroup:getNote(iNote)
		note:setLanguageOverride(self.languageOverride)
	end
end

-- Update AI Retakes for new group note harmony
function NotesObject:updateAIRetakes(newNoteGroup)
	
	for iNote = 1, newNoteGroup:getNumNotes() do
		local note = newNoteGroup:getNote(iNote)
		local retakeListNote = note:getRetakes()
			if retakeListNote ~= nil then
				-- Generate new AI retakes
				local takeId = retakeListNote:generateTake(self.newDurationRetakes, self.newPitchRetakes, self.newTimbreRetakes)
				retakeListNote:setActiveTake(takeId)
			end
	end
end

-- Trim string
function NotesObject:trim(s)
  return s:match'^()%s*$' and '' or s:match'^%s*(.*%S)'
end

-- Scale tools
-- Pitch note is in scale
function NotesObject:isInScale(pitch, keyScaleTypeValues, posKeyInScale)
	local inScale = false
	for key = 1, #keyScaleTypeValues do
		if pitch % 12 == (keyScaleTypeValues[key] + posKeyInScale) % 12 then
			inScale = true
			break
		end
	end
	return inScale
end

-- Key note is in scale
function NotesObject:isKeyInScale(keyPos, keyScaleTypeValues)
	local inScale = false
	-- 0,2,4,5,7,9,11
	for key = 1, #keyScaleTypeValues do
		if keyScaleTypeValues[key] == keyPos then
			inScale = true
			break
		end
	end
	return inScale
end

-- Get next note in scale
function NotesObject:getNextNoteInScale(keyPos, keyScaleTypeValues)
	local nextNote = keyScaleTypeValues[1]
	for key = 1, #keyScaleTypeValues do
		if keyScaleTypeValues[key] > keyPos then
			nextNote = keyScaleTypeValues[key]
			break
		end
	end
	return nextNote
end

-- GetScale in current track
function NotesObject:getScaleTrack(groupsSelected)
	return self:getScale(groupsSelected, "track")
end

-- GetScale in current group
function NotesObject:getScaleGroup(groupsSelected)
	return self:getScale(groupsSelected, "group")
end

-- Get Scale
function NotesObject:getScale(groupsSelected, paramTrack)
	local groupOrTrackNotes = "None"
	local scaleFound = ""
	local notes = {}
	local sep = ""
	local trackinfos = ""

	if paramTrack == "track" then
		-- Use current track
		groupOrTrackNotes = "Track"
		-- Loop through groups in track
		local numGroups = self:getCurrentTrack():getNumGroups()
		local refGroupTrack = nil
		trackinfos = SV:T("Groups") .. " (" .. numGroups .. ")"
		
		for grp = 1, numGroups do
			refGroupTrack = self:getCurrentTrack():getGroupReference(grp)
			self:addNotes(notes, refGroupTrack)
		end
	else
		-- paramTrack == "group"
		-- Groups selected
		if #groupsSelected > 0 then
			groupOrTrackNotes = SV:T("Groups") .. " (" .. #groupsSelected .. ")"
			for _, group in pairs(groupsSelected) do
				self:addNotes(notes, group)
			end
		else
			self:show(SV:T("No group selected!"))
		end
	end
	
	local oldScaleFoundItem = ""
	-- loop each scales
	for key = 1, #self.keyNames do
		local isInScale = false
		local scaleFoundItem = ""
		for j, keyScaleTypeValues in ipairs(self.scales) do
			
			-- Limit scale detection to activated detection
			if keyScaleTypeValues.detection then
				-- Limit to major scales or all activated scales
				if (self.isDetectionMajorScaleOnly and keyScaleTypeValues.name == self.majorScale) 
					or not self.isDetectionMajorScaleOnly then
					
					-- Loop on pitch notes
					isInScale = self:loopNotes(notes, keyScaleTypeValues.val, key - 1)
					if isInScale then
						-- scale found
						scaleFoundItem = scaleFoundItem .. sep .. self.keyNames[key]
						if self.isDetectionMajorScaleOnly then
							if keyScaleTypeValues.name == self.majorScale then
								scaleFoundItem = scaleFoundItem .. " (" .. self:getKeyMajToMinor(self.keyNames[key]) .. ")"
							end
						else
							scaleFoundItem = scaleFoundItem .. " " .. keyScaleTypeValues.name
						end
						sep = self.SEP_KEYS
					end
				end
			end
		end
		if oldScaleFoundItem ~= scaleFoundItem then
			scaleFound = scaleFound .. scaleFoundItem
		end
		oldScaleFoundItem = scaleFoundItem
	end

	return scaleFound
end

-- Append notes from group
function NotesObject:addNotes(notes, refGroup)
	-- Check group type
	if refGroup ~= nil and not refGroup:isInstrumental() then
		local notesGroup = refGroup:getTarget()
		-- Store group notes
		for note = 1, notesGroup:getNumNotes() do
			local pitchNote = notesGroup:getNote(note):getPitch()
			if pitchNote ~= nil then
				table.insert(notes, pitchNote)
			end
		end
	end
end

-- Snap pitch to nearest scale note (for scale-quantize feature)
function NotesObject:snapToScale(pitch, keyScaleTypeValues, posKeyInScale)
	local octave = math.floor(pitch / 12)
	local pitchClass = pitch % 12

	-- Check if already in scale
	if self:isInScale(pitch, keyScaleTypeValues, posKeyInScale) then
		return pitch
	end

	-- Find nearest scale note
	local minDistance = 12
	local nearestPitchClass = pitchClass

	for _, scaleNote in ipairs(keyScaleTypeValues) do
		local scalePitchClass = (scaleNote + posKeyInScale) % 12
		local distance = math.abs(pitchClass - scalePitchClass)

		-- Handle wraparound (e.g., distance from B to C)
		if distance > 6 then
			distance = 12 - distance
		end

		if distance < minDistance then
			minDistance = distance
			nearestPitchClass = scalePitchClass
		end
	end

	return octave * 12 + nearestPitchClass
end

-- Wrap pitch to voice range by octave shifting
-- Keeps the note within minPitch to maxPitch by trying different octaves
function NotesObject:wrapToVoiceRange(pitch, minPitch, maxPitch)
	if minPitch == nil or maxPitch == nil then
		return pitch
	end

	-- If already in range, return as-is
	if pitch >= minPitch and pitch <= maxPitch then
		return pitch
	end

	-- Try shifting by octaves to find best fit
	local bestPitch = pitch
	local minDistance = math.abs(pitch - ((minPitch + maxPitch) / 2))

	for octaveShift = -3, 3 do
		local shiftedPitch = pitch + (octaveShift * 12)

		if shiftedPitch >= minPitch and shiftedPitch <= maxPitch then
			local midpoint = (minPitch + maxPitch) / 2
			local distance = math.abs(shiftedPitch - midpoint)

			if distance < minDistance then
				minDistance = distance
				bestPitch = shiftedPitch
			end
		end
	end

	return bestPitch
end

-- Get new pitch in key scale
function NotesObject:getNewPitch(isFixed, firstNotePitch, notePitch, pitchTarget, posKeyInScale, rotatingData)
	if isFixed then 
		-- Fix all notes from the first note found
		notePitch = firstNotePitch
		
	elseif self.isRotating and rotatingData ~= nil then
	
		-- Rotating chords with new interval object format
		if rotatingData.intervalObj.isChromatic then
			-- Use chromatic semitone transposition
			notePitch = notePitch + pitchTarget

			-- Apply scale quantization if enabled
			if self.isRotatingScaleQuantize then
				notePitch = self:snapToScale(notePitch, self.keyScaleTypeValuesSelected, posKeyInScale - 1)
			end
		else
			-- Use scale-degree transposition (default for rotating chords)
			notePitch = self:getNextKeyInScale(self.keyScaleSelected, notePitch, pitchTarget, posKeyInScale)
		end

		-- Apply voice range wrapping if specified
		notePitch = self:wrapToVoiceRange(notePitch, rotatingData.voiceMinPitch, rotatingData.voiceMaxPitch)
	else
		notePitch = self:getNextKeyInScale(self.keyScaleSelected, notePitch, pitchTarget, posKeyInScale)
	end
	return notePitch
end

-- Calculate scale reflexion axe
function NotesObject:getScaleAxis(scale)
    local first = scale[1]
    local fifth = scale[5] or (first + 7) % 12
    
    -- Axe in midway between tonic & fifth
    local axis = (first + fifth) / 2
    
    return axis
end

-- Get scale from tonic
function NotesObject:getScaleFromTonic(tonicValue, scalePattern)
    local scale = {}
    for i, interval in ipairs(scalePattern) do
        local noteValue = tonicValue + interval
		noteValue = noteValue % 12
        scale[i] = noteValue
    end
    
    return scale
end

-- Get closest note in range
function NotesObject:getClosestNote(firstNegativeNote, notePitchNew)
	local diffMain = {}
	local range = {24, 12, 0, -12, -24}
	local bFirst = true
	local minValue = 0
	local diff = 0
	local gap = 0
	
	-- Create range with gap values
	for i, val in ipairs(range) do
		diff = math.abs(firstNegativeNote - (notePitchNew + val))
		if bFirst then
			minValue = diff
			gap = val
		else
			minValue = math.min(minValue, diff)
			if minValue == diff then
				gap = val
			end
		end
		bFirst = false
	end
	
	return notePitchNew + gap
end

-- Get next valid key in scale
function NotesObject:getNextKeyInScale(keyScaleFound, notePitch, pitchTarget, posKeyInScale)
	local notePitchNew = notePitch 

	-- NOT negative harmony
	if not self.isNegativeHarmony then
		local octave = 0
		local newPitchTarget = 0
		if type(pitchTarget) == "string" then
			newPitchTarget = tonumber(pitchTarget)
		else
			newPitchTarget = pitchTarget
		end
		-- Octave -1
		if newPitchTarget < 0 then
			newPitchTarget = 7 + newPitchTarget
			octave = -12
		end
			
		local gapDegree = self:getShiftDegrees(newPitchTarget, notePitch)
		notePitchNew = notePitch + gapDegree + octave
	else
		-- Negative Harmony
		local scaleFromTonic = self:getScaleFromTonic(posKeyInScale, self.keyScaleTypeValuesSelected)
		
		-- Calculate reflexion axe
		local axis = self:getScaleAxis(scaleFromTonic)
        -- Octave
        local pitchPos = notePitch % 12

		-- Calculate reflexion around axe
        local reflected = 2 * axis - pitchPos
        reflected = math.floor(reflected + 0.5)
		reflected = reflected % 12

		local notePitchNewTemp = notePitch - (notePitch % 12) + reflected
		
		if self.firstNegativeNote == 0 then
			self.firstNegativeNote = notePitchNewTemp
		end

		notePitchNew = self:getClosestNote(self.firstNegativeNote, notePitchNewTemp)
		
	end
	return notePitchNew
end

-- Get shifted degrees
function NotesObject:getShiftDegrees(pitchTarget, notePitch)
	local shift = 0
	local newNotePitch = notePitch

	-- Update notes outer scales
	if self.isUpdateNotesOuterScale then
	
		-- Is in scale
		if not self:isInScale(notePitch, self.keyScaleTypeValuesSelected, self.posKeyInScale -1) then
			local keypos = notePitch % 12 -- Get note
			-- Get next note in scale
			local newKeypos = self:getNextNoteInScale(keypos, self.keyScaleTypeValuesSelected)
			local updateNote = newKeypos - keypos
			-- Update to pitch
			newNotePitch = notePitch + updateNote
			-- shift to scale degree
			shift = shift + updateNote
		end
	end
	
	if pitchTarget > 0 then
		local keyScaleTypeGaps = self:getKeyScaleTypeToGap(self.keyScaleTypeValuesSelected)

		-- shift in scale degree
		local noteKey = self:getKeyFromPitch(newNotePitch)
		local posKeyInScaleKey = self:getKeyPosInKeynames(self.keysInScale, noteKey) -- key pos in degrees (1 to 7)
		
		for key = 1, pitchTarget do
			-- Add all gaps to get shifting note
			local dec = (posKeyInScaleKey + key - 2) % (#self.keyScaleTypeValuesSelected) + 1
			-- {0,2,4,5,7,9,11} => {2, 2, 1, 2, 2, 2, 1}
			--                     {2, 1, 2, 2, 1, 2, 2} "Natural Minor" 
			shift = shift + keyScaleTypeGaps[dec]
		end
	end
	
	return shift
end

-- Get key scale type to gap values
function NotesObject:getKeyScaleTypeToGap(keyScaleTypeValues)
	-- {0,2,4,5,7,9,11} => {2, 2, 1, 2, 2, 2, 1}
	local keyScaleGaps = {}
	
	for iKey = 1, #keyScaleTypeValues do
		local diff = 0
		if iKey + 1 > #keyScaleTypeValues then
			diff = 12 - keyScaleTypeValues[iKey]
		else
			diff = keyScaleTypeValues[iKey + 1] - keyScaleTypeValues[iKey]
		end
		-- 0 + 1 => 2 - 0 = 2
		table.insert(keyScaleGaps, diff)
	end
	return keyScaleGaps
end

-- Get key pitch
function NotesObject:getKeyFromPitch(notePitch)
	local pitchPos = notePitch % 12
	return self.keyNames[pitchPos + 1]
end

-- loop for each notes
function NotesObject:loopNotes(notes, keyScaleTypeValues, posKeyInScale)
	local isInScale = false
	-- loop all notes
	for note = 1, #notes do
		local notePitch = notes[note]
		if notePitch ~= nil then
			isInScale = self:isInScale(notePitch, keyScaleTypeValues, posKeyInScale)
			if not isInScale then
				break
			end
		end
	end
	return isInScale
end

-- Get key position in Keynames
function NotesObject:getKeyPosInKeynames(keyNames, keyfound)
	local posKeyInScale = 1
	-- loop each scales
	for key = 1, #keyNames do
		if keyfound == keyNames[key] then
			posKeyInScale = key
			break
		end
	end
	return posKeyInScale
end

-- Get key scale found from position self.keyScaleChoice
function NotesObject:getkeyScaleChoiceFromPos(scaleKeyPosInput)
	local keyScaleFound = ""
	for iPos = 1, #self.keyScaleChoice do
		if scaleKeyPosInput == iPos -1 then
			keyScaleFound = self.keyScaleChoice[iPos]
		end
	end
	return keyScaleFound
end

-- Get keys in scale
function NotesObject:getKeysInScale(currentKeyNames)
	local keysInScale = {}
	for key = 1, #currentKeyNames do
		if self:isKeyInScale(key - 1, self.keyScaleTypeValuesSelected) then
			table.insert(keysInScale, currentKeyNames[key])
		end
	end
	return keysInScale
end

-- Key tools
-- Get Key from minor to major
function NotesObject:getKeyMinToMaj(key)
	local arrKeys = self.relativeKeys
	
	for iMaj, kMin in pairs(arrKeys) do
		if key == kMin[2] then
			keyResult = kMin[1]
		end
	end	
	return keyResult
end

-- Get Key from major to minor
function NotesObject:getKeyMajToMinor(key)
	local arrKeys = self.relativeKeys
	
	for iMaj, kMin in pairs(arrKeys) do
		if key == kMin[1] then
			keyResult = kMin[2]
		end
	end	
	return keyResult
end

-- Get pitch action from position
function NotesObject:getPitchActionFromPos(pos, harmonyChoice)
	return self.transposition[harmonyChoice][self.transpositionRefData][pos + 1]
end

-- Split string by sep char
function NotesObject:split(str, sep)
	local result = {}
	local regex = ("([^%s]+)"):format(sep)
	for each in str:gmatch(regex) do
		table.insert(result, each)
	end
	return result
end

-- Rotate table content
function NotesObject:shiftTable(tInput, num)
	for iPos = 1, math.abs ( num ) do
		if num < 0 then
			table.insert ( tInput, 1, table.remove ( tInput ) )
		else
			table.insert ( tInput, table.remove ( tInput, 1 ) )
		end
	end
end

-- Duplicate table
function NotesObject:copyTable(tInput)
	local tOutput = {}
	for k, v in pairs(tInput) do
		table.insert(tOutput, k, v)
	end
	return tOutput
end

-- Add log into self.logs
function NotesObject:addLogs(message)
	table.insert(self.logs, message)
	self:addTextPanel(message)
end

-- Display logs into panel
function NotesObject:addLogsInPanel()
	for i = 1, #self.logs do
		self:addTextPanel(self.logs[i])
	end
end

-- Display message box in panel
function NotesObject:addTextPanel(message)
	local old = self.statusTextValue:getValue()
	local sepLine = "\r"
	if #old > 0 then
		message = old .. sepLine .. message
	end
	self.statusTextValue:setValue(message)
end

-- Clear display message in panel
function NotesObject:clearTextPanel()
	self.statusTextValue:setValue("")
end

-- Store error message
function NotesObject:error(message)
	table.insert(self.errorMessages, message)
end

-- Get controls panel
function NotesObject:getControls()
	-- TextArea: Key found 						scaleKeys
	-- ComboBox: Select a key scale				scaleKeyChoice
	-- ComboBox: Key scale type					scaleKeyType
	-- Slider:   Pitch transposition			pitch
	-- ComboBox: Harmony type					harmonyChoice
	-- CheckBox: Update notes outer scale		isUpdateNotesOuterScale
	-- CheckBox: Synchronize unlinked groups	isSynchronizeGroup
	-- CheckBox: Drop notes from DAW			isDropNotesFromDAW
	-- CheckBox: use current track as source	isTrackClone
	-- CheckBox: Update current group only		isUpdateCurrentGroup
	-- TextArea: status text 					statusTextValue
	
	local controls = {
		scaleKeyFound = {						-- TextArea: Key found
			value = SV:create("WidgetValue"),
			defaultValue = "",
			paramKey = "scaleKeyFound"
		},
		isDetectionMajorScaleOnly = {			-- CheckBox: Detection major scale only
			value = SV:create("WidgetValue"),
			defaultValue = true,
			paramKey = "isDetectionMajorScaleOnly"
		},
		scaleKeyChoice = {						-- ComboBox: Select a key scale
			value = SV:create("WidgetValue"),
			defaultValue = 0, -- C
			paramKey = "scaleKeyChoice"
		},
		scaleKeyType = {						-- ComboBox: Key scale type
			value = SV:create("WidgetValue"),
			defaultValue = 0, -- major
			paramKey = "scaleKeyType"
		},
		harmonyChoice = {						-- ComboBox: Harmony type
			value = SV:create("WidgetValue"),
			defaultValue = 0,
			paramKey = "harmonyChoice"
		},
		multiplePitchChoice = {					-- ComboBox: Multiple notes for Harmony type
			value = SV:create("WidgetValue"),
			defaultValue = 0,
			paramKey = "multiplePitchChoice"
		},
		trackChoice = {							-- ComboBox: Destination track
			value = SV:create("WidgetValue"),
			defaultValue = 0, 
			paramKey = "trackChoice"
		},
		pitch = {								-- Slider: Pitch value
			value = SV:create("WidgetValue"),
			defaultValue = 0, 
			paramKey = "pitchChoice"
		},
		transpositionSelected = {				-- TextArea: transposition selected
			value = SV:create("WidgetValue"),
			defaultValue = 0, 
			paramKey = "transpositionSelected"
		},
		isUpdateNotesOuterScale = {				-- CheckBox: Update notes outer scale
			value = SV:create("WidgetValue"),
			defaultValue = true,
			paramKey = "isUpdateNotesOuterScale"
		},
		isSynchronizeGroup = {				-- 	CheckBox: Synchronize unlinked groups
			value = SV:create("WidgetValue"),
			defaultValue = false,
			paramKey = "isSynchronizeGroup"
		},
		isDropNotesFromDAW = {				-- 	CheckBox: Drop notes from DAW
			value = SV:create("WidgetValue"),
			defaultValue = false,
			paramKey = "isDropNotesFromDAW"
		},
		isTrackClone = {						-- CheckBox: Use current track as source
			value = SV:create("WidgetValue"),
			defaultValue = false,
			paramKey = "isTrackClone"
		},
		isUpdateCurrentGroup = {				-- CheckBox: Update current group of notes
			value = SV:create("WidgetValue"),
			defaultValue = false,
			paramKey = "isUpdateCurrentGroup"
		},
		rotatingPresetChoice = {				-- ComboBox: Rotating pattern preset
			value = SV:create("WidgetValue"),
			defaultValue = 0,
			paramKey = "rotatingPresetChoice"
		},
		rotatingCustomInput = {					-- TextArea: Custom rotating pattern input
			value = SV:create("WidgetValue"),
			defaultValue = "",
			paramKey = "rotatingCustomInput"
		},
		isRotatingScaleQuantize = {			-- CheckBox: Scale-quantize rotating chords
			value = SV:create("WidgetValue"),
			defaultValue = false,
			paramKey = "isRotatingScaleQuantize"
		},
		isRotatingScaleSteps = {			-- CheckBox: Use scale steps for rotating chords
			value = SV:create("WidgetValue"),
			defaultValue = true,
			paramKey = "isRotatingScaleSteps"
		}
	}
	return controls
end

-- Initialize widget values
function NotesObject:initializeControlsValues()
	-- Initialize widget values
	for key, control in pairs(self.controls) do
		control.value:setValue(control.defaultValue)
	end
end

-- Set controls callback (TODO)
function NotesObject:setControlsCallback()
	for key, control in pairs(self.controls) do
		control.value:setValueChangeCallback(function()
				-- self:addLogsInPanel()

				if control.paramKey == "isDetectionMajorScaleOnly" then
					self.isDetectionMajorScaleOnly = self.controls.isDetectionMajorScaleOnly.value:getValue()
				end
				
				if control.paramKey == "pitchChoice" then
					self.pitchSelectedType = control.paramKey
					self.pitchSelected = string.format("%i", self.controls.pitch.value:getValue())
					
					-- Display SV:T("Selected") .. ": " .. pitchSelected
					self.controls.transpositionSelected.value:setValue(self.pitchSelectedLabel 
						.. string.format("%i", self.pitchSelected))
					
					-- Reset harmonyChoice value because user select "pitch" only "one note" for harmonyChoice
					self.controls.harmonyChoice.value:setValue(0)
					self.controls.multiplePitchChoice.value:setValue(0)
					self.displayMultiplePitchChoice = false
					SV:refreshSidePanel()
				end
				
				if control.paramKey == "harmonyChoice" then
					self.pitchSelectedType = control.paramKey
					self.transpositionSelected = self.controls.harmonyChoice.value:getValue() + 1
					-- {SV:T("1 note"),  8, {}},
					if self.transpositionSelected == 1 then
						self.pitchSelected = string.format("%i", self.controls.pitch.value:getValue())
					else
						self.pitchSelected = self.transposition[self.transpositionSelected][self.transpositionRefData][1]
					end

					-- Reset simple transposition value because user select "harmonyChoice" double notes
					self.controls.pitch.value:setValue(0)
					-- self.controls.rotatingPresetChoice.value:setValue(self.rotatingPresetSelected - 1)

					if self.pitchSelected == "Fixed" or self.transpositionSelected == 1 
						or self.pitchSelected == "Negative" or self.pitchSelected == "Rotating" then
						self.displayMultiplePitchChoice = false
					else
						-- Add new ComboBox for multiple pitch choice
						self.displayMultiplePitchChoice = true
					end
					self.controls.multiplePitchChoice.value:setValue(0)
					self.controls.transpositionSelected.value:setValue(self.pitchSelectedLabel .. self.pitchSelected)
					SV:refreshSidePanel()
				end
				
				if control.paramKey == "multiplePitchChoice" then
					self.pitchSelectedType = control.paramKey
					local transpositionSelected = self.controls.multiplePitchChoice.value:getValue() + 1
					self.pitchSelected = self.transposition[self.transpositionSelected][self.transpositionRefData][transpositionSelected]
					-- Display SV:T("Selected") .. ": " .. pitchSelected
					self.controls.transpositionSelected.value:setValue(self.pitchSelectedLabel .. self.pitchSelected)
					
					-- Reset simple transposition value because user select "harmonyChoice" double notes
					self.controls.pitch.value:setValue(0)
				end
				
				if control.paramKey == "scaleKeyType" then
					self.keyScaleTypeSelected = self.controls.scaleKeyType.value:getValue() + 1
				end
				
				if control.paramKey == "isSynchronizeGroup" then
					self.isSynchronizeGroup = self.controls.isSynchronizeGroup.value:getValue()
					self.numTracks = self:getProject():getNumTracks()
					
					if self.isSynchronizeGroup then
						self:getProject():newUndoRecord()
						self:setGroupSource()

						if self.groupSource == nil then
							self.isSynchronizeGroup = false
							self.controls.isSynchronizeGroup.value:setValue(self.isSynchronizeGroup)
							self:show(SV:T("Select a group first (only one)!"))
						else							
							self.initialTrack = self:getCurrentTrack()
							self.initialTrackName = self.initialTrack:getName()
							self:displayMessage(SV:T("Synchronize unlinked groups") .. "...")
							self.resultDebug = ""
							SV:setTimeout(100, function() self:loopSynchronize() end)
						end
					else
						if self.initialTrack ~= nil then
							self.initialTrack:setName(self.initialTrackName)
						end
						self:displayMessage(self.defaultLabelInfoText .. "...")
						self.applyButtonText = SV:T("Apply")
					end
					SV:refreshSidePanel()
				end
				
				if control.paramKey == "isDropNotesFromDAW" then
					self.isDropNotesFromDAW = self.controls.isDropNotesFromDAW.value:getValue()
					self.isSynchronizeGroup = false
					self.numTracks = self:getProject():getNumTracks()

					if self.isDropNotesFromDAW then
						self:getProject():newUndoRecord()
						self.trackTarget = self:getCurrentTrack()
						self.stopProcess = false
						self.initialTrackName = self.trackTarget:getName()
						SV:setTimeout(100, function() self:loopDropNotesFromDAW() end)
					else
						self.stopProcess = true
						self:refreshAfterDropNotesFromDAWPanel(self.isDropNotesFromDAW)
					end
					SV:refreshSidePanel()
				end
				
				if control.paramKey == "isUpdateCurrentGroup" then
					self.isSynchronizeGroup = false
					self.isDropNotesFromDAW = false
					self.controls.harmonyChoice.value:setValue(0)
					self.controls.multiplePitchChoice.value:setValue(0)
					self.pitchSelected = string.format("%i", self.controls.pitch.value:getValue())
					self.controls.transpositionSelected.value:setValue(self.pitchSelectedLabel .. self.pitchSelected)
					self.controls.isSynchronizeGroup.value:setValue(self.isSynchronizeGroup)
					self.isUpdateCurrentGroup = self.controls.isUpdateCurrentGroup.value:getValue()
					self:addTextPanel(self.infosToDisplay)
					
					if self.isUpdateCurrentGroup then
						self:getProject():newUndoRecord()
						self:displayMessage(SV:T("Update notes in selected scale") .. "...")
						self.applyButtonText = SV:T("Update notes in selected scale")
					else
						self:displayMessage(self.defaultLabelInfoText .. "...")
						self.applyButtonText = SV:T("Apply")
					end
					SV:refreshSidePanel()
				end

				if control.paramKey == "rotatingPresetChoice" then
					self.rotatingPresetSelected = self.controls.rotatingPresetChoice.value:getValue() + 1
					local preset = self.rotatingPresets[self.rotatingPresetSelected]

					-- Get pattern text from preset
					local patternText = preset.pattern

					-- Parse pattern to new format
					self.rotatingIntervals = self:parseRotatingPattern(patternText)
					self.rotatingCustomPattern = patternText

					-- Update custom input text to show the current preset
					self.controls.rotatingCustomInput.value:setValue(patternText)
				end

				if control.paramKey == "rotatingCustomInput" then
					local customPattern = self.controls.rotatingCustomInput.value:getValue()
					local parsed = self:parseRotatingPattern(customPattern)
					if parsed ~= nil then
						self.rotatingIntervals = parsed
						self.rotatingCustomPattern = customPattern
					end
				end

				if control.paramKey == "isRotatingScaleQuantize" then
					self.isRotatingScaleQuantize = self.controls.isRotatingScaleQuantize.value:getValue()
				end
				if control.paramKey == "isRotatingScaleSteps" then
					self.isRotatingScaleSteps = self.controls.isRotatingScaleSteps.value:getValue()
				end

			end
		)
	end
end

-- Get group reference in time position
function NotesObject:getGroupRefBlicks(track, blicksPos)
	local groupRefFound = nil
	local numGroups = track:getNumGroups()
	
	-- All groups 
	for iGroup = 1, numGroups do
		local groupRef = track:getGroupReference(iGroup)
		if not groupRef:isInstrumental() then
			local blickSeconds = self:secondsToClock(self:getTimeAxis():getSecondsFromBlick(groupRef:getOnset()))
			
			-- Get group on timing pos
			if blicksPos >= groupRef:getOnset() and blicksPos <= groupRef:getEnd() then
				groupRefFound = groupRef
				break
			end
		end						
	end						
	return groupRefFound
end

-- Get group reference in time position
function NotesObject:getGroupRefTime(track, time)
	local groupRefFound = nil
	local numGroups = track:getNumGroups()
	local blicksPos = self:getTimeAxis():getBlickFromSeconds(time)
	
	-- All groups 
	for iGroup = 1, numGroups do
		local groupRef = track:getGroupReference(iGroup)
		if not groupRef:isInstrumental() then
			local blickSeconds = self:secondsToClock(self:getTimeAxis():getSecondsFromBlick(groupRef:getOnset()))
			
			-- Get group on timing pos
			if blicksPos >= groupRef:getOnset() and blicksPos <= groupRef:getEnd() then
				groupRefFound = groupRef
				break
			end
		end						
	end						
	return groupRefFound
end

-- Set button apply control callback
function NotesObject:setButtonApplyControlCallback()

	-- Button create harmony
	self.applyButtonValue:setValueChangeCallback(function()
			self:getProject():newUndoRecord()
			self.resultDebug = ""

			self.groupsSelected = self:getSelectedGroups()
			
			if #self.groupsSelected > 0 then
				self.posKeyInScaleForm = self.controls.scaleKeyChoice.value:getValue()

				self.isTrackClone = self.controls.isTrackClone.value:getValue()
				self.isUpdateCurrentGroup = self.controls.isUpdateCurrentGroup.value:getValue()
				self.isUpdateNotesOuterScale = self.controls.isUpdateNotesOuterScale.value:getValue()
				self.isSynchronizeGroup = self.controls.isSynchronizeGroup.value:getValue()
				
				local keysInfos = self:getGroupKeyScale()
				
				-- Get user selected scale
				self:getScaleSelected()
				
				-- Duplicate note groups & create tracks
				local numGroups = self:duplicateNotes(self.groupsSelected)
				
				if self.debug then SV:setHostClipboard(self.resultDebug) end
			else
				-- No group selected
				self.controls.scaleKeyFound.value:setValue(self.defaultKeyFoundMessage)
				self:show(self.defaultKeyFoundMessage)
			end
		end
	)
end

-- Set button Generate group control callback
function NotesObject:setButtonGenerateGroupControlCallback()

	-- Button generate group harmony
	self.generateGroupButtonValue:setValueChangeCallback(function()
			self:getProject():newUndoRecord()

			self.posKeyInScaleForm = self.controls.scaleKeyChoice.value:getValue()
			self.isTrackClone = self.controls.isTrackClone.value:getValue()
			self.isUpdateCurrentGroup = self.controls.isUpdateCurrentGroup.value:getValue()
			
			local keysInfos = self:getGroupKeyScale()
			-- Get user selected scale
			self:getScaleSelected()
			
			-- Generate group for testing purpose
			local numGroups = self:generateGroupForTestOnly()
			
		end
	)
end

-- Display message
function NotesObject:displayMessage(message)
	self:clearTextPanel()
	self:addTextPanel(self.infosToDisplay)
	self:addTextPanel(message)
end
	
-- Get combo box data
function NotesObject:getComboLists()
	self.scalesList = {}
	
	-- scales list
	for key, scale in ipairs(self.scales) do
		table.insert(self.scalesList, scale.name)
	end
end

-- Display error messages
function NotesObject:displayErrors()
	local result = ""
	if #self.errorMessages > 0 then
		for _, m in pairs(self.errorMessages) do
			result = result .. m .. "\r"
		end
	end
	return result
end

-- Get new color
function NotesObject:getNewColor(track)
	if self.currentColorPos == 0 then 
		self.currentColorPos = self:getCurrentColorPos(track)
	end
	self.currentColorPos = self.currentColorPos + 1
	if self.currentColorPos > #self.colors then
		self.currentColorPos = 1
	end
	return self.colors[self.currentColorPos].val
end

-- Get current color position
function NotesObject:getCurrentColorPos(track)
	local newPos = 1
	for i, color in ipairs(self.colors) do
		if color.val == track:getDisplayColor() then
			newPos = i
			break
		end
	end	
	return newPos
end

-- Get colors
function NotesObject:getColors()
	local colors = {}
	table.insert(colors, {val = "ffd14f5b", name = "red"})
	table.insert(colors, {val = "ffc27455", name = "orange"})
	table.insert(colors, {val = "ffc27455", name = "ocher"})
	table.insert(colors, {val = "ffd6bc43", name = "yellow"})
	table.insert(colors, {val = "ff7db235", name = "green"})
	table.insert(colors, {val = "ff3bb26c", name = "greenish"})
	table.insert(colors, {val = "ff3eb2a8", name = "blue-sky"})
	table.insert(colors, {val = "ff4794cb", name = "blue"})
	table.insert(colors, {val = "ff5478c7", name = "turquoise"})
	table.insert(colors, {val = "ff6959d4", name = "purple"})
	table.insert(colors, {val = "ffb853b3", name = "pink"})
	return colors
end

-- loop synchronize groups
function NotesObject:loopSynchronize()

	if not self.isSynchronizeGroup then
		-- Stop loop
		-- if #self.resultDebug > 0 then
			-- SV:setHostClipboard(self.resultDebug)
			-- self:show(#self.resultDebug)
		-- end
		self.initialTrack:setName(self.initialTrackName)
		self:refreshAfterSynchroPanel(self.isSynchronizeGroup)
	else
		-- if a track is deleted by another script or action
		if self.numTracks < self:getProject():getNumTracks() or not self:isSameGroupSourceNotesCount() then
			-- Stop loop
			self.isSynchronizeGroup = false
			self:refreshAfterSynchroPanel(self.isSynchronizeGroup)
		else
			self.processing = self.processing  + 1
			if self.processing > 4 then
				self.processing = 0
			end
			local followString = string.rep(".", self.processing)
			self:displayMessage(SV:T("Synchronize unlinked groups") .. followString)
			local targetName = followString .. " " .. self.initialTrackName
			self.initialTrack:setName(targetName)
		
			-- Find current group
			self:scanTracks()

			SV:setTimeout(400, function() self:loopSynchronize() end)
		end			
	end	
end

-- loop drop notes from DAW
function NotesObject:loopDropNotesFromDAW()

	if self.stopProcess then
		-- self:show("cause: " .. cause)
		self.isDropNotesFromDAW = false
		self.controls.isDropNotesFromDAW.value:setValue(self.isDropNotesFromDAW)
		self:refreshAfterDropNotesFromDAWPanel(self.isDropNotesFromDAW)
	else
		-- if a new same script instance is running or track is deleted by another script
		if self.numTracks > self:getProject():getNumTracks() then
			self.stopProcess = true
			self.isDropNotesFromDAW = false
			self.controls.isDropNotesFromDAW.value:setValue(self.isDropNotesFromDAW)
			self:refreshAfterDropNotesFromDAWPanel(self.isDropNotesFromDAW)
		else
			-- Scan a new track
			self:scanNewTrack()
			
			if not self.stopProcess then
				SV:setTimeout(500, function() self:loopDropNotesFromDAW() end)
			else
				-- if #self.resultDebug > 0 then
					-- SV:setHostClipboard(self.resultDebug)
					-- -- self:show(#self.resultDebug)
				-- end
				self.isDropNotesFromDAW = false
				self.controls.isDropNotesFromDAW.value:setValue(self.isDropNotesFromDAW)
				self.stopProcess = true
				self:refreshAfterDropNotesFromDAWPanel(self.isDropNotesFromDAW)
			end
		end
	end	
end

-- Set track name waiting
function NotesObject:setTrackNameWaiting()
	if self.trackTarget ~= nil then
		self.processing = self.processing  + 1
		if self.processing > 4 then
			self.processing = 0
		end
		local followString = string.rep(".", self.processing)
		local targetName = followString .. " " .. self.initialTrackName
		
		if self.isDropNotesFromDAW then
			self.trackTarget:setName(targetName)
			self:displayMessage(SV:T("Drop notes from DAW") .. followString)
		else
			self:displayMessage(self.defaultLabelInfoText .. "...")
			self:setTrackTarget()
		end
	end
end

-- Scan a new track
function NotesObject:scanNewTrack()

	SV:setTimeout(100, function() self:setTrackNameWaiting() end)
	self.currentSeconds = SV:getPlayback():getPlayhead()
	local secondsInfo = self:secondsToClock(self.currentSeconds)
	
	-- Check if a new track is created
	if self.numTracks < self:getProject():getNumTracks() then
		self.newDAWTrack = self:getLastTrack()
		local numNotesNewDAWTrack = self:getTrackNumNotes(self.newDAWTrack)
		
		if numNotesNewDAWTrack > 0 then
			
			local newStartPosition = self:getTimeAxis():getBlickFromSeconds(self.currentSeconds)
			local measureBlick = self:getFirstMesure(newStartPosition, 0)

			-- New notes => Create a new group
			self:createGroup(measureBlick, self.currentSeconds)
			
			self:removeTrackDAW()
			self.isDropNotesFromDAW = false
			self.stopProcess = true -- End of process
			self.stopProcessOK = true -- End of process OK
			self:setTrackTarget()
		else
			-- a new track is created with no notes
		end
	end
end

-- Remove track DAW
function NotesObject:removeTrackDAW()
	if self.newDAWTrack ~= nil then
		self:getProject():removeTrack(self.newDAWTrack:getIndexInParent())
		self.newDAWTrack = nil
	end
end

--- Get last created track
function NotesObject:getLastTrack()
	return self:getProject():getTrack(self:getProject():getNumTracks())
end

-- Get track notes count
function NotesObject:getTrackNumNotes(track)
	local numNotes = 0
	for iGroupNote = 1, track:getNumGroups() do
		local groupRef = track:getGroupReference(iGroupNote)
		local group = groupRef:getTarget()
		numNotes = numNotes + group:getNumNotes()
	end
	return numNotes
end

-- Create group for new track with new notes
function NotesObject:createGroup(startPosition, targetPosition)
	local maxLengthResult = 30
	local groupRefMain = self.newDAWTrack:getGroupReference(self.newDAWTrack:getNumGroups())
	local durationGroupRefMain = groupRefMain:getDuration()
	local groupNotesMain = groupRefMain:getTarget()
	local isChordsGroup = false
	local mainGroupNotes = {}
	
	local iGroup = 1
	self.THRESHOLD = self:getMaxTimeGapFromBPM(targetPosition) -- 41505882 = 0.06 seconds
	local previousNote = nil

	-- Save notes to groups
	for iNote = 1, groupNotesMain:getNumNotes() do
		local note = groupNotesMain:getNote(iNote)
		if previousNote ~= nil then
			if note:getOnset() == previousNote:getOnset() then
				isChordsGroup = true
				iGroup = iGroup + 1
			else
				iGroup = 1
			end
		end
		if mainGroupNotes[iGroup] == nil then
			mainGroupNotes[iGroup] = {}
		end
		table.insert(mainGroupNotes[iGroup], note)
		previousNote = groupNotesMain:getNote(iNote)
	end
	
	if #mainGroupNotes > 0 then
		for iGroup, group in ipairs(mainGroupNotes) do
			-- Create new group 
			local noteGroup = SV:create("NoteGroup")
			local newGrouptRef = SV:create("NoteGroupReference")
				
			self:getProject():addNoteGroup(noteGroup)
			newGrouptRef:setTarget(noteGroup)
			newGrouptRef:setTimeOffset(startPosition)
			newGrouptRef:setTimeRange(startPosition, durationGroupRefMain) -- v2.1.1
			
			if iGroup == 1 then
				self.trackTarget:addGroupReference(newGrouptRef)
			else
				trackName = self.initialTrackName .. "-" .. iGroup
				if self.isTrackClone then
					-- Clone track for new groups
					local track = self:cloneTrackReference(self.trackTarget, trackName)
					track:addGroupReference(newGrouptRef)
				else
					local track = self:createTrackTarget(trackName)
					track:addGroupReference(newGrouptRef)
				end
			end

			local previousNote = nil
			for iNote = 1, #group do
				local note = group[iNote]:clone()
				-- Update position within the new group
				note:setOnset(group[iNote]:getOnset())
				
				if self.linkNotesActive then
					if previousNote ~= nil then
						self:linkedTheNotes(previousNote, note, noteGroup:getNote(iNote - 1))
					end
				end
				
				noteGroup:addNote(note)
				previousNote = note
			end
			
			local resultLyrics = self:renameOneGroup(self:getTimeAxis(), maxLengthResult, noteGroup)
		end
	end
	
	return true
end

-- Linked the notes
function NotesObject:linkedTheNotes(previousNote, note, storedNote)
	local gapNotes = previousNote:getEnd() - note:getOnset()
	-- SIL = 29400000 => 0.02s
	-- if iNote == 2 then 
		-- self:show("gapNotes: " .. gapNotes .. ", " 
		-- .. self.timeAxis:getSecondsFromBlick(gapNotes))
	-- end
	
	-- Notes overlay
	if gapNotes > 0 then
	-- if previousNote:getEnd() > note:getOnset() then
		-- Reduce previous note duration
		storedNote:setDuration(previousNote:getDuration() - gapNotes)
	end
				
	-- SIL = short time between notes
	if gapNotes < 0 and math.abs(gapNotes) < self.THRESHOLD then
		-- Spread previous note duration
		storedNote:setDuration(previousNote:getDuration() + math.abs(gapNotes))
	end
end

-- Rename one group
function NotesObject:renameOneGroup(timeAxis, maxLengthResult, noteGroup)
	local resultLyrics = ""
	local groupName = noteGroup:getName()
	local notesCount = noteGroup:getNumNotes()

	if notesCount > 0 then
		local lyricsLine = ""
		local sep = ""

		for i = 1, notesCount do
			local infos = ""
			local note = noteGroup:getNote(i)
			
			if note ~= nil then
				local lyrics = note:getLyrics()
				if string.len(lyrics) > 0 then
				
					-- Filter char '+' & '-' & 'br' & .cl & .pau & .sil
					if self:isTextAccepted(timeAxis, note) then
						-- Replace following note char '-'
						if lyrics == "-" then lyrics = ".." end 
						-- Add lyrics for each note
						lyricsLine = lyricsLine .. sep .. lyrics
						sep = " "
					end				  
				end
			end
		end

		-- Add lyrics
		resultLyrics = self:limitStringLength(lyricsLine, maxLengthResult)
		-- Update if new lyrics only
				if string.len(resultLyrics)> 0 and
			noteGroup:getName() ~= resultLyrics then
			noteGroup:setName(resultLyrics)
		end
	end

	return resultLyrics
end

-- Limit string max length
function NotesObject:limitStringLength(resultLyrics, maxLengthResult)
	-- Limit string max length
	if string.len(resultLyrics) > maxLengthResult then
		local posStringChar = string.find(resultLyrics," ", maxLengthResult - 10)
		if posStringChar == nil then posStringChar = maxLengthResult end
		resultLyrics = string.sub(resultLyrics, 1, posStringChar)
	end
	return resultLyrics
end

-- Is lyrics is a text accepted new
function NotesObject:isTextAcceptedNew(lyrics)
	local result = true
	
	-- Filter char '+' & '++' & '-' & 'br' & .cl & .pau & .sil
	for i, lyricsExcept in pairs(self.lyricsException) do
		if  lyrics == lyricsExcept then
			result = false
			break
		end
	end

	return result
end

-- Is lyrics is a text accepted
function NotesObject:isTextAccepted(timeAxis, note)
	local result = false
	local lyrics = note:getLyrics()
	
	if self:isTextAcceptedNew(lyrics) then
		result = true
	end
	
	-- Specific for personal vocal effect
	if lyrics == "a" and self:isLyricsEffect(timeAxis, note) then
		result = false
	end

	return result
end

-- Get time max gap between notes
function NotesObject:getMaxTimeGapFromBPM(positionSeconds)
	local THRESHOLDBlicks = self.THRESHOLD
	local coef = 17 -- Convert 1/quarterBlicks to 0.03 seconds (120)
	local bpm = self:getProjectTempo(positionSeconds)
	
	if bpm ~= nil then
		-- "120:" time: 0.03s, 1s: blicks 1411200000 quarter 2
		-- "60: " time: 0.06s, 1s: blicks 705600000 quarter 1
		local blicks = SV:seconds2Blick(1, bpm) -- get blicks 1 second with bpm
		local quarterBlicks = SV:blick2Quarter(blicks)
		local gapMax = (1/quarterBlicks) / coef  -- result gap in seconds
		THRESHOLDBlicks = self:getTimeAxis():getBlickFromSeconds(gapMax)
	end
	return THRESHOLDBlicks
end

-- Get current project tempo
function NotesObject:getProjectTempo(seconds)
	local tempoActive = 120
	local blicks = self:getTimeAxis():getBlickFromSeconds(seconds)
	local tempoMarks = self:getTimeAxis():getAllTempoMarks()
	for iTempo = 1, #tempoMarks do
		local tempoMark = tempoMarks[iTempo]
		if tempoMark ~= nil and blicks >= tempoMark.position then
			tempoActive = tempoMark.bpm
		end
	end
	return math.floor(tempoActive)
end

-- Set track target
function NotesObject:setTrackTarget()
	if self.trackTarget ~= nil then
		self.trackTarget:setName(self.initialTrackName)
	end
end

-- Refresh after synchro panel
function NotesObject:refreshAfterSynchroPanel(value)
	self.controls.isSynchronizeGroup.value:setValue(value)
	if not value then
		self:displayMessage(self.defaultLabelInfoText .. "...")
	else
		self:displayMessage(SV:T("Synchronize unlinked groups") .. "...")
	end
	SV:refreshSidePanel()
end

-- Refresh after drop notes from DAW panel
function NotesObject:refreshAfterDropNotesFromDAWPanel(value)	
	if value then
		self:displayMessage(SV:T("Drop notes from DAW") .. "...")
	else
		self:displayMessage(self.defaultLabelInfoText .. "...")
		self:setTrackTarget()
	end
	SV:refreshSidePanel()
end

-- Check if notes count is updated
function NotesObject:isSameGroupSourceNotesCount()
	return self.groupSourceNumNotes == self.groupSource:getTarget():getNumNotes()
end

-- Scan tracks
function NotesObject:scanTracks()
	local currentTargetGroup = self.groupSource:getTarget()

	-- Find current group
	for iTrack = 1, self.numTracks do
		-- Find all tracks except the current one
		if iTrack ~= self.currentTrackNumber then
			local track = self:getProject():getTrack(iTrack)
			local groupRefTrack = self:getGroupRefBlicks(track, self.groupSource:getOnset())
			
			if groupRefTrack ~= nil then
				local targetGroup = groupRefTrack:getTarget()

				-- Only target groups not synchronized by copy/paste
				if targetGroup:getUUID() ~= currentTargetGroup:getUUID() then
					-- Same group to synchronize
					local isSimilarGroupFound = self:isSameGroup(groupRefTrack)
					if isSimilarGroupFound then
						local groupNotesModified = self:setNotSimilarNotes(targetGroup, iTrack)						
					 end
				end
			end
		end
	end
end

-- Check same groups
function NotesObject:isSameGroup(groupRef)
	local result = false
	if groupRef:getTarget():getNumNotes() == self.groupSource:getTarget():getNumNotes() then
		result = true
	end
	return result
end

-- get group lyrics
function NotesObject:getGroupLyrics(group)
	local lyrics = ""
	for iNote = 1, group:getNumNotes() do
		lyrics = lyrics .. group:getNote(iNote):getLyrics() .. " "
	end
	return lyrics
end

-- Set not similar notes in target group
function NotesObject:setNotSimilarNotes(group, iTrack)
	local targetGroupNotes = {}
	local currentTargetGroup = self.groupSource:getTarget()
	
	for iNote = 1, group:getNumNotes() do
		local noteDiff = false
		if group:getNote(iNote):getOnset() ~= currentTargetGroup:getNote(iNote):getOnset() then
			noteDiff = true
			group:getNote(iNote):setOnset(currentTargetGroup:getNote(iNote):getOnset())
		end
		if group:getNote(iNote):getEnd() ~= currentTargetGroup:getNote(iNote):getEnd() then
			noteDiff = true
			group:getNote(iNote):setDuration(currentTargetGroup:getNote(iNote):getDuration())
		end
		if group:getNote(iNote):getLyrics() ~= currentTargetGroup:getNote(iNote):getLyrics() then
			noteDiff = true
			group:getNote(iNote):setLyrics(currentTargetGroup:getNote(iNote):getLyrics())
		end
		if group:getNote(iNote):getPhonemes() ~= currentTargetGroup:getNote(iNote):getPhonemes() then
			noteDiff = true
			group:getNote(iNote):setPhonemes(currentTargetGroup:getNote(iNote):getPhonemes())
		end
		if noteDiff then
			table.insert(targetGroupNotes, group:getNote(iNote))
		end
	end
	return targetGroupNotes
end

-- Create user input form
function NotesObject:getSectionContainer()
	local scaleKeyType = {}
	local pitchMinValue = -7
	local pitchMaxValue = 7
	local pitchInterval = 1
	local trackClone = {}
	local updateNotesOuter = {}
	local synchroGroups = {}
	local multiplePitchChoice = {}
	local harmonyChoice = {}
	local pitchChoice = {}
	local trackTest = {}
	local applyButton = {}
	local transpositionSelected = {} 
	local scaleKeyChoice = {}	
	local updateCurrentGroup = {}
	local labelAction = {}
	local labelSynchroGroups = {}
	local dropFromDAW = {}
	local labelDropFromDAW = {}
	local rotatingPresetChoice = {}
	local rotatingCustomInput = {}
	local rotatingScaleQuantize = {}
	local rotatingScaleSteps = {}
	local rotatingLabel = {}

	self.controls.isTrackClone.value:setValue(self.isCurrentVoiceTrack)
	self.controls.isUpdateNotesOuterScale.value:setValue(self.isUpdateNotesOuterScale)
	self.controls.isSynchronizeGroup.value:setValue(self.isSynchronizeGroup)
	self.controls.scaleKeyFound.value:setValue(self.defaultKeyFoundMessage)
	self.controls.isDetectionMajorScaleOnly.value:setValue(self.isDetectionMajorScaleOnly)
	self.controls.isUpdateCurrentGroup.value:setValue(self.isUpdateCurrentGroup)
	-- Rotating
	self.controls.rotatingPresetChoice.value:setValue(self.rotatingPresetSelected - 1)
	self.controls.rotatingCustomInput.value:setValue(self.rotatingCustomPattern)
	self.controls.isRotatingScaleQuantize.value:setValue(self.isRotatingScaleQuantize)
	self.controls.isRotatingScaleSteps.value:setValue(self.isRotatingScaleSteps)

	-- TextArea: Key found 						scaleKeys
	-- ComboBox: Select a key scale				scaleKeyChoice
	-- ComboBox: Key scale type					scaleKeyType
	-- Slider:   Pitch transposition			pitch
	-- ComboBox: Harmony type					harmonyChoice
	-- CheckBox: use current track as source	isTrackClone
	-- CheckBox: Update gurrent Group			isUpdateCurrentGroup
	-- button:   apply							applyButtonValue
	-- button:   generate group					generateGroupButtonValue
	-- TextArea: status text 					statusTextValue
	
	if not self.isUpdateCurrentGroup and not self.isDropNotesFromDAW then
		labelSynchroGroups = 
			{
				type = "Label",
				text = SV:T("Action2: Synchronize groups"),
			}
	end
	
	if not self.isUpdateCurrentGroup and not self.isSynchronizeGroup then
		labelDropFromDAW = 
			{
				type = "Label",
				text = SV:T("Action3: Drop from DAW"),
			}
	end
	
	local scaleKeyFound =
		{
			type = "Container",
			columns = {
				{
					type = "TextArea",
					value = self.controls.scaleKeyFound.value,
					height = 100,
					width = 1.0,
					readOnly = true
				}
			}
		}

	local detectionLimited = 
		{
			type = "Container",
			columns = {
				{
				type = "CheckBox",
				text = SV:T("Major scales only detection"),
				value = self.controls.isDetectionMajorScaleOnly.value,
				width = 1.0
				}
			}
		}

	if not self.isSynchronizeGroup and not self.isDropNotesFromDAW then
		labelAction = {
				type = "Label",
				text = SV:T("Action1: Select a scale and type"),
			}

		scaleKeyChoice = 
			{
				type = "Container",
				columns = {
					{
						type = "ComboBox",
						text = SV:T("Select a key scale"),
						value = self.controls.scaleKeyChoice.value,
						choices = self.keyScaleChoice,
						width = 0.3
					},
					{
						type = "ComboBox",
						text = SV:T("Key scale type"),
						value = self.controls.scaleKeyType.value,
						choices = self.scalesList,
						width = 0.7
					}
				}
			}
		updateCurrentGroup = 
			{
				type = "Container",
				columns = {
					{
					type = "CheckBox",
					text = SV:T("Update scale selected groups"),
					value = self.controls.isUpdateCurrentGroup.value,
					width = 1.0
					}
				}
			}
			
		transpositionSelected = {
				type = "Container",
				columns = {
					{
						type = "TextArea",
						value = self.controls.transpositionSelected.value,
						height = 20,
						width = 1.0,
						readOnly = false
					}
				}
			}
		pitchChoice = 
			{
				type = "Container",
				columns = {
					{
						type = "Slider",
						text = SV:T("Transpose (-7 to +7)"),
						format = "%3.0f pitch",
						minValue = pitchMinValue, 
						maxValue = pitchMaxValue, 
						interval = pitchInterval,
						value = self.controls.pitch.value,
						width = 1.0
					}
				}
			}
		applyButton = {
				type = "Container",
				columns = {
					{
						type = "Button",
						text = self.applyButtonText,
						width = 1.0,
						value = self.applyButtonValue
					}
				}
			}
	end
	
	if self.isUpdateCurrentGroup then
		self.controls.harmonyChoice.value:setValue(0)
		self.pitchSelected = string.format("%i", self.controls.pitch.value:getValue())
		self.controls.transpositionSelected.value:setValue(self.pitchSelectedLabel .. self.pitchSelected)
		self.controls.multiplePitchChoice.value:setValue(0)
		self.displayMultiplePitchChoice = false
		self.isUpdateNotesOuterScale = true
		self.controls.isUpdateNotesOuterScale.value:setValue(self.isUpdateNotesOuterScale)
		self.isSynchronizeGroup = false
		self.controls.isSynchronizeGroup.value:setValue(self.isSynchronizeGroup)
	end

	if not self.isUpdateCurrentGroup and not self.isSynchronizeGroup and not self.isDropNotesFromDAW then
		trackClone = 
			{
				type = "Container",
				columns = {
					{
					type = "CheckBox",
					text = SV:T("Get current voice for new tracks"),
					value = self.controls.isTrackClone.value,
					width = 1.0
					}
				}
			}
		if self.pitchSelected ~= "Rotating" then
			updateNotesOuter = 
				{
					type = "Container",
					columns = {
						{
						type = "CheckBox",
						text = SV:T("Update notes outer scale"),
						value = self.controls.isUpdateNotesOuterScale.value,
						width = 1.0
						}
					}
				}
		end
		
		harmonyChoice = 
			{
				type = "Container",
				columns = {
					{
						type = "ComboBox",
						text = SV:T("Harmony type"),
						value = self.controls.harmonyChoice.value,
						choices = self.harmonyList,
						width = 1.0
					}
				}
			}
	end

	-- Show rotating controls when "Rotating" harmony type is selected
	if self.pitchSelected == "Rotating" and not self.isUpdateCurrentGroup and not self.isSynchronizeGroup and not self.isDropNotesFromDAW  then
		rotatingLabel = {
			type = "Label",
			text = "Rotating Chord Patterns",
		}

		rotatingPresetChoice = {
			type = "Container",
			columns = {
				{
					type = "ComboBox",
					text = "Pattern Preset",
					value = self.controls.rotatingPresetChoice.value,
					choices = self:getRotatingPresetList(),
					width = 1.0
				}
			}
		}

		rotatingCustomInput = {
			type = "Container",
			columns = {
				{
					type = "TextArea",
					text = "Custom Pattern (e.g., 5,-7,4 | -8,3,2 | 7)",
					value = self.controls.rotatingCustomInput.value,
					height = 40,
					width = 1.0,
					readOnly = false
				}
			}
		}

		rotatingScaleQuantize = {
			type = "Container",
			columns = {
				{
					type = "CheckBox",
					text = "Quantize to scale",
					value = self.controls.isRotatingScaleQuantize.value,
					width = 1.0
				}
			}
		}

		rotatingScaleSteps = {
			type = "Container",
			columns = {
				{
					type = "CheckBox",
					text = "Use scale steps (vs. chromatic semitones)",
					value = self.controls.isRotatingScaleSteps.value,
					width = 1.0
				}
			}
		}
	end
	
	if not self.isUpdateCurrentGroup and not self.isDropNotesFromDAW then
			synchroGroups = 
			{
				type = "Container",
				columns = {
					{
					type = "CheckBox",
					text = SV:T("Synchronize similar groups"),
					value = self.controls.isSynchronizeGroup.value,
					width = 1.0
					}
				}
			}
	end
	
	if not self.isUpdateCurrentGroup and not self.isSynchronizeGroup then
			dropFromDAW = 
			{
				type = "Container",
				columns = {
					{
					type = "CheckBox",
					text = SV:T("Drop notes from DAW"),
					value = self.controls.isDropNotesFromDAW.value,
					width = 1.0
					}
				}
			}
	end

	if self.displayMultiplePitchChoice and not self.isUpdateCurrentGroup and not self.isSynchronizeGroup and not self.isDropNotesFromDAW  then
		local transpositionList = self.transposition[self.transpositionSelected][self.transpositionRefData]
		multiplePitchChoice = 
			{
				type = "Container",
				columns = {
					{
						type = "ComboBox",
						text = SV:T("Harmony type"),
						value = self.controls.multiplePitchChoice.value,
						choices = transpositionList,
						width = 1.0
					}
				}
			}
	end
	
	if self.trackTestActive	then
		trackTest = 
			{
				type = "Container",
				columns = {
					{
						type = "Button",
						text = SV:T("Generate group"),
						width = 1.0,
						value = self.generateGroupButtonValue
					}
				}
			}
	end
	
	-- Define CheckBox & button & textarea
	local section = {
		title = SV:T(SCRIPT_TITLE),
		rows = {
			{
				type = "Label",
				text = SV:T("Detection: Select a group"),
			},
			scaleKeyFound,
			detectionLimited,
			labelAction,
			scaleKeyChoice,
			pitchChoice,
			harmonyChoice,
			multiplePitchChoice,
			transpositionSelected,
			rotatingLabel,
			rotatingPresetChoice,
			rotatingCustomInput,
			rotatingScaleQuantize,
			rotatingScaleSteps,
			updateNotesOuter,
			trackClone,
			updateCurrentGroup,
			applyButton,
			trackTest,
			labelSynchroGroups,
			synchroGroups,
			labelDropFromDAW,
			dropFromDAW,
			{
				type = "Container",
				columns = {
					{
						type = "TextArea",
						value = self.statusTextValue,
						height = 40,
						width = 1.0,
						readOnly = true
					}
				}
			}
		}
	}
	return section
end

-- Get panel section state
function NotesObject:getPanelSectionState()
	self:logsClear()
	self.applyButtonValue:setEnabled(true)
	self.generateGroupButtonValue:setEnabled(true)
	
	local section = self:getSectionContainer()

	local errors = self:displayErrors()
	if #errors > 0 then
		self:addTextPanel(errors)
	end
	
	return section
end

-- Initialize main internal object	
local notesObject = NotesObject:new()

-- Get panel section state called by Synthesizer V internal system
function getSidePanelSectionState()

	local section = notesObject:getPanelSectionState()
	return section
end
