--------------------------------------------------
---  Copyright 20008-2019, HDRsoft - www.hdrsoft.com
--------------------------------------------------

local LrApplication = import 'LrApplication'
local LrBinding = import 'LrBinding'
local LrView = import 'LrView'
local LrColor = import 'LrColor'
local LrDialogs = import 'LrDialogs'
local LrFunctionContext = import 'LrFunctionContext'
local LrErrors = import 'LrErrors'
local LrFileUtils = import 'LrFileUtils'
local LrPathUtils = import 'LrPathUtils'
local LrTasks = import 'LrTasks'
local LrLogger = import 'LrLogger'
local prefs = import 'LrPrefs'.prefsForPlugin()

local cntPhotos=0
local folderPath=''

BatchInputSettings = {}


function BatchInputSettings.debutCommun(fic1, fic2, minSeuilLen)
	local resStr=''
	local i=1
	local lenFicMin=#fic1
	if #fic2<lenFicMin then
		lenFicMin=#fic2
	end
	while (i<=lenFicMin) do
		if string.sub(fic1, i, i) ~= string.sub(fic2, i, i) then
			break
		end
		i=i+1
	end
	if (i>minSeuilLen) then
		resStr=string.sub(fic1, 1, i-1)
	end
	return resStr
end

function BatchInputSettings.getFirstFileName(photos)
	-- firstFileName=LrPathUtils.leafName(LrPathUtils.removeExtension(photos[1].path))
	local pathToFirstPhoto=photos[1]
	-- if pathToFirstPhoto:type()=='LrPhoto' then
	if type(pathToFirstPhoto) ~= 'string' then
		pathToFirstPhoto = pathToFirstPhoto.path
	end
	firstFileName=LrPathUtils.leafName(LrPathUtils.removeExtension(pathToFirstPhoto))
	return firstFileName
end

function BatchInputSettings.firstFileName( )
	local firstFileName=''
	local activeCatalog = LrApplication.activeCatalog()
	activeCatalog:withReadAccessDo( function()
		local photos = activeCatalog.targetPhotos
		firstFileName=BatchInputSettings.getFirstFileName(photos)
	end )
	return firstFileName
end


function BatchInputSettings.getDefaultFileName(photos)
	local combinedFileName=''

	if prefs.LrVersion<2 then
		return combinedFileName
	end
	local photosPaths = nil
	BatchUploadTask.outputToLog(string.format("In getDefaultFileName, photo is: %s (%s)", photos[1], type(photos[1])))
	-- if photos[1]:type()=='LrPhoto' then
	if type(photos[1]) ~= 'string' then
		photosPaths = {}
		for idxPhoto = 1,#photos do
			photosPaths[idxPhoto] = photos[idxPhoto].path
		end
	end
	if photosPaths == nil then -- photos already contains path strings
		photosPaths = photos
	end

	cntPhotos=#photosPaths
	folderPath=LrPathUtils.parent(photosPaths[1])

	if cntPhotos==1 then
		combinedFileName=string.format('%s_tonemapped', LrPathUtils.leafName(LrPathUtils.removeExtension(photosPaths[1])))
	else

	local iPhoto=1
	local commonStr=''
	local firstFileName=LrPathUtils.leafName(LrPathUtils.removeExtension(photosPaths[1]))
	local maxLen=0
	for iPhoto=2, cntPhotos, 1 do
		local curFileName=LrPathUtils.leafName(LrPathUtils.removeExtension(photosPaths[iPhoto]))
		if (iPhoto==2) then
			commonStr=BatchInputSettings.debutCommun(firstFileName, curFileName, 2)
		else
			if #commonStr>1 then
				commonStr=BatchInputSettings.debutCommun(commonStr, curFileName, 2)
			end
		end
		if #curFileName>maxLen then
			maxLen=#curFileName
		end
	end

	if #commonStr>1 then
		if ((maxLen - #commonStr) <= 8) then
			combinedFileName=firstFileName
			local cntSameName=0
			for iPhoto=2, cntPhotos, 1 do
				local curFileName=LrPathUtils.leafName(LrPathUtils.removeExtension(photosPaths[iPhoto]))
				local differingPart=string.sub(curFileName, #commonStr+1)
				if #differingPart>0 then
					combinedFileName=string.format('%s_%s', combinedFileName, differingPart)
				else
					cntSameName=cntSameName+1
				end
			end
			if (cntSameName==(cntPhotos-1)) then
				combinedFileName=string.format('%sx%d',firstFileName,cntPhotos)
			end
		end
	end

	if ((#combinedFileName<2) or (cntPhotos > 7)) then
		combinedFileName=string.format('%sAnd%dmore', firstFileName, cntPhotos-1)
	end

	end -- fin if cntPhotos==1


	return combinedFileName
end

function BatchInputSettings.defaultFileName(props)
	local combinedFileName=''
	local activeCatalog = LrApplication.activeCatalog()
	activeCatalog:withReadAccessDo( function()
		local photos = activeCatalog.targetPhotos
		local photos4FileName={}
		local kMax = props.kMax
		if props.doBatchSingle then kMax = 1 end
		for iPhoto = 1, #photos do
			table.insert(photos4FileName,photos[iPhoto])
			if iPhoto == kMax then
				break
			end
		end
		combinedFileName=BatchInputSettings.getDefaultFileName(photos4FileName)
	end )
	return combinedFileName
end

local builtinPresets={

	{method="DetailsEnhancer", text=LOC "$$$/Photomatix/Batch/Presets/Detailed=Detailed", value="Detailed", categories={"BuiltinPresetsShortList", "BuiltinPresetsDetailsEnhancer"},},
	{method="ContrastOptimizer", text=LOC "$$$/Photomatix/Batch/Presets/Balanced=Balanced", value="Balanced", categories={"BuiltinPresetsShortList", "BuiltinPresetsRealistic","BuiltinPresetsContrastOptimizer"},},
	{method="ToneBalancer", text=LOC "$$$/Photomatix/Batch/Presets/Realistic=Realistic", value="Realistic", categories={"BuiltinPresetsShortList", "BuiltinPresetsRealistic", "BuiltinPresetsArchitecture","BuiltinPresetsToneBalancer"},},
	{method="ToneCompressor", text=LOC "$$$/Photomatix/Batch/Presets/Photographic=Photographic", value="Photographic", categories={"BuiltinPresetsShortList", "BuiltinPresetsRealistic", "BuiltinPresetsToneCompressor"},},
	{method="Adjust", text=LOC "$$$/Photomatix/Batch/Presets/Natural=Natural", value="Natural", categories={"BuiltinPresetsShortList", "BuiltinPresetsRealistic", "BuiltinPresetsArchitecture", "BuiltinPresetsExposureFusion"},},
	{method="DetailsEnhancer", text=LOC "$$$/Photomatix/Batch/Presets/Painterly=Painterly", value="Painterly", categories={"BuiltinPresetsShortList", "BuiltinPresetsArtistic", "BuiltinPresetsDetailsEnhancer"},},
	{method="DetailsEnhancer", text=LOC "$$$/Photomatix/Batch/Presets/Painterly2=Painterly 2", value="Painterly2", categories={"BuiltinPresetsArtistic", "BuiltinPresetsDetailsEnhancer"},},
	{method="DetailsEnhancer", text=LOC "$$$/Photomatix/Batch/Presets/Painterly3=Painterly 3", value="Painterly3", categories={"BuiltinPresetsArtistic", "BuiltinPresetsDetailsEnhancer"},},
	{method="DetailsEnhancer", text=LOC "$$$/Photomatix/Batch/Presets/Painterly4=Painterly 4", value="Painterly4", categories={"BuiltinPresetsArtistic", "BuiltinPresetsDetailsEnhancer"},},
	{method="Adjust", text=LOC "$$$/Photomatix/Batch/Presets/Painterly5=Painterly 5", value="Painterly5", categories={"BuiltinPresetsArtistic", "BuiltinPresetsExposureFusion"},},
	{method="ContrastOptimizer", text=LOC "$$$/Photomatix/Batch/Presets/Vibrant=Vibrant", value="Vibrant", categories={"BuiltinPresetsShortList", "BuiltinPresetsArtistic", "BuiltinPresetsContrastOptimizer"},},
	{method="DetailsEnhancer", text=LOC "$$$/Photomatix/Batch/Presets/Enhanced=Enhanced", value="Enhanced", categories={"BuiltinPresetsShortList", "BuiltinPresetsRealistic", "BuiltinPresetsDetailsEnhancer"},},

	{method="ContrastOptimizer", text=LOC "$$$/Photomatix/Batch/Presets/Enhanced2=Enhanced 2", value="Enhanced2", categories={"BuiltinPresetsRealistic", "BuiltinPresetsContrastOptimizer"},},
	{method="ToneBalancer", text=LOC "$$$/Photomatix/Batch/Presets/Realistic2=Realistic 2", value="Realistic2", categories={"BuiltinPresetsShortList", "BuiltinPresetsRealistic", "BuiltinPresetsToneBalancer"},},
	{method="Realistic", text=LOC "$$$/Photomatix/Batch/Presets/Interior=Interior", value="Interior", categories={"BuiltinPresetsShortList", "BuiltinPresetsRealistic", "BuiltinPresetsArchitecture", "BuiltinPresetsExposureFusion"},},
	{method="Realistic", text=LOC "$$$/Photomatix/Batch/Presets/Interior2=Interior 2", value="Interior2", categories={"BuiltinPresetsRealistic", "BuiltinPresetsArchitecture", "BuiltinPresetsExposureFusion"},},
	{method="ContrastOptimizer", text=LOC "$$$/Photomatix/Batch/Presets/Interior3=Interior 3", value="Interior3", categories={"BuiltinPresetsRealistic", "BuiltinPresetsArchitecture", "BuiltinPresetsContrastOptimizer"},},
	{method="ToneBalancer", text=LOC "$$$/Photomatix/Batch/Presets/Interior4=Interior 4", value="Interior4", categories={"BuiltinPresetsRealistic", "BuiltinPresetsArchitecture", "BuiltinPresetsToneBalancer"},},
	{method="ToneCompressor", text=LOC "$$$/Photomatix/Batch/Presets/Deep=Deep", value="CompressorDeep", categories={"BuiltinPresetsShortList", "BuiltinPresetsRealistic", "BuiltinPresetsToneCompressor"},},
	{method="ToneBalancer", text=LOC "$$$/Photomatix/Batch/Presets/Vibrant2=Vibrant 2", value="Vibrant2", categories={"BuiltinPresetsArtistic", "BuiltinPresetsToneBalancer"},},
	{method="DetailsEnhancer", text=LOC "$$$/Photomatix/Batch/Presets/Surreal=Surreal", value="Surreal", categories={"BuiltinPresetsShortList", "BuiltinPresetsArtistic", "BuiltinPresetsDetailsEnhancer"},},
	{method="Adjust", text=LOC "$$$/Photomatix/Batch/Presets/Surreal2=Surreal 2", value="Surreal2", categories={"BuiltinPresetsArtistic", "BuiltinPresetsExposureFusion"},},
	{method="DetailsEnhancer", text=LOC "$$$/Photomatix/Batch/Presets/Grunge=Grunge", value="Grunge", categories={"BuiltinPresetsShortList", "BuiltinPresetsArtistic", "BuiltinPresetsDetailsEnhancer"},},
	{method="DetailsEnhancer", text=LOC "$$$/Photomatix/Batch/Presets/Grunge2=Grunge 2", value="Grunge2", categories={"BuiltinPresetsArtistic", "BuiltinPresetsDetailsEnhancer"},},
	{method="DetailsEnhancer", text=LOC "$$$/Photomatix/Batch/Presets/Creative=Creative", value="Creative", categories={"BuiltinPresetsShortList", "BuiltinPresetsArtistic", "BuiltinPresetsDetailsEnhancer"},},
	{method="DetailsEnhancer", text=LOC "$$$/Photomatix/Batch/Presets/Creative2=Creative 2", value="Creative2", categories={"BuiltinPresetsArtistic", "BuiltinPresetsDetailsEnhancer"},},
	{method="DetailsEnhancer", text=LOC "$$$/Photomatix/Batch/Presets/Creative3=Creative 3", value="Creative3", categories={"BuiltinPresetsArtistic", "BuiltinPresetsDetailsEnhancer"},},
	{method="ContrastOptimizer", text=LOC "$$$/Photomatix/Batch/Presets/Soft=Soft", value="Soft", categories={"BuiltinPresetsShortList", "BuiltinPresetsRealistic", "BuiltinPresetsContrastOptimizer"},},
	{method="DetailsEnhancer", text=LOC "$$$/Photomatix/Batch/Presets/Soft2=Soft 2", value="Soft2", categories={"BuiltinPresetsRealistic", "BuiltinPresetsDetailsEnhancer"},},
	{method="DetailsEnhancer", text=LOC "$$$/Photomatix/Batch/Presets/Soft3=Soft 3", value="Soft3", categories={"BuiltinPresetsRealistic", "BuiltinPresetsDetailsEnhancer"},},
	{method="Adjust", text=LOC "$$$/Photomatix/Batch/Presets/Soft4=Soft 4", value="Soft4", categories={"BuiltinPresetsRealistic", "BuiltinPresetsExposureFusion"},},
	{method="DetailsEnhancer", text=LOC "$$$/Photomatix/Batch/Presets/SmoothSkies=SmoothSkies", value="SmoothSkies", categories={"BuiltinPresetsShortList", "BuiltinPresetsRealistic", "BuiltinPresetsDetailsEnhancer"},},
	{method="DetailsEnhancer", text=LOC "$$$/Photomatix/Batch/Presets/SmoothSkies2=SmoothSkies 2", value="Smooth2", categories={"BuiltinPresetsRealistic", "BuiltinPresetsDetailsEnhancer"},},
	{method="DetailsEnhancer", text=LOC "$$$/Photomatix/Batch/Presets/SmoothSkies3=SmoothSkies 3", value="Smooth3", categories={"BuiltinPresetsRealistic", "BuiltinPresetsArchitecture", "BuiltinPresetsDetailsEnhancer"},},
	{method="DetailsEnhancer", text=LOC "$$$/Photomatix/Batch/Presets/Monochrome=Monochrome", value="DefaultBW", categories={"BuiltinPresetsShortList", "BuiltinPresetsRealistic", "BuiltinPresetsBlackAndWhite", "BuiltinPresetsDetailsEnhancer"},},

	{method="DetailsEnhancer", text=LOC "$$$/Photomatix/Batch/Presets/Monochrome2=Monochrome 2", value="BW2", categories={"BuiltinPresetsArtistic", "BuiltinPresetsBlackAndWhite", "BuiltinPresetsDetailsEnhancer"},},
	{method="ContrastOptimizer", text=LOC "$$$/Photomatix/Batch/Presets/Monochrome3=Monochrome 3", value="BW3", categories={"BuiltinPresetsArtistic", "BuiltinPresetsBlackAndWhite", "BuiltinPresetsContrastOptimizer"},},
	{method="ToneBalancer", text=LOC "$$$/Photomatix/Batch/Presets/BWRealistic=B&&W Realistic", value="RealisticBW", categories={"BuiltinPresetsBlackAndWhite", "BuiltinPresetsRealistic", "BuiltinPresetsToneBalancer"},},
	{method="ToneCompressor", text=LOC "$$$/Photomatix/Batch/Presets/BWPhotographic=B&&W Photographic", value="PhotographicBW", categories={"BuiltinPresetsRealistic", "BuiltinPresetsBlackAndWhite", "BuiltinPresetsToneCompressor"},},
	{method="DetailsEnhancer", text=LOC "$$$/Photomatix/Batch/Presets/BWArtistic=B&&W Artistic", value="ArtisticBW", categories={"BuiltinPresetsArtistic", "BuiltinPresetsBlackAndWhite", "BuiltinPresetsDetailsEnhancer"},},
	{method="Adjust", text=LOC "$$$/Photomatix/Batch/Presets/BWNatural=B&&W Natural", value="FusionBW", categories={"BuiltinPresetsRealistic", "BuiltinPresetsBlackAndWhite", "BuiltinPresetsExposureFusion"},},

}

-- local builtinPresetsPath = LrPathUtils.child(_PLUGIN.path,"presets")
-- if not prefs.isDebug then
local builtinPresetsPath = LrPathUtils.child(_PLUGIN.path,"BuiltinPresets")
-- end

local itemSelectPreset={title=LOC "$$$/Photomatix/Batch/Input/HdrPresetSection/SelectPreset=----- Select a preset -----", value=""}

function BatchInputSettings.getBuiltinPresetItems(presetStyle, isSingleFile)

	local items={
		itemSelectPreset,
	}
	local iItem=2

	local allTM = presetStyle=="ToneMapping"
	for k,preset in ipairs(builtinPresets) do
		local addPreset = presetStyle=="AllPresets"
		if ((not addPreset) or isSingleFile) then
			if allTM then
				addPreset=true
			end
			for kk,cat in pairs(preset.categories) do
				if (isSingleFile or allTM) and cat == "BuiltinPresetsExposureFusion" then
					addPreset = false
					break
				end
				if (cat==presetStyle) then
					addPreset=true
					if not isSingleFile then
						break
					end
				end
			end
		end
		-- BatchUploadTask.outputToLog(string.format("In getPresetItems k=%d, add=%s p=%s bpath=%s",k, addPreset, preset.value, builtinPresetsPath))
		if addPreset then
			presetPath=LrPathUtils.child(builtinPresetsPath,LrPathUtils.addExtension(preset.value,"xmp"))
			-- BatchUploadTask.outputToLog(string.format("In getPresetItems ppath=%s", presetPath))

			if not LrFileUtils.exists(presetPath) then
				BatchUploadTask.outputToLog( string.format("Warning, couldn't find preset at path: %s", presetPath))
			end
			local item={title=preset.text, value=presetPath}
			items[iItem]=item
			iItem=iItem+1
		end
	end
	return items

end

local sysAppData=LrPathUtils.parent(LrPathUtils.parent(LrPathUtils.getStandardFilePath("appData")))
local hdrsoftAppData=LrPathUtils.child(sysAppData,"HDRsoft")
if MAC_ENV then
  hdrsoftAppData=sysAppData
end
local pmpAppData=LrPathUtils.child(hdrsoftAppData,"PhotomatixPro")
if MAC_ENV then
  pmpAppData=LrPathUtils.child(hdrsoftAppData,"Photomatix")
end
local customPresetPath=LrPathUtils.child(pmpAppData,"Presets")

function BatchInputSettings.isPresetForFusion(xmpFile)
	local isFusionPreset = false
	if LrFileUtils.exists(xmpFile) then
		local xmpHandle=io.open(xmpFile,"r")
		if xmpHandle then
			-- BatchUploadTask.outputToLog("In getCustomPresetItems, handle valid")
			-- BatchUploadTask.outputToLog(string.format("Handle=%s",xmpHandle))
			-- for xmpLine in io.lines(xmpHandle) do
			for xmpLine in xmpHandle:lines() do
				-- BatchUploadTask.outputToLog("Inside line loop...")
				-- BatchUploadTask.outputToLog(string.format("line=%s",xmpLine))
				local startStart, startEnd = string.find(xmpLine, "<pmtm:Method>", 1, true)
				-- BatchUploadTask.outputToLog("After find")
				-- BatchUploadTask.outputToLog(string.format("start=%s",startStart))

				-- BatchUploadTask.outputToLog(string.format("line=%s start=%d end=%d",xmpLine,startStart, startEnd))
				if startStart then
					-- BatchUploadTask.outputToLog(string.format("start OK end=%d", startEnd))
					local endStart, endEnd = string.find(xmpLine, "</pmtm:Method>", 1, true)
					-- BatchUploadTask.outputToLog(string.format("endStart=%d",endStart))
					if endStart then
						-- BatchUploadTask.outputToLog(string.format("endStart OK endEnd=%d",endEnd))
						-- BatchUploadTask.outputToLog(string.format("About to sub=%s, start=%d, end=%d",xmpLine, startEnd, endStart))
						local method=string.sub(xmpLine, startEnd+1, endStart-1)
						-- BatchUploadTask.outputToLog(string.format("method=%s",method))
						if (string.find(method,"Fusion"))==1 or method=="Average" then
							-- BatchUploadTask.outputToLog("Skipping preset as fusion")
							isFusionPreset = true
						end
					end
					break --method tag found so no need to parse more of the xmp file
				end
			end
			-- BatchUploadTask.outputToLog("Closing handle")
			io.close(xmpHandle)
		end
	end
	return isFusionPreset
end

function BatchInputSettings.getCustomPresetItems(isSingleFile, addSelectPreset)

	local items={
		-- {title=LOC "$$$/Photomatix/Batch/Input/HdrPresetSection/LoadPreset=Load preset", value=""},
	}
	if addSelectPreset then
		table.insert(items, itemSelectPreset)
	end

	if LrFileUtils.exists(customPresetPath) then
		for xmpFile in LrFileUtils.directoryEntries(customPresetPath) do
			if LrFileUtils.exists(xmpFile)=='file' and LrPathUtils.extension(xmpFile)=='xmp' then
				local shouldSkipItem=false
				if (isSingleFile) then --we need to check inside the xmp file whether it is for a fusion method and skip it if so as we're processing single photos so only TM methods are allowed
					shouldSkipItem = BatchInputSettings.isPresetForFusion(xmpFile)
				end
				if not shouldSkipItem then
					local xmpName=LrPathUtils.removeExtension(LrPathUtils.leafName(xmpFile))
					local item={title=xmpName, value=xmpFile}
					table.insert(items,item)
				end
			end
		end
	end

	return items

end

function BatchInputSettings.getPresetItems(presetStyle, isSingleFile)
	local items
	if presetStyle ~= "custom" then
		items = BatchInputSettings.getBuiltinPresetItems(presetStyle, isSingleFile)
	else
		items = BatchInputSettings.getCustomPresetItems(isSingleFile, true)
	end
	if presetStyle == "AllPresets" then
		custItems = BatchInputSettings.getCustomPresetItems(isSingleFile, false)
		table.insert(items,{ separator = true})
		BatchUploadTask.outputToLog(string.format("In getPresetItems, before cust=%s",custItems), true)
		for k, v in ipairs(custItems) do
			BatchUploadTask.outputToLog(string.format("Getting custItem %s=%s",k,v))
			table.insert(items,v)
		end
	end
	return items
end


function BatchInputSettings.getStickySettings(context)

	local props = LrBinding.makePropertyTable( context )

	props.doBatchSingle = true
	props.batchStacks = true
	-- props.useCustomPreset=false
	-- props.showInputSection=true
	-- props.builtinPreset=""
	props.presetToUse = ""
	-- props.customPreset = ""
	props.chkAlign = true
	props.chkCrop = true
	props.chkGhosting = false
	props.curPresetStyle = "AllPresets"
	props.presetAlign = "2"
	-- props.chkReduceCA=false
	-- props.chkReduceNoise=false
	props.kMax = 3
	-- props.outputFormat='tif16'
	-- props.outBps=8

	props.hasStacks = prefs.hasStacks

	props.cbxContrast = 0
	props.cbxSharpening = 0

	props.colorProfile = "AdobeRGB"

	props.outputFileNameOption = "0"
	props.fileNameSuffix = ""
	props.outputFormat = "jpg"

	props.chkStack = false



	-- if cntPhotos==1 then
		-- props.outputName=props.combinedFileName
	-- end

	-- if (prefs.maxShift~=nil) then
		-- props.maxShift=prefs.maxShift
	-- end
	-- if (prefs.chkPerspective~=nil) then
		-- props.chkPerspective=prefs.chkPerspective
	-- end

	props.pmpRunning = false

	if (prefs.doBatchSingle ~= nil) then
		props.doBatchSingle = prefs.doBatchSingle
	end

	if (prefs.batchStacks ~= nil) then
		props.batchStacks = prefs.batchStacks
	end
	if props.batchStacks and not prefs.hasStacks then
		props.batchStacks = false
	end

	-- if (prefs.useCustomPreset ~= nil) then
		-- props.useCustomPreset = prefs.useCustomPreset
	-- end

	-- if (prefs.builtinPreset ~= nil) then
		-- props.builtinPreset = prefs.builtinPreset
	-- end

	if (prefs.presetToUse ~= nil) then
		props.presetToUse = prefs.presetToUse
	end

	-- if (prefs.customPreset ~= nil) then
		-- props.customPreset = prefs.customPreset
	-- end

	if (prefs.chkAlign ~= nil) then
		props.chkAlign = prefs.chkAlign
	end

	if (prefs.chkCrop ~= nil) then
		props.chkCrop = prefs.chkCrop
	end

	if (prefs.chkGhosting ~= nil) then
		props.chkGhosting = prefs.chkGhosting
	end

	if (prefs.curPresetStyle ~= nil) then
		props.curPresetStyle = prefs.curPresetStyle
	end

	if (prefs.presetAlign ~= nil) then
		props.presetAlign = prefs.presetAlign
	end

	-- if (prefs.chkReduceNoise) then
		-- props.chkReduceNoise=prefs.chkReduceNoise
	-- end
	if (prefs.kMax ~= nil) then
		props.kMax = prefs.kMax
	end
	-- if (prefs.outBps ~= nil) then
		-- props.outBps = prefs.outBps
	-- end
	if (prefs.cbxContrast ~= nil) then
		props.cbxContrast = prefs.cbxContrast
	end
	if (prefs.cbxSharpening ~= nil) then
		props.cbxSharpening = prefs.cbxSharpening
	end
	if (prefs.colorProfile ~= nil) then
		props.colorProfile = prefs.colorProfile
	end
	if (prefs.outputFileName ~= nil) then
		props.outputFileName = prefs.outputFileName
	end

	if (prefs.outputFormat ~= nil) then
		props.outputFormat = prefs.outputFormat
	end

	if (prefs.outputFileNameOption ~= nil) then
		props.outputFileNameOption = prefs.outputFileNameOption
	end

	if (prefs.fileNameSuffix ~= nil) then
		props.fileNameSuffix = prefs.fileNameSuffix
	end

	-- Uncomment below if we ever need to put back the stack with photo checkbox.
	-- if (prefs.chkStack ~= nil) then
		-- props.chkStack = prefs.chkStack
	-- end

	-- if (prefs.chkReduceCA) then
		-- props.chkReduceCA=prefs.chkReduceCA
	-- end
	-- if (prefs.outputFormat~=nil) then
		-- props.outputFormat=prefs.outputFormat
	-- end

	-- props.combinedFileName=BatchInputSettings.defaultFileName(props)
	-- props.firstFileName=BatchInputSettings.firstFileName()

	-- props.combinedFileName=BatchInputSettings.getDefaultFileName({"myphoto_normal.jpg","myphoto_over.jpg","myphoto_under.jpg"})
	-- props.firstFileName=BatchInputSettings.getFirstFileName({"myphoto_normal.jpg","myphoto_over.jpg","myphoto_under.jpg"})


	return props
end

function BatchInputSettings.saveStickySettings(props)

	-- BatchUploadTask.outputToLog("\nIn SaveSticky dumping props before save:")
	-- for k,v in props:pairs() do
		-- BatchUploadTask.outputToLog(string.format("%s=%s",k,v))
	-- end

	prefs.doBatchSingle = props.doBatchSingle
	prefs.batchStacks = props.batchStacks
	-- prefs.useCustomPreset=props.useCustomPreset
	-- prefs.builtinPreset=props.builtinPreset
	prefs.presetToUse = props.presetToUse
	-- prefs.customPreset=props.customPreset
	prefs.chkAlign = props.chkAlign
	prefs.chkCrop = props.chkCrop
	prefs.chkGhosting = props.chkGhosting
	prefs.curPresetStyle = props.curPresetStyle
	prefs.presetAlign = props.presetAlign
	prefs.kMax = props.kMax
	-- prefs.outBps=props.outBps
	prefs.cbxContrast = props.cbxContrast
	prefs.cbxSharpening = props.cbxSharpening
	prefs.colorProfile = props.colorProfile
	prefs.outputFormat = props.outputFormat
	prefs.outputFileNameOption = props.outputFileNameOption
	prefs.fileNameSuffix = props.fileNameSuffix
	prefs.chkStack = props.chkStack

	-- BatchUploadTask.outputToLog("\nIn SaveSticky dumping prefs after save:")
	-- for k,v in prefs:pairs() do
		-- BatchUploadTask.outputToLog(string.format("%s=%s",k,v))
	-- end

end

numTargetPhotos=0

function BatchInputSettings.getOptions( )

	require 'BatchPhotomatixCom'
	if prefs.LrVersion==nil then
		LrDialogs.message("Plugin did not start correctly","Please check whether you invoked the plugin by choosing 'File > Plug-in Extras'","info")
		return
	end

	if prefs.LrVersion>1 then
		isLr2=true
		-- titleBox2=LOC "$$$/Photomatix/Settings/BoxTitle=Handling of HDR Processed Image"
	end
	local targetPhotos = LrApplication.activeCatalog():getTargetPhotos()
	if targetPhotos ~= nil then
		numTargetPhotos = #targetPhotos
	else
		numTargetPhotos = 0
	end
	local doProcess=false
	LrFunctionContext.callWithContext( 'batchInputSettings', function( context )

	local f = LrView.osFactory()
	-- local props = LrBinding.makePropertyTable( context )
	local props = BatchInputSettings.getStickySettings(context)

	props.refreshPresetList = 0
	props.forceSingle = false

	local kMaxItems = {
		-- { title = "2", value = 2 },
		-- { title = "3", value = 3 },
		-- { title = "4", value = 4 },
		-- { title = "5", value = 5 },
		-- { title = "6", value = 6 },
		-- { title = "7", value = 7 },
		-- { title = "8", value = 8 },
		-- { title = "9", value = 9 },
	}
	for kItemIndex = 2,17 do
		table.insert(kMaxItems, { title = string.format("%s",kItemIndex), value = kItemIndex } )
	end

	local txtPhotosPerBrackets = LOC "$$$/Photomatix/Batch/Input/InputSection/FramesPerBracket=photos per bracket"
	if prefs.hasStacks then
		local txtStacksIgnored = LOC "$$$/Photomatix/Batch/Input/InputSection/StacksIgnored=(stacks are ignored)"
		txtPhotosPerBrackets = string.format("%s %s",txtPhotosPerBrackets, txtStacksIgnored)
	end

	props.firstFileName=BatchInputSettings.firstFileName()

	if props.doBatchSingle and (not prefs.hasStacks)  and BatchInputSettings.isPresetForFusion(props.presetToUse) then
		props.presetToUse = ""
	end
	
	local checkFusionPossible = function (curProps, curKey, curValue)
		if props.doBatchSingle and (not prefs.hasStacks)  and BatchInputSettings.isPresetForFusion(props.presetToUse) then
			LrDialogs.message(LOC "$$$/Photomatix/Batch/Input/Messages/SingleFusionNoStacksTitle=Fusion preset requires bracketed set",
			LOC "$$$/Photomatix/Batch/Input/Messages/SingleFusionNoStacksMessage=The preset you selected is a fusion preset. It works by fusing multiple photos, but none of the photos you selected are in a stack.\n\nPlease choose a tone mapping preset instead (you can filter presets to view only those with a tone mapping method).")
		end
	end
	props:addObserver("presetToUse", checkFusionPossible)
	props:addObserver("doBatchSingle", checkFusionPossible)
	
	local LeftMarginSavePanel=135


	local leftMarginPresetSection=180
	local widthFirstControlPresetSection=130
	local leftMarginOutputSection=135

	local platformAdjustPresetLabel = 0
	if WIN_ENV then
		platformAdjustPresetLabel = 11
	end
	
	local labelOrTopMargin = 1
	if WIN_ENV then
		labelOrTopMargin = 4
	end
	
    local topGroupMargin = 28
    local botGroupMargin =18

	local batchInputUI = f:column {
		bind_to_object = props,
		spacing=26,
        margin_top = 0,

		f:group_box {
			title = LOC "$$$/Photomatix/Batch/Input/InputSection/Title=Input",
			show_title=true,
			fill_horizontal=1,
			margin_top = topGroupMargin,
			margin_bottom = botGroupMargin,
			-- visible=LrView.bind("showInputSection"),
			font = "<system>",
			f:column {
				spacing=10,
				f:radio_button {
					title = LOC "$$$/Photomatix/Batch/Input/InputSection/StacksAndSinglePhotos=Stacks are treated as bracketed sets, other photos as single images",
					value=LrView.bind("doBatchSingle"),
					tooltip = LOC "$$$/Photomatix/Batch/Input/InputSection/Tooltips/StacksAndSinglePhotos=Photos in stacks will be merged, then tone mapped or fused. Other photos will be tone mapped if you selected a tone mapping preset, and skipped otherwise.",
					checked_value=true,
					height=26,
				},

				f:row {
					f:radio_button {
						title = LOC "$$$/Photomatix/Batch/Input/InputSection/PhotosAsBracketed=Photos are treated as bracketed sets, with ",
						-- tooltip = LOC "$$$/Photomatix/Input/InputSection/Tooltips/PhotosAsBracketed=All photos will be merged to an HDR image that is then tone mapped or fused.",
						tooltip = LrView.bind {
							keys = { 'kMax' },
							operation = function( binder, values, fromTable )
								if fromTable then
									return string.format( LOC "$$$/Photomatix/Input/InputSection/Tooltips/PhotosAsBracketed=The %d photos in each set will be merged, then tone mapped or fused. (Photos in stacks will be ignored).",values.kMax)
							   end
							end
						},
						value=LrView.bind("doBatchSingle"),
						checked_value=false,
						enabled=LrBinding.negativeOfKey("forceSingle"),
					},
						f:row {
							spacing=10,

							f:popup_menu {
								value = LrView.bind ("kMax"),
								items = kMaxItems,
								fill_horizontal=0.4,
							},

							f:static_text {
								title = txtPhotosPerBrackets,
							},

						},
				},
			},

		},

		f:group_box {
			title = LOC "$$$/Photomatix/Batch/Input/HdrPresetSection/Title=HDR Preset",
			show_title=true,
			fill_horizontal=1,
			margin_top = topGroupMargin,
			margin_bottom = botGroupMargin,

			font = "<system>",
			f:column {
				fill=1,
				spacing=10,
				f:row {
					fill=1,
					f:static_text {
						title = LOC "$$$/Photomatix/Batch/Input/HdrPresetSection/PresetFromList=Choose a preset from list:",
						fill=0.3,
                    width=170,
					},
					f:popup_menu {
						fill=0.31,
						width=200,
						value=LrView.bind("presetToUse"),
						items=LrView.bind {
								keys = { 'curPresetStyle', 'doBatchSingle', 'refreshPresetList' },
								operation = function( binder, values, fromTable )
									if fromTable then
										-- local presetItems = BatchInputSettings.getPresetItems(values.curPresetStyle, values.doBatchSingle)
										local presetItems = BatchInputSettings.getPresetItems(values.curPresetStyle, false)
										local curPresetIsInList = false
										for i,presetItem in ipairs(presetItems) do
											if presetItem.value == props.presetToUse then
												curPresetIsInList = true
												break
											end
										end
										if not curPresetIsInList then
											props.presetToUse = ""
										end
										return presetItems
								   end
								end
							},
						-- enabled=LrBinding.negativeOfKey("useCustomPreset"),
					},
					f: row
					{
						-- spacing=10,
						-- fill=0.39,
						f:row {
							margin_left = 10,
							f:static_text {
								title="filtered by:",
								fill=0.3,
							},

							f:popup_menu {
								 fill=0.09,

								value=LrView.bind("curPresetStyle"),
								width=widthFirstControlPresetSection,
								items=LrView.bind {
									keys= { 'doBatchSingle' },
									operation = function(binder, values, fromTable)
										if fromTable then
											local items= {
												{title=LOC "$$$/Photomatix/Batch/Presets/Styles/AllStyles=All Styles", value="AllPresets"},
												{title=LOC "$$$/Photomatix/Batch/Presets/Styles/CompactList=Compact List", value="BuiltinPresetsShortList"},
												{ separator = true},
												{title=LOC "$$$/Photomatix/Batch/Presets/Styles/Realistic=Realistic", value="BuiltinPresetsRealistic"},
												{title=LOC "$$$/Photomatix/Batch/Presets/Styles/Artistic=Artistic", value="BuiltinPresetsArtistic"},
												{title=LOC "$$$/Photomatix/Batch/Presets/Styles/RealEstate=Real Estate", value="BuiltinPresetsArchitecture"},
												{title=LOC "$$$/Photomatix/Batch/Presets/Styles/BlackWhite=Black & White", value="BuiltinPresetsBlackAndWhite"},
												{ separator = true},
												{title=LOC "$$$/Photomatix/Batch/Presets/Styles/DetailsEnhancer=Details Enhancer", value="BuiltinPresetsDetailsEnhancer"},
												{title=LOC "$$$/Photomatix/Batch/Presets/Styles/ToneMapping=Tone Mapping", value="ToneMapping"},
												{title=LOC "$$$/Photomatix/Batch/Presets/Styles/ContrastOptimizer=Contrast Optimizer", value="BuiltinPresetsContrastOptimizer"},
												{title=LOC "$$$/Photomatix/Batch/Presets/Styles/ToneCompressor=Tone Compressor", value="BuiltinPresetsToneCompressor"},
												{title=LOC "$$$/Photomatix/Batch/Presets/Styles/ToneBalancer=Tone Balancer", value="BuiltinPresetsToneBalancer"},
												{title=LOC "$$$/Photomatix/Batch/Presets/Styles/Fusion=Fusion", value="BuiltinPresetsExposureFusion"},
												{title=LOC "$$$/Photomatix/Batch/Presets/Styles/MyPresets=My Presets", value="custom"},

											}
											-- condition below forced to false, since we always show presets for fusion now that option to process stacks and single photos have been merged into one.
											if false and values.doBatchSingle then --remove Fusion item since it would cause an empty preset list.
												local fusionItem = table.remove(items, #items-1)
												if fusionItem.value == props.curPresetStyle then
													props.curPresetStyle = items[1].value
												end
											end
											return items
										end
									end
								},
							},
						},
					},
				},

				f:row {
					fill=1,
					f:row {
					f: column
					{
						margin_left=140 - platformAdjustPresetLabel,
						margin_top = labelOrTopMargin,
						-- spacing=10,
						f:static_text{
						title="Or:",

						fill=0.3,
						width=30 + platformAdjustPresetLabel,
						},
						},
						f:push_button {
							fill=0.31,
							margin_left = 0,
							size = "regular",
							title = LOC "$$$/Photomatix/Batch/Input/HdrPresetSection/CreatePreset=Choose Preset with preview",
							-- width=widthFirstControlPresetSection,
							width=200,							-- enabled=LrView.bind("useCustomPreset"),
							enabled = LrView.bind {
								-- keys= { 'useCustomPreset', 'pmpRunning' },
								keys= { 'pmpRunning' },
								operation = function(binder, values, fromTable)
									if fromTable then
										-- return values.useCustomPreset and not values.pmpRunning
										return not values.pmpRunning
									end
								end
							},
							action = function(button)
								BatchUploadTask.outputToLog("About to call create preset")
								LrTasks.startAsyncTask( function()
									props.pmpRunning = true
									local kMax = props.kMax
									-- if props.batchStacks and props.hasStacks then
										-- kMax=0
									-- elseif props.doBatchSingle then
										-- kMax=1
									-- end
									if props.doBatchSingle then
										if prefs.hasStacks then
											kMax = 0
										else
											kMax = 1
										end
									end
									local xmpTempPath = BatchPhotomatixCom.callPreviewForPreset(kMax, true, props.presetToUse, props)
									BatchUploadTask.outputToLog(string.format("xmpTempDir=%s and exists=%s",xmpTempPath,LrFileUtils.exists(xmpTempPath)))

									-- if not LrFileUtils.exists(xmpTempFile) then
									-- local xmpTempPath = LrPathUtils.parent(xmpTempFile)
									-- local xmpTempPath = LrPathUtils.parent(xmpTempFile)
									local xmpTempFile = nil
									for tempPresetFile in LrFileUtils.directoryEntries(xmpTempPath) do
										if LrPathUtils.extension(tempPresetFile)=="xmp" then
											xmpTempFile=tempPresetFile
											break
										end
									end
									if xmpTempFile then
										local isExistingPreset = false
										local tempPresetName=LrPathUtils.leafName(xmpTempFile)
										local allPresetItems=BatchInputSettings.getPresetItems("AllPresets",false)
										for i,presetItem in ipairs(allPresetItems) do
											if (presetItem.value) then
												local curPresetName=LrPathUtils.leafName(presetItem.value)
												if tempPresetName == curPresetName then
													isExistingPreset = true
													props.curPresetStyle = "AllPresets"
													props.presetToUse=presetItem.value
													break
												end
											end
										end


										if not isExistingPreset then --It is a new custom preset so we save it then select it
											local presetFileName=LrPathUtils.leafName(xmpTempFile)
											BatchUploadTask.outputToLog(string.format("About to save preset: %s",presetName))
											local xmpFile2Save=LrPathUtils.child(customPresetPath,presetFileName)
											BatchUploadTask.outputToLog(string.format("Saving to: %s",xmpFile2Save))
											BatchUploadTask.outputToLog(string.format("Saving from: %s",xmpTempFile))
											LrFileUtils.copy(xmpTempFile,xmpFile2Save)
											props.presetToUse = xmpFile2Save
											local oldPresetStyle = props.curPresetStyle
											-- props.curPresetStyle = "AllPresets" -- or maybe better?: "custom"
											props.curPresetStyle = "custom"
											if (props.curPresetStyle == oldPresetStyle) then --Preset style hasn't changed so we make sure the preset list gets refreshed so that it contains the newly added presetToUse
												props.refreshPresetList = props.refreshPresetList + 1
											end

										end

									end
									-- local tmpXmpPath=LrPathUtils.parent(xmpTempFile)
									-- if tmpXmpPath ~= nil and LrFileUtils.exists(tmpXmpPath) then
										-- LrFileUtils.delete(tmpXmpPath)
									-- end
									if xmpTempPath ~= nil and LrFileUtils.exists(xmpTempPath) then
										LrFileUtils.delete(xmpTempPath)
									end
									props.pmpRunning = false
								end)
							end,
						},
						f: row {
						fill=0.39,
						}
						-- f:static_text {
							-- -- fill=0.21,
							-- title = LOC "$$$/Photomatix/Batch/Input/HdrPresetSection/UseSavedPreset=or use saved preset:",
							-- enabled=LrView.bind("useCustomPreset"),
							-- alignment = 'right',
						-- },
						-- f:popup_menu {
							-- -- fill=0.315,
							-- fill=1,
							-- value=LrView.bind("customPreset"),
							-- -- value=0,
							-- -- items={
								-- -- {title="Load Preset", value=0},
							-- -- },
							-- items=LrView.bind {
								-- keys = { 'doBatchSingle', 'customPreset' },
								-- operation = function( binder, values, fromTable )
									-- if fromTable then
										-- return BatchInputSettings.getCustomPresetItems(values.doBatchSingle)
								   -- end
								-- end
							-- },
							-- enabled=LrView.bind("useCustomPreset"),
						-- },
					},
				},
				f: row {
					fill = 1,
					margin_top = 10,
					f:static_text {
						title = LOC "$$$/Photomatix/Batch/Input/HdrPresetSection/FusionSingleNotice=Note: The preset you selected is a fusion preset. Photos in stacks will be fused, the others skipped.",
						text_color = LrColor(178/256,0,0),
						visible = LrView.bind{
							keys = {'presetToUse', 'doBatchSingle'},
							operation = function( binder, values, fromTable )
								-- LrDialogs.message(string.format("Single fusion notice, fromTable=%s, stacks=%s, unstacked=%s, isFusion=%s", fromTable, prefs.hasStacks, prefs.hasUnstacked, BatchInputSettings.isPresetForFusion(values.presetToUse)))
								if fromTable then
								
									return values.doBatchSingle and prefs.hasStacks and prefs.hasUnstacked and BatchInputSettings.isPresetForFusion(values.presetToUse)
							   end
							end
						},
					},
				},
			},

		},


		f:group_box {
			title = LOC "$$$/Photomatix/Batch/MergeOptions/Title=Merge Options for Bracketed Photos",
			show_title=true,
			fill_horizontal=1,
            margin_top = topGroupMargin,
            margin_bottom = botGroupMargin,
			font = "<system>",
			f:row {
				f:checkbox {
					title = LOC "$$$/Photomatix/Batch/MergeOptions/Align/Checkbox=Align images",
					tooltip=LOC "$$$/Photomatix/Batch/MergeOptions/Align/Tooltip=Corrects misalignment problems when the camera moves slightly between the bracketed frames.  Always check this option when your bracketed photos are taken hand-held, but do not check it if they are stitched panoramas or derived from a single Raw file.",
					value = LrView.bind ("chkAlign"),
					checked_value = true,
					unchecked_value = false,
					enabled=LrView.bind {
						keys = { 'doBatchSingle' },
						operation = function( binder, values, fromTable )
							if fromTable then
								return (not values.doBatchSingle) or prefs.hasStacks
						   end
						end
					},
				},
				f:row {
					-- margin_bottom = f:control_spacing() / 4,
					margin_left=50,
					f:static_text {

						title = LOC "$$$/Photomatix/Batch/MergeOptions/Align/Type=Alignment type:",
						alignment = 'left',
						enabled=LrView.bind {
							keys = { 'doBatchSingle', 'chkAlign' },
							operation = function( binder, values, fromTable )
								if fromTable then
									return (not values.doBatchSingle or prefs.hasStacks) and (values.chkAlign)
							   end
							end
						},
					},

					f:popup_menu {
						value = LrView.bind ("presetAlign"),
						items = {
								{ title = LOC "$$$/Photomatix/Batch/MergeOptions/Align/Tripod=On Tripod", value = "1" },
								{ title = LOC "$$$/Photomatix/Settings/Batch/MergeOptions/Align/HandheldMinMovement=Hand-held (minimal movement) ", value = "3" },
								{ title = LOC "$$$/Photomatix/Settings/Batch/MergeOptions/Align/HandheldStandard=Hand-held (standard)", value = "2" },
								{ title = LOC "$$$/Photomatix/Settings/Batch/MergeOptions/Align/HandheldLargeShifts=Hand-held (large shifts)", value = "0" },
						},
						enabled=LrView.bind {
							keys = { 'doBatchSingle', 'chkAlign' },
							operation = function( binder, values, fromTable )
								if fromTable then
									return (not values.doBatchSingle or prefs.hasStacks) and (values.chkAlign)
							   end
							end
						},

					},
				},
			},
			f:row {
				margin_left=20,
				f:checkbox {
					title = LOC "$$$/Photomatix/Batch/MergeOptions/Align/Crop=Crop aligned images",
					tooltip=LOC "$$$/Photomatix/Batch/MergeOptions/Align/Crop/Tooltip=Checking this option removes the unneeded borders resulting from the alignment adjustments.  Unchecking it disables this, so that the resulting image has exactly the same width and height as the source images, but may have white areas around the edges.",
					-- margin_left=30,
					value = LrView.bind ("chkCrop"),
					-- enabled = LrView.bind("chkAlign"),
					enabled=LrView.bind {
						keys = { 'doBatchSingle', 'chkAlign' },
						operation = function( binder, values, fromTable )
							if fromTable then
								return (not values.doBatchSingle or prefs.hasStacks) and (values.chkAlign)
						   end
						end
					},
					size=mini,
					font = "<system/small>",
					checked_value = true,
					unchecked_value = false,
				},
			},
			f:row {
				--margin_top=f:control_spacing();
				spacing = f:control_spacing(),

				f:checkbox {
					title = LOC "$$$/Photomatix/Batch/MergeOptions/Deghost=Remove ghosts",
					tooltip=LOC "$$$/Photomatix/Batch/MergeOptions/Deghost/Tooltip=Check this option only if your scene includes objects that moved between the bracketed shots. Otherwise, leave it unchecked, as removing ghosts lowers the quality of the merged image.",
					value = LrView.bind ("chkGhosting"),
					checked_value = true,
					unchecked_value = false,
					enabled=LrView.bind {
						keys = { 'doBatchSingle' },
						operation = function( binder, values, fromTable )
							if fromTable then
								return (not values.doBatchSingle) or prefs.hasStacks
						   end
						end
					},
				},
			},

		},
		f:group_box {
			title = LOC "$$$/Photomatix/Batch/Finishing/Title=Finishing",
			show_title=true,
            margin_top = topGroupMargin,
            margin_bottom = botGroupMargin,
			fill_horizontal=1,
			font = "<system>",
			f:row {
				f:row {
					margin_left=30,
					f:static_text {
						title = LOC "$$$/Photomatix/Batch/Finishing/Contrast/Title=Contrast:",
					},
					f:popup_menu {
						value=LrView.bind("cbxContrast"),
						items = {
							{ title= LOC "$$$/Photomatix/Batch/Finishing/Contrast/None=None", value=0},
							{ title= LOC "$$$/Photomatix/Batch/Finishing/Contrast/VeryMild=Very Mild Contrast", value=1},
							{ title= LOC "$$$/Photomatix/Batch/Finishing/Contrast/Mild=Mild Contrast", value=2},
							{ title= LOC "$$$/Photomatix/Batch/Finishing/Contrast/Medium=Medium Contrast", value=3},
							{ title= LOC "$$$/Photomatix/Batch/Finishing/Contrast/Strong=Strong Contrast", value=4},
							{ title= LOC "$$$/Photomatix/Batch/Finishing/Contrast/Extreme=Extreme Contrast", value=5},
						}
					}
				},
				f:row {
					margin_left=50,
					f:static_text {
						title = LOC "$$$/Photomatix/Batch/Finishing/Sharpening/Title=Sharpening:",
					},
					f:popup_menu {
						value=LrView.bind("cbxSharpening"),
						items = {
							{ title= LOC "$$$/Photomatix/Batch/Finishing/Sharpening/None=None", value=0},
							{ title= LOC "$$$/Photomatix/Batch/Finishing/Sharpening/Mild=Mild Sharpening", value=1},
							{ title= LOC "$$$/Photomatix/Batch/Finishing/Sharpening/Medium=Medium Sharpening", value=2},
							{ title= LOC "$$$/Photomatix/Batch/Finishing/Sharpening/Strong=Strong Sharpening", value=3},
						}
					}
				},
				f:row{}, -- Empty row for taking over the remaining space left by the fill_horizontal of the parent group_box
			},
		},
		f:group_box {
			title = LOC "$$$/Photomatix/Batch/Ouput/Title=Output",
			show_title=true,
			fill_horizontal=1,
            margin_top = topGroupMargin,
            margin_bottom = botGroupMargin,
			font = "<system>",

			f:row {
				 fill=1,
					f:static_text {
						title = LOC "$$$/Photomatix/Batch/Output/FileName=File name:",
						fill= 0.18,
						alignment="right",
					},
					f:popup_menu {
						fill=0.30,
						value = LrView.bind ("outputFileNameOption"),
						items = {
							{ title = LOC "$$$/Photomatix/Batch/Output/FileName/CombinedOption=Combined file names", value = "0" },
							{ title = LOC "$$$/Photomatix/Batch/Output/FileName/FirstPhotoOption=File name of first photo", value = "1" },
							-- { separator = true},
							-- { title = LOC "$$$/Photomatix/Batch/Output/FileName/CustomOption=Custom file name...", value = "10" },
							-- { title = LOC "$$$/Photomatix/Batch/Output/FileName/CombinedOption=Combined file names", value = 0 },
							-- { title = LOC "$$$/Photomatix/Batch/Output/FileName/FirstPhotoOption=File name of first photo", value = 1 },
							-- { separator = true},
							-- { title = LOC "$$$/Photomatix/Batch/Output/FileName/CustomOption=Custom file name...", value = 2 },
						},
					},

					f:static_text {
						fill=0.18,
						title = LOC "$$$/Photomatix/Batch/Output/SuffixLabel=Suffix:",
						alignment = "right",
					},
					f:edit_field {
							width_in_chars = 14,
							value = LrView.bind ("fileNameSuffix"),
						},
			},

--[[
			f:row {
				fill=1,
                margin_bottom = 5,

				f:column {
					fill=0.15,
				},
				f:static_text {
					fill=0.85,
					title = LrView.bind {
						keys = { 'outputFileNameOption', 'fileNameSuffix', 'doBatchSingle', 'kMax' },
						operation = function( binder, values, fromTable )
							local curFileName=''
							if fromTable then
								if values.outputFileNameOption == '0' then
									curFileName=BatchInputSettings.defaultFileName(props)
								end
								if values.outputFileNameOption == '1' then
									curFileName=props.firstFileName
								end
								-- if values.fileNameSuffix ~= nil and #(values.fileNameSuffix)>0 then
								if values.fileNameSuffix ~= nil then
									curFileName=string.format('%s%s', curFileName, values.fileNameSuffix)
								end
								BatchUploadTask.outputToLog(string.format("curFileName=%s",curFileName))
								return string.format(LOC "$$$/Photomatix/Batch/Ouput/SampleName=Sample Output Name:  %s", curFileName)
						   end
						   return LrBinding.kUnsupportedDirection
						end,
					},
				}
			},
--]]
			f:row {
				fill=1,
					f:static_text {
						fill=0.18,
						title = LOC "$$$/Photomatix/Batch/Output/Format=File format:",
						alignment="right",
					},
					f:popup_menu {
						fill=0.30,
						tooltip=LOC "$$$/Photomatix/Batch/Output/Format/Tooltip=Format for saving the resulting tone mapped or fused image.",
						value = LrView.bind ("outputFormat"),
						items = {
							{ title = "JPEG", value = "jpg" },
							{ title = "TIFF 8-bit", value = "tif8" },
							{ title = "TIFF 16-bit ", value = "tif16" },
						},
					},
					f:static_text {
						fill=0.18,
						title = LOC "$$$/Photomatix/Batch/Output/ColorSpace=Color space:",
						alignment="right",
					},
					f:popup_menu {
						fill=0.27,
						value = LrView.bind ("colorProfile"),
						items = {
							{ title =  LOC "$$$/Photomatix/Batch/Output/ColorSpace/SRGB=sRGB", value = "sRGB" },
							{ title = LOC "$$$/Photomatix/Batch/Output/ColorSpace/Adobe=Adobe RGB", value = "AdobeRGB" },
							{ title =  LOC "$$$/Photomatix/Batch/Output/ColorSpace/ProPhoto=ProPhoto RGB", value = "ProPhotoRGB" },
						},
					},
				},
			
			},
	}

	local result = LrDialogs.presentModalDialog({
		title = LOC "$$$/Photomatix/Batch/Input/Title=Photomatix Batch",
		contents = batchInputUI,
		actionVerb = LOC "$$$/Photomatix/Batch/Input/DoBatch=Batch",
		actionBinding = {
			-- enabled=LrView.bind {
			enabled = {
				bind_to_object = props,
				-- keys = { 'builtinPreset', 'useCustomPreset', 'customPreset' },
				keys = { 'presetToUse', 'doBatchSingle' },
				operation = function( binder, values, fromTable )
					if fromTable then
						-- return (values.builtinPreset~="") and (not values.useCustomPreset)
						-- return ((values.builtinPreset~="") and (not values.useCustomPreset)) or ((values.customPreset~="") and (values.useCustomPreset))
						-- return ((values.presetToUse~=""))
						local shouldEnable = (values.presetToUse ~= "")
						if shouldEnable then
							local isFusionForOnlySingles = values.doBatchSingle and (not prefs.hasStacks) and BatchInputSettings.isPresetForFusion(values.presetToUse)
							shouldEnable = not isFusionForOnlySingles
						end
						return shouldEnable
				   end
				end
			},

			-- enabled = {
				-- bind_to_object = props,
				-- key = 'actionEnabled'
			-- },
		},
		save_frame="mainBatchFormLocation",
	})

	if (result=='ok') then

		-- prefs.processType='ToneMap'

		BatchInputSettings.saveStickySettings(props)
		doProcess = true
	end

end )
	return doProcess

end