--
-- Singing Style Plugin

PLUGIN_NAME = "Sachikobushi"

--
-- プラグインマニフェスト関数.
--
function manifest()
    myManifest = {
        name          = PLUGIN_NAME,
        comment       = "幸子節全開！！！！！（声の立ち上がりと揺れ幅を曲に合わせてSachiko風に調整します）",
        author        = "Yamaha Corporation",
        pluginID      = "{0A7A4612-EFEF-414f-B4E3-C5CEE7A71193}",
        pluginVersion = "1.0.0.1",
        apiVersion    = "3.0.0.1"
    }
    return myManifest
end

--
-- スクリプトのエントリポイント関数.
--
function main(processParam, envParam)

	local retCode = 0
	-- 実行時に渡された実行環境パラメータを取得する.
	local OSType = checkOS(envParam.tempDir)
	if( OSType == "Mac") then
		retCode,envParam.scriptDir,envParam.scriptName,envParam.tempDir = modifyPath(envParam.scriptDir,envParam.scriptName,envParam.tempDir)
	end
	if( retCode ~= 0 ) then
		return retCode
	end
		
	local scriptDir  = envParam.scriptDir	-- Luaスクリプトが配置されているディレクトリパス（末尾にデリミタ "\" を含む）.
	local scriptName = envParam.scriptName	-- Luaスクリプトのファイル名.
	local tempDir    = envParam.tempDir		-- Luaプラグインが利用可能なテンポラリディレクトリパス（末尾にデリミタ "\" を含む）.
	local workPath   = tempDir .. PLUGIN_NAME -- プラグイン専用の作業ディレクトリ（末尾のデリミタ "\" は含めない）.

	if( OSType == "Mac") then
		package.path = scriptDir .. "bin/?.lub;" .. package.path
	else
		package.path = ".\\bin/?.lub;" .. package.path
	end
	--VSMessageBox("package.path=" .. package.path,0)

	retCode = pcall(require,"SSgen")
	if( retCode == false ) then
		require("SSgen64")
	end
	
	envParam['workPath'] = workPath
	envParam['OSType']   = OSType

	local endStatus = SSgen(processParam,envParam)
	return endStatus
end
	
-- //--------------------------
function checkOS(tempDir)
	if(string.find(tempDir,"/VOCALOID%d* Editor for Cubase/JOB_PLUGINS") ~= nil) then
		return "Mac"
	elseif(string.find(tempDir,"\\VOCALOID%d* Editor for Cubase\\JOB_PLUGINS\\") ~= nil) then
		return "Win" --VOCALOID Editor for Cubase
	elseif(string.find(tempDir,"(\\VOCALOID%d*\\JOB_PLUGINS)") ~= nil) then
		return "Win" --Std. VOCALOID Editor
	end
	return "Unknown"
end

function modifyPath(scriptDir,scriptName,tempDir)
	local FH
	local message 

	scriptName = scriptName:match("(.*.lua)")

	local FH
	local message 
	local scriptDirTmp = scriptDir
	while string.len(scriptDirTmp) > 0 do
		local scriptFile = scriptDirTmp .. "/" .. scriptName
		FH,message = io.open(scriptFile,"r")
		if( FH ~= nil ) then
			FH:close()
			break
		end
		scriptDirTmp = string.sub(scriptDirTmp,1,string.len(scriptDirTmp)-1)
	end
	
	if( string.len(scriptDirTmp) == 0 ) then
		VSMessageBox("Cannot find scriptDir!",0)
		return 1,"","",""
	end
	
	if( scriptDir:match("/$") == nil ) then
		scriptDir = scriptDirTmp .. "/"
	end
	package.path = package.path .. ";" .. scriptDir .. "?.lua"
	tempDir = tempDir:gsub("\\$","/")
	
	return 0 , scriptDir, scriptName , tempDir
end
