-- -----------------------------------------------------------------------------
-- EnhancedStackSplit by kunda
-- -----------------------------------------------------------------------------
-- Features:
-- # 1-Click mode:
--   -> 'mode' Button (toggle: '1-Click mode' / 'Original WoW mode'[DEFAULT])
--   Split a stack with just one click when you click on one of the numbered
--   buttons (OK(1),2,3,4,5,6,7,8,9,10 and 20). Split is placed on the cursor,
--   so you can place it in a slot, trade, buy, destroy or what ever.
-- # Auto Split mode:
--   -> 'auto' Button
--   Automatically splits a stack and place the splitted item(s) in a free bag
--   slot when you click on one of the numbered buttons (1,2,3,4,5,6,7,8,9,10
--   and 20). Free bag slots depends on ItemFamily from item you wanna split
--   and on ItemFamily from bag(s) with free slots. Items are placed from top
--   left to bottom right slot in a bag.
--   example: Free bagslots = 20
--            Item with StackSize = 137
--            - you click on 5
--              you get: 20 items with 5 Itemstacksize in your bag(s)
--                       leftover = 37
--                       (20 because free bagslots = 20)
--            - you click on 10
--              you get: 13 items with 10 Itemstacksize in your bag(s)
--                       leftover = 7
--            leftover and last n-stacksize remains in the original bagslot
--   Note: Auto-splitted items are only placed in the five normal bags including
--         special bags (or less if you have not five bags).
--         The 'Auto Split mode' should be only accessible via bags and bank, but
--         I did not find a good way to do this. So it's possible that this mode
--         is available where it shouldn't be. If you try to auto split in such
--         cases the SplitFrame can stuck. Just press ESC to close it.
--         Bag and Bank Addons MUST provide the bag/slot IDs in the same way the
--         original Blizzard UI does, otherwise EnhancedStackSplit can not
--         auto-split such stacks or you can get the stuck-error I described above.
--         Most bag/bank addons works perfect with EnhancedStackSplit because the
--         addon authors made a good job :)
-- # Chat Announce:
--   To disable Chat Messages ('Chat Announce'):
--   Options (ESC) -> Interface -> AddOns Tab -> EnhancedStackSplit
--
-- Credits:
-- LockSlot functions from ClosetGnome by Rabbit
--
-- Note:
-- You can shift-click on any stackable item, press a number on your
-- keyboard and click OK or press ENTER to split a stack!!!
--
-- If you get an error while using this Addon please post here:
-- http://www.wowace.com/forums/index.php?topic=9612.0
-- -----------------------------------------------------------------------------

-- Localization START ----------------------------------------------------------
local LOC_CHATOUTPUT = CHAT.." "..CHAT_ANNOUNCE -- Localized Blizzard Global Strings "Chat Announce"

local L = GetLocale()
local LOC_ORIGINAL = "Original WoW mode"
local LOC_1CLICK = "1-Click mode"
local LOC_AUTO = "Auto Split mode"
local LOC_MODE = "mode"
local LOC_MODE_AUTO = "auto"
local LOC_BAGSLOTS = "Free Bag Slots"
local LOC_LEFTOVER = "leftover"
local LOC_MODE_CHANGE = "StackSplit click mode changed to '%s'."
local LOC_ATTENTION = "%sATTENTION:%s no OK to confirm!!!"
if L == "deDE" then
	LOC_ORIGINAL = "Original WoW Modus"
	LOC_1CLICK = "1-Klick Modus"
	LOC_AUTO = "Auto Split Modus"
	LOC_MODE = "Modus"
	LOC_MODE_AUTO = "auto"
	LOC_BAGSLOTS = "Freie Taschenplätze"
	LOC_LEFTOVER = "rest"
	LOC_MODE_CHANGE = "StackSplit Klick Modus auf '%s' geändert."
	LOC_ATTENTION = "%sACHTUNG:%s kein OK zur Bestätigung!!!"
elseif L == "esES" then
	LOC_ORIGINAL = "Modo original del WOW"
	LOC_1CLICK = "Modo 1-Clic"
	--LOC_AUTO = "Auto Split mode" -- NEEDS TRANSLATION !!!
	LOC_MODE = "modo"
	--LOC_MODE_AUTO = "auto" -- NEEDS TRANSLATION !!!
	--LOC_BAGSLOTS = "Free Bag Slots" -- NEEDS TRANSLATION !!!
	--LOC_LEFTOVER = "leftover" -- NEEDS TRANSLATION !!!
	LOC_MODE_CHANGE = "Modo de StackSplit cambiado a '%s'."
	LOC_ATTENTION = "%sATENCION:%s ningún OK para confirmar!!!"
elseif L == "frFR" then
	LOC_ORIGINAL = "Mode WoW original"
	LOC_1CLICK = "Mode 1-Clic"
	--LOC_AUTO = "Auto Split mode" -- NEEDS TRANSLATION !!!
	LOC_MODE = "mode"
	--LOC_MODE_AUTO = "auto" -- NEEDS TRANSLATION !!!
	--LOC_BAGSLOTS = "Free Bag Slots" -- NEEDS TRANSLATION !!!
	--LOC_LEFTOVER = "leftover" -- NEEDS TRANSLATION !!!
	LOC_MODE_CHANGE = "Mode StackSplit changé en '%s'."
	LOC_ATTENTION = "%sATTENTION:%s pas de OK pour confirmer!!!"
elseif L == "zhTW" then
	LOC_ORIGINAL = "原始WoW格式" 
	LOC_1CLICK = "單鍵點擊模式"
	LOC_AUTO = "自動分拆模式"
	LOC_MODE = "模式切換" 
	LOC_MODE_AUTO = "自動" 
	LOC_BAGSLOTS = "剩餘背包空格" 
	LOC_LEFTOVER = "剩餘" 
	LOC_MODE_CHANGE = "點擊模式更改為 '%s'." 
	LOC_ATTENTION = "%s注意:%s此種模式沒有確認功能!!!" 
end
-- Localization END ------------------------------------------------------------

EnhancedStackSplit_Save = {} -- SavedVariable table
EnhancedStackSplit_Save.version = 2
if not EnhancedStackSplit_Save.mode then EnhancedStackSplit_Save.mode = 1 end
if not EnhancedStackSplit_Save.chat then EnhancedStackSplit_Save.chat = true end

local EnhancedStackSplit = CreateFrame("Frame", "EnhancedStackSplit")
local splitMode = {[1] = LOC_ORIGINAL, [2] = LOC_1CLICK, [3] = LOC_AUTO}
local autoSplitMode = false
local splitItemBag
local splitItemSlot
local maxStackSize = 0
local slotLocks = nil
local autoSplitStackCount
local autoSplitNumStacks
local autoSplitNumber
local autoSplitLeftOver
local autoSplitItemLink
local blockedFrames = {
	[1] = "MerchantItem",
	[2] = "GuildBank"
	}
local mainBankFrames = {
	[1] = "BankFrame", -- default Blizzard Bank Frame
	[2] = "TBnkFrame" -- TBag-Shefki-20080611-r163
	}

-- Helper functions START ------------------------------------------------------
local function reclaim(t) -- LockSlot function
	if type(t) ~= "table" then return end
	for k, v in pairs(t) do
		if type(v) == "table" then
			t[k] = reclaim(v)
		else
			t[k] = nil
		end
	end
	t = nil
	return nil
end

local function LockSlot(bag, slot) -- LockSlot function
	if not slotLocks then slotLocks = {} end
	if not slotLocks[bag] then slotLocks[bag] = {} end
	slotLocks[bag][slot] = true
end

local function IsSlotLocked(bag, slot) -- LockSlot function
	if slotLocks and slotLocks[bag] and slotLocks[bag][slot] then
		return true
	end
	return false
end

local function ClearSlotLocks() -- LockSlot function
	slotLocks = reclaim(slotLocks)
end

local function Print(text)
	if EnhancedStackSplit_Save.chat and DEFAULT_CHAT_FRAME then
		DEFAULT_CHAT_FRAME:AddMessage("|cffffff7fEnhancedStackSplit: |r"..text)
	end
end

local function IsBag(bag)
	local invID = ContainerIDToInventoryID(bag)
	local bagLink = GetInventoryItemLink("player",invID)
	if bagLink then
		return bagLink
	else
		return false
	end
end

local function GetFreeBagSlots()
	local freeSlots = GetContainerNumFreeSlots(0)
	local containerBagType = 0
	local itemBagType = GetItemFamily(autoSplitItemLink)
	for bag = 1, NUM_BAG_SLOTS do
		local bagLink = IsBag(bag)
		if bagLink then
			containerBagType = GetItemFamily(bagLink)
			if containerBagType == 0 or containerBagType == itemBagType then
				freeSlots = freeSlots + GetContainerNumFreeSlots(bag)
			end
		end
	end
	return freeSlots
end

local function GetFreeSlot()
	local containerBagType = 0
	local itemBagType = GetItemFamily(autoSplitItemLink)
	local goodBag = true
	for bag = 0, NUM_BAG_SLOTS do
		if bag > 0 then
			local bagLink = IsBag(bag)
			if bagLink then
				containerBagType = GetItemFamily(bagLink)
				if containerBagType == 0 or containerBagType == itemBagType then
					goodBag = true
				else
					goodBag = false
				end
			end
		end
		if goodBag then
			for slot = 1, GetContainerNumSlots(bag) do
				if not IsSlotLocked(bag, slot) then
					if not GetContainerItemLink(bag, slot) then
						return bag, slot
					end
				end
			end
		end
	end
	return nil
end

local function AutoSplitCalc(num)
	local freeSlots = GetFreeBagSlots()
	local numStacks = floor(maxStackSize/num)
	if numStacks > freeSlots then
		numStacks = freeSlots
	end
	local leftOver = maxStackSize-(numStacks*num)
	return freeSlots or 0, numStacks or 0, leftOver or 0
end
-- Helper functions END --------------------------------------------------------

function EnhancedStackSplit_OnEvent()
	if event == "ADDON_LOADED" then
		if arg1 == "EnhancedStackSplit" then
			hooksecurefunc("OpenStackSplitFrame", EnhancedStackSplit_OpenStackSplitFrame)
			EnhancedStackSplit_CreateFrames()
			EnhancedStackSplit_CreateInterfaceOptions()
		end
	end
	if event == "ITEM_LOCK_CHANGED" then
		EnhancedStackSplit_CheckItemLock()
	end
end

function EnhancedStackSplit_ModeToggle(mode)
	if mode == 3 then
		autoSplitMode = true
		Print(string.format(LOC_MODE_CHANGE,"|cffffff99"..splitMode[3].."|r").." "..string.format(LOC_ATTENTION,"|cffff9900","|r"))
		EnhancedStackSplit_ModeSettings(3)
	else
		if not autoSplitMode then
			if EnhancedStackSplit_Save.mode == 2 then
				EnhancedStackSplit_Save.mode = 1
				Print(string.format(LOC_MODE_CHANGE,"|cffffff99"..splitMode[1].."|r"))
			else
				EnhancedStackSplit_Save.mode = 2
				Print(string.format(LOC_MODE_CHANGE,"|cffffff99"..splitMode[2].."|r").." "..string.format(LOC_ATTENTION,"|cffff9900","|r"))
			end
		end
		autoSplitMode = false
		EnhancedStackSplit_ModeSettings(EnhancedStackSplit_Save.mode)
	end
end

function EnhancedStackSplit_ModeSettings(mode)
	for i=1, 10 do
		getglobal("EnhancedStackSplitButton"..i):Enable()
	end
	if mode == 3 then
		if maxStackSize > 1 and maxStackSize < 11 then
			for i=maxStackSize-1, 10 do
				getglobal("EnhancedStackSplitButton"..i):Disable()
			end
		end
		if maxStackSize > 10 and maxStackSize < 21 then
			EnhancedStackSplitButton10:Disable()
		end
		EnhancedStackSplitAutoSplitButton:Disable()
		StackSplitOkayButton:Hide()
		StackSplitLeftButton:Hide()
		StackSplitRightButton:Hide()
		EnhancedStackSplitAutoTextureFrame:Show()
		EnhancedStackSplitAuto1Button:Show()
		EnhancedStackSplitTextAutoText1:Show()
		EnhancedStackSplitTextAutoText2:Show()
		EnhancedStackSplitTextAutoText1:SetText("|cffffffff"..LOC_BAGSLOTS..": |cffff8000"..GetFreeBagSlots())
		EnhancedStackSplitTextAutoText2:SetText("")
	else
		if maxStackSize > 1 and maxStackSize < 11 then
			for i=maxStackSize, 10 do
				getglobal("EnhancedStackSplitButton"..i):Disable()
			end
		end
		if not autoSplitItemLink then
			EnhancedStackSplitAutoSplitButton:Disable()
		else
			EnhancedStackSplitAutoSplitButton:Enable()
		end
		EnhancedStackSplitAutoTextureFrame:Hide()
		EnhancedStackSplitAuto1Button:Hide()
		EnhancedStackSplitTextAutoText1:Hide()
		EnhancedStackSplitTextAutoText2:Hide()
		StackSplitOkayButton:Show()
		StackSplitLeftButton:Show()
		StackSplitRightButton:Show()
	end
	EnhancedStackSplitTextFrameTXT:SetText(splitMode[mode])
end

function EnhancedStackSplit_CreateInterfaceOptions()
	local options = CreateFrame("FRAME", "EnhancedStackSplit_InterfaceOptions")
	options.name = "EnhancedStackSplit"
	local cb = CreateFrame("CheckButton", "EnhancedStackSplit_InterfaceOptions_Chat", EnhancedStackSplit_InterfaceOptions, "InterfaceOptionsCheckButtonTemplate")
	EnhancedStackSplit_InterfaceOptions_Chat:SetPoint("TOPLEFT", 10, -10)
	EnhancedStackSplit_InterfaceOptions_ChatText:SetText(LOC_CHATOUTPUT)
	EnhancedStackSplit_InterfaceOptions_Chat:SetChecked(EnhancedStackSplit_Save.chat)
	EnhancedStackSplit_InterfaceOptions_Chat:SetScript("OnClick", function(self)
		EnhancedStackSplit_Save.chat = not EnhancedStackSplit_Save.chat
	end)
	InterfaceOptions_AddCategory(options)
end

function EnhancedStackSplit_CreateFrames()
	local f = CreateFrame("Frame", "EnhancedStackSplitTopTextureFrame", StackSplitFrame)
	f:SetPoint("TOPLEFT", "StackSplitFrame", "TOPLEFT", 0, 2)
	--f:SetFrameStrata("HIGH")
	f:SetWidth(172)
	f:SetHeight(20)
	local x = f:CreateTexture("EnhancedStackSplitTopTextureFrameTexture", "BACKGROUND")
	x:SetTexture("Interface\\MoneyFrame\\UI-MoneyFrame2")
	x:SetAllPoints(f)
	x:SetTexCoord(0, 172/256, 0, 20/128)
	f.texture = x
	local t = f:CreateFontString("EnhancedStackSplitTextFrameTXT", "BACKGROUND", "GameFontNormalSmall")
	t:SetPoint("TOP", "EnhancedStackSplitTopTextureFrame", "TOP", 1, -8)
	t:SetJustifyH("CENTER")

	local f = CreateFrame("Frame", "EnhancedStackSplitBottomTextureFrame", StackSplitFrame)
	f:SetPoint("TOPLEFT", "StackSplitFrame", "BOTTOMLEFT", 0, 20)
	--f:SetFrameStrata("HIGH")
	f:SetWidth(172)
	f:SetHeight(50)
	local x = f:CreateTexture("EnhancedStackSplitBottomTextureFrameTexture", "BACKGROUND")
	x:SetTexture("Interface\\MoneyFrame\\UI-MoneyFrame")
	x:SetAllPoints(f)
	x:SetTexCoord(0, 172/256, 48/128, 96/128)
	f.texture = x

	local f = CreateFrame("Frame", "EnhancedStackSplitAutoTextureFrame", StackSplitFrame)
	f:SetPoint("TOPLEFT", "StackSplitFrame", "TOPLEFT", 16, -13)
	--f:SetFrameStrata("HIGH")
	f:SetWidth(142)
	f:SetHeight(37)
	f:Hide()
	local x = f:CreateTexture("EnhancedStackSplitAutoTextureFrameTexture", "BACKGROUND")
	x:SetTexture("Interface\\MoneyFrame\\UI-MoneyFrame2")
	x:SetAllPoints(f)
	x:SetTexCoord(16/256, 158/256, 13/128, 50/128)
	f.texture = x

	local x = f:CreateTexture("EnhancedStackSplitAutoTextureFrameWarningTexture", "HIGH")
	x:SetTexture("Interface\\DialogFrame\\DialogAlertIcon")
	x:SetPoint("BOTTOM", "EnhancedStackSplitAutoTextureFrame", "TOPRIGHT", 6, 0)
	x:SetWidth(41)
	x:SetHeight(32)
	x:SetTexCoord(11/64, 52/64, 16/64, 48/64)
	f.texture = x
	local x = f:CreateTexture("EnhancedStackSplitAutoTextureFrameWarningTexture", "HIGH")
	x:SetTexture("Interface\\DialogFrame\\DialogAlertIcon")
	x:SetPoint("BOTTOM", "EnhancedStackSplitAutoTextureFrame", "TOPLEFT", -6, 0)
	x:SetWidth(41)
	x:SetHeight(32)
	x:SetTexCoord(11/64, 52/64, 16/64, 48/64)
	f.texture = x

	EnhancedStackSplit_CreateButton("EnhancedStackSplitAuto1Button",StackSplitFrame,"StackSplitFrame",64,"RIGHT","BOTTOM",-3,40,"1",function() EnhancedStackSplit_Split(1) end,function() EnhancedStackSplit_AutoSplitInfo(1) end)
	EnhancedStackSplitAuto1Button:Hide()

	local t = f:CreateFontString("EnhancedStackSplitTextAutoText1", "BACKGROUND", "GameFontNormalSmall")
	t:SetPoint("TOP", "EnhancedStackSplitTextFrameTXT", "BOTTOM", 0, -2)
	t:SetJustifyH("CENTER")
	local t = f:CreateFontString("EnhancedStackSplitTextAutoText2", "BACKGROUND", "GameFontNormalSmall")
	t:SetPoint("TOP", "EnhancedStackSplitTextAutoText1", "BOTTOM", 0, -2)
	t:SetJustifyH("CENTER")

	EnhancedStackSplit_CreateButton("EnhancedStackSplitButton1" ,EnhancedStackSplitBottomTextureFrame,"EnhancedStackSplitBottomTextureFrame",18,"TOPLEFT","TOPLEFT" , 12,  9, "2",function() EnhancedStackSplit_Split(2) end ,function() EnhancedStackSplit_AutoSplitInfo(2) end)
	EnhancedStackSplit_CreateButton("EnhancedStackSplitButton2" ,EnhancedStackSplitBottomTextureFrame,"EnhancedStackSplitBottomTextureFrame",18,"TOPLEFT","TOPLEFT" , 31,  9, "3",function() EnhancedStackSplit_Split(3) end ,function() EnhancedStackSplit_AutoSplitInfo(3) end)
	EnhancedStackSplit_CreateButton("EnhancedStackSplitButton3" ,EnhancedStackSplitBottomTextureFrame,"EnhancedStackSplitBottomTextureFrame",18,"TOPLEFT","TOPLEFT" , 50,  9, "4",function() EnhancedStackSplit_Split(4) end ,function() EnhancedStackSplit_AutoSplitInfo(4) end)
	EnhancedStackSplit_CreateButton("EnhancedStackSplitButton4" ,EnhancedStackSplitBottomTextureFrame,"EnhancedStackSplitBottomTextureFrame",18,"TOPLEFT","TOPLEFT" , 69,  9, "5",function() EnhancedStackSplit_Split(5) end ,function() EnhancedStackSplit_AutoSplitInfo(5) end)
	EnhancedStackSplit_CreateButton("EnhancedStackSplitButton5" ,EnhancedStackSplitBottomTextureFrame,"EnhancedStackSplitBottomTextureFrame",18,"TOPLEFT","TOPLEFT" , 88,  9, "6",function() EnhancedStackSplit_Split(6) end ,function() EnhancedStackSplit_AutoSplitInfo(6) end)
	EnhancedStackSplit_CreateButton("EnhancedStackSplitButton6" ,EnhancedStackSplitBottomTextureFrame,"EnhancedStackSplitBottomTextureFrame",18,"TOPLEFT","TOPLEFT" ,107,  9, "7",function() EnhancedStackSplit_Split(7) end ,function() EnhancedStackSplit_AutoSplitInfo(7) end)
	EnhancedStackSplit_CreateButton("EnhancedStackSplitButton7" ,EnhancedStackSplitBottomTextureFrame,"EnhancedStackSplitBottomTextureFrame",18,"TOPLEFT","TOPLEFT" ,126,  9, "8",function() EnhancedStackSplit_Split(8) end ,function() EnhancedStackSplit_AutoSplitInfo(8) end)
	EnhancedStackSplit_CreateButton("EnhancedStackSplitButton8" ,EnhancedStackSplitBottomTextureFrame,"EnhancedStackSplitBottomTextureFrame",18,"TOPLEFT","TOPLEFT" ,145,  9, "9",function() EnhancedStackSplit_Split(9) end ,function() EnhancedStackSplit_AutoSplitInfo(9) end)
	EnhancedStackSplit_CreateButton("EnhancedStackSplitButton9" ,EnhancedStackSplitBottomTextureFrame,"EnhancedStackSplitBottomTextureFrame",24,"TOPLEFT","TOPLEFT" , 30,-11,"10",function() EnhancedStackSplit_Split(10) end,function() EnhancedStackSplit_AutoSplitInfo(10) end)
	EnhancedStackSplit_CreateButton("EnhancedStackSplitButton10",EnhancedStackSplitBottomTextureFrame,"EnhancedStackSplitButton9"           ,24,"TOPLEFT","TOPRIGHT",  0,  0,"20",function() EnhancedStackSplit_Split(20) end,function() EnhancedStackSplit_AutoSplitInfo(20) end)

	local w
	local wsum = 48
	w = EnhancedStackSplit_CreateButton("EnhancedStackSplitModeTXTButton",EnhancedStackSplitBottomTextureFrame,"EnhancedStackSplitButton10",64,"TOPLEFT","TOPRIGHT",0,0,LOC_MODE,function() EnhancedStackSplit_ModeToggle(1) end)
	EnhancedStackSplitModeTXTButton:SetWidth(w)
	wsum = wsum + w
	w = EnhancedStackSplit_CreateButton("EnhancedStackSplitAutoSplitButton",EnhancedStackSplitBottomTextureFrame,"EnhancedStackSplitModeTXTButton",18,"TOPLEFT","TOPRIGHT",0,0,LOC_MODE_AUTO,function() EnhancedStackSplit_ModeToggle(3) end)
	EnhancedStackSplitAutoSplitButton:SetWidth(w)
	wsum = wsum + w
	
	local xdim = ceil((172+2-wsum)/2)
	EnhancedStackSplitButton9:SetPoint("TOPLEFT", "EnhancedStackSplitBottomTextureFrame", "TOPLEFT", xdim, -13)
	EnhancedStackSplit_ModeSettings(EnhancedStackSplit_Save.mode)
end

function EnhancedStackSplit_CreateButton(name, parent, anchorparent, width, anchorp, anchorrp, adimx, adimy, text, func1, func2)
	local b = CreateFrame("Button", name, parent, "UIPanelButtonTemplate")
	b:SetWidth(width)
	b:SetHeight(24)
	b:SetPoint(anchorp, anchorparent, anchorrp, adimx, adimy)
	b:SetText(text)
	b:SetScript("OnClick", func1)
	if func2 then
		b:SetScript("OnEnter", func2)
	end
	return ceil(b:GetTextWidth())+10
end

function EnhancedStackSplit_AutoSplitInfo(num)
	local freeSlots, numStacks, leftOver = AutoSplitCalc(num)
	EnhancedStackSplitTextAutoText2:SetText("|cffffffff"..maxStackSize.." | |cffff8000"..numStacks.."|cffffffffx "..num.." | "..LOC_LEFTOVER.."="..leftOver.."|r")
end

function EnhancedStackSplit_AutoSplitButtonToggle(toggle)
	if toggle then
		for i=1, 10 do
			getglobal("EnhancedStackSplitButton"..i):Enable()
		end
		EnhancedStackSplitAuto1Button:Enable()
		EnhancedStackSplitModeTXTButton:Enable()
		StackSplitCancelButton:Enable()
	else
		for i=1, 10 do
			getglobal("EnhancedStackSplitButton"..i):Disable()
		end
		EnhancedStackSplitAuto1Button:Disable()
		EnhancedStackSplitModeTXTButton:Disable()
		StackSplitCancelButton:Disable()
	end
end

function EnhancedStackSplit_OpenStackSplitFrame(maxStack, parent, anchor, anchorTo)
	if maxStack < 2 then return end

	splitItemBag = StackSplitFrame.owner:GetParent():GetID()
	splitItemSlot = StackSplitFrame.owner:GetID()

	local splitItemName = StackSplitFrame.owner:GetParent():GetName()
	if splitItemName then
		for i = 1, #mainBankFrames do -- this needs some better solution
			if string.find(splitItemName, mainBankFrames[i]) then
				splitItemBag = -1
			end
		end
		for i = 1, #blockedFrames do -- this needs some better solution
			if string.find(splitItemName, blockedFrames[i]) then
				splitItemBag = nil
			end
		end
	end

	autoSplitItemLink = nil
	if splitItemBag then
		autoSplitItemLink = GetContainerItemLink(splitItemBag, splitItemSlot)
	end

	maxStackSize = maxStack
	StackSplitFrame:SetPoint(anchor, parent, anchorTo, 0, 14)
	StackSplitOkayButton:SetPoint("RIGHT", "StackSplitFrame", "BOTTOM", -3, 40)
	StackSplitCancelButton:SetPoint("LEFT", "StackSplitFrame", "BOTTOM", 5, 40)
	autoSplitMode = false
	EnhancedStackSplit_AutoSplitButtonToggle(true)
	EnhancedStackSplitTextFrameTXT:SetText(splitMode[EnhancedStackSplit_Save.mode])
	EnhancedStackSplit_ModeSettings(EnhancedStackSplit_Save.mode)
end

function EnhancedStackSplit_Split(num)
	if autoSplitMode then
		local freeSlots, numStacks, leftOver = AutoSplitCalc(num)
		autoSplitStackCount = 0
		autoSplitNumStacks = numStacks
		autoSplitLeftOver = leftOver
		autoSplitNumber = num
		ClearSlotLocks()
		EnhancedStackSplit_AutoSplitButtonToggle(false)
		EnhancedStackSplit_AutoSplit(autoSplitNumStacks, autoSplitNumber, autoSplitLeftOver)
	else
		EnhancedStackSplit_SetNewSplitSize(num)
	end
end

function EnhancedStackSplit_CheckItemLock()
	if StackSplitFrame:IsShown() and StackSplitFrame.owner and splitItemBag and splitItemSlot then
		if arg1 and arg2 then
			if arg1 == splitItemBag and arg2 == splitItemSlot then
				local locked = select(3, GetContainerItemInfo(splitItemBag, splitItemSlot))
				if not locked then
					EnhancedStackSplit_AutoSplit(autoSplitNumStacks, autoSplitNumber, autoSplitLeftOver)
				end
			end
		end
	end
end

function EnhancedStackSplit_AutoSplit(numStacks, num, leftOver)
	if leftOver == 0 then
		if autoSplitStackCount == numStacks-1 then
			StackSplitFrame:Hide() return
		end
	else
		if autoSplitStackCount == numStacks then
			StackSplitFrame:Hide() return
		end
	end
	local bag, slot = GetFreeSlot()
	SplitContainerItem(splitItemBag, splitItemSlot, num)
	if bag ~= nil then
		LockSlot(bag, slot)
		PickupContainerItem(bag, slot)
	end
	autoSplitStackCount = autoSplitStackCount + 1
end

function EnhancedStackSplit_SetNewSplitSize(num)
	if num >= StackSplitFrame.maxStack then
		num = StackSplitFrame.maxStack
		StackSplitRightButton:Disable()
	end
	if num < StackSplitFrame.maxStack then
		StackSplitRightButton:Enable()
	end
	StackSplitLeftButton:Enable()
	StackSplitFrame.split = num
	StackSplitText:SetText(num)
	if EnhancedStackSplit_Save.mode == 2 then
		StackSplitFrameOkay_Click()
	end
end

EnhancedStackSplit:RegisterEvent("ITEM_LOCK_CHANGED")
EnhancedStackSplit:RegisterEvent("ADDON_LOADED")
EnhancedStackSplit:SetScript("OnEvent", EnhancedStackSplit_OnEvent)