--[[
		Mouse File Browser
		by:
			Stiepen irc(Kilobyte)
			Cruor
			BigSHinyToys
		
		note: send link to nightin9ale on CC forums
		note 2: Permission given to NDFJay to modify this for NDF-OS
--]]

local tArgs = {...}
local ver = "Modified for NDF-OS"
local sTitle = "File Browser"
local bugTest, norun, dir, showAll
local _tArgs = {}
local cloudPath = "/documents/cloud"
local function help()
  print("Usage: browser [-d] [-h] [-a] [--debug] [--help] [--dir <dir>] [--all]")
  print("--debug or -d: enable debug mode")
  print("--help or -h: display this screen")
  print("--dir: define initial directory")
  print("--all or -a: show hidden files")
  print("-u: update")
end

local function titleBar()
term.setBackgroundColor(tbColor)
term.setTextColor(tbtColor)
term.setCursorPos(1,1)
term.clearLine()
term.setCursorPos(2,1)
print("[Begin] [Close]")
end

for a = 1, #tArgs do
	if tArgs[a]:sub(1,2) == "--" then
		local cmd = tArgs[a]:sub(3):lower()
		if cmd == "debug" then
			bugTest = true
		elseif cmd == "help" then
			help()
			norun = true
		elseif cmd == "dir" then
			dir = tArgs[a+1]
			a = a + 1
		elseif cmd == "all" then
			showAll = true
		end
	elseif tArgs[a]:sub(1,1) == "-" then
		for b = 2, #tArgs[a] do
			cmd = tArgs[a]:sub(b, b)
			if cmd == "d" then
				bugTest = true
			elseif cmd == "h" then
				help()
				norun = true
			elseif cmd == "p" then
				dir = tArgs[a+1]
				a = a + 1
			elseif cmd == "a" then
				showAll = true
			elseif cmd == "u" then

				print("Checking for Updates")
				local isHTTP = false
				local response
				if http then
					isHTTP = true
					print("http on")
					response = http.get("http://pastebin.com/raw.php?i=rLbnyM1U")
				end
				local flag = false
				local isNewFlag = false
				local newVerID
				if response and isHTTP then
					print("recived")
					local sInfo = response.readLine()
					print(sInfo)
					while sInfo do
						print(sInfo)
						if flag then
							if sInfo == ver then
								print("Mouse File Browser is up to date")
								break
							else
								newVerID = sInfo
								flag = false
								isNewFlag = true
							end
						elseif sInfo == sTitle then
							flag = true
						elseif isNewFlag then
							isNewFlag = sInfo
							response.close()
							break
						end
						sInfo = response.readLine()
					end
					if isNewFlag then
						print("New vershion avalible "..newVerID)
						print('downloading to \Browser')
						if fs.exists("Browser") then
							write("Browser exists OverWrite Browser Y/N : ")
							local input = string.lower(read())
							while input ~= "y" and input ~= "n" do
								print("y or n required")
								input = string.lower(read())
							end
							if input == "y" then
								print("Over Writeing Browser")
								print("Downloading new File")
								local response = http.get("http://pastebin.com/raw.php?i="..isNewFlag)
								if response then
									print("file downloaded")
									print("installing")
									fs.delete("Browser")
									local handel = fs.open("Browser","w")
									if handel then
										handel.write(response.readAll())
										handel.close()
										print("Update Complete")
									end
									response.close()
								end
							else
								print("Update aborted")
							end
						else
							print("Downloading new File")
							local response = http.get("http://pastebin.com/raw.php?i="..isNewFlag)
							if response then
								print("file downloaded")
								print("installing")
								local handel = fs.open("Browser","w")
								if handel then
									handel.write(response.readAll())
									handel.close()
									print("Update Complete")
								end
								response.close()
							end
						end
					end
				elseif isHTTP then
					print("Error downloading update file Please contact BigSHinyToys on the CC forums")
					print("http://www.computercraft.info/forums2/index.php?/topic/5509-advanced-computer-mouse-file-browser/")
				elseif not isHTTP then
					print("HTTP API is turned off")
					print("Access Computer Craft Configer and change line")
					print([[enableapi_http {
# Enable the "http" API on Computers
general=false
}
TO THIS :
enableapi_http {
# Enable the "http" API on Computers
general=true
}]])
				end
				notCMD = false
				norun = true
			end
		end
	else
		table.insert(_tArgs, tArgs[a])
	end
end

if (not dir) and shell and shell.dir then
	dir = shell.dir()
end

if dir and shell and shell.resolve then
	dir = shell.resolve(dir)
end

dir = dir or "/"

if bugTest then -- this is that the var is for testing
	print("Dir: "..dir)
	os.startTimer(4)
	os.pullEvent()
end

local function clear()
	term.setBackgroundColor(colors.black)
	term.setTextColor(colors.white)
	term.clear()
	term.setCursorBlink(false)
	term.setCursorPos(1,1)
end

--[[
		Code thanks to Cruor 
		http://www.computercraft.info/forums2/index.php?/topic/5802-support-for-shell/
]]--
local function fixArgs(...)
	local tReturn={}
	local str=table.concat({...}," ")
	local sMatch
	while str and #str>0 do
		if string.sub(str,1,1)=="\"" then
			sMatch, str=string.match(str, "\"(.-)\"%s*(.*)")
		else
			sMatch, str=string.match(str, "(%S+)%s*(.*)")
		end
		table.insert(tReturn,sMatch)
	end
	return tReturn
end
--[[ end Cruor function ]]--


-- modified read made to play nice with coroutines

local function readMOD( _sReplaceChar, _tHistory,_wdth)
	local sLine = ""
	term.setCursorBlink( true )

	local nHistoryPos = nil
	local nPos = 0
    if _sReplaceChar then
		_sReplaceChar = string.sub( _sReplaceChar, 1, 1 )
	end
	
	local sx, sy = term.getCursorPos()	

	local w, h = term.getSize()
	if _wdth and type(_wdth) == "number" then
		w = sx + _wdth - 1
	end
	
	local function redraw( _sCustomReplaceChar )
		local nScroll = 0
		if sx + nPos >= w then
			nScroll = (sx + nPos) - w
		end
			
		term.setCursorPos( sx + _wdth - 1, sy )
		term.write(" ")
		term.setCursorPos( sx, sy )
		local sReplace = _sCustomReplaceChar or _sReplaceChar
		if sReplace then
			term.write( string.rep(sReplace,_wdth) )
		else
			term.write( string.sub( sLine, nScroll + 1 ,nScroll + _wdth) )
		end
		term.setCursorPos( sx + nPos - nScroll, sy )
	end
	
	while true do
		local sEvent, param = os.pullEvent()
		if sEvent == "char" then
			sLine = string.sub( sLine, 1, nPos ) .. param .. string.sub( sLine, nPos + 1 )
			nPos = nPos + 1
			redraw()
			
		elseif sEvent == "key" then
			
			if param == keys.left then
				-- Left
				if nPos > 0 then
					nPos = nPos - 1
					redraw()
				end
				
			elseif param == keys.right then
				-- Right				
				if nPos < string.len(sLine) then
					nPos = nPos + 1
					redraw()
				end
			
			elseif param == keys.up or param == keys.down then
                -- Up or down
				if _tHistory then
					redraw(" ");
					if param == keys.up then
						-- Up
						if nHistoryPos == nil then
							if #_tHistory > 0 then
								nHistoryPos = #_tHistory
							end
						elseif nHistoryPos > 1 then
							nHistoryPos = nHistoryPos - 1
						end
					else
						-- Down
						if nHistoryPos == #_tHistory then
							nHistoryPos = nil
						elseif nHistoryPos ~= nil then
							nHistoryPos = nHistoryPos + 1
						end						
					end
					
					if nHistoryPos then
                    	sLine = _tHistory[nHistoryPos]
                    	nPos = string.len( sLine ) 
                    else
						sLine = ""
						nPos = 0
					end
					redraw()
                end
			elseif param == keys.backspace then
				-- Backspace
				if nPos > 0 then
					redraw(" ");
					sLine = string.sub( sLine, 1, nPos - 1 ) .. string.sub( sLine, nPos + 1 )
					nPos = nPos - 1					
					redraw()
				end
			elseif param == keys.home then
				-- Home
				nPos = 0
				redraw()		
			elseif param == keys.delete then
				if nPos < string.len(sLine) then
					redraw(" ");
					sLine = string.sub( sLine, 1, nPos ) .. string.sub( sLine, nPos + 2 )				
					redraw()
				end
			elseif param == keys["end"] then
				-- End
				nPos = string.len(sLine)
				redraw()
			end
		elseif sEvent == "redraw" then
			redraw()
		elseif sEvent == "return" then
			term.setCursorBlink( false )
			return sLine
		end
	end
	
	term.setCursorBlink( false )
	
	return sLine
end

-- end modified read

local function printC(posX,posY,textCol,backCol,text)
	term.setCursorPos(posX,posY)
	term.setTextColor(colors[textCol] or textCol)
	term.setBackgroundColor(colors[backCol] or backCol)
	term.write(text)
end

local function InputBox(title)
	local boxW,boxH = 26,3
	local termX,termY = term.getSize()
	local ofsX,ofsY = math.ceil((termX/2) - (boxW/2)) , math.ceil((termY/2) - (boxH/2)) -- offset from top left
	local options = {"ok","cancel"}
	
	local selected = 1
	local space = 0
	local range = {}
	for i = 1,#options do
		range[i] = {s = space,f = space + string.len(options[i])}
		space = space + string.len(options[i])+3
	end
	local ofC = (boxW/2) - (space/2)
	
	local function drawBox()
		printC(ofsX,ofsY,colors.white,colors.lightBlue,string.rep(" ",boxW))
		printC(ofsX+1,ofsY,colors.white,colors.lightBlue,(title or "User Input"))
		printC(ofsX,ofsY+1,colors.black,256,string.rep(" ",boxW))
		printC(ofsX,ofsY+2,colors.black,256,string.rep(" ",boxW))
		printC(ofsX,ofsY+3,colors.black,256,string.rep(" ",boxW))
		
		for i = 1,#options do
			if i == selected then
				term.setBackgroundColor(colors.lightGray)
				term.setCursorPos(range[i].s + ofC + ofsX - 1,ofsY + 3)
				term.write("["..options[i].."]")
				term.setBackgroundColor(colors.lightGray)
				term.write(" ")
			else
				term.setCursorPos(range[i].s + ofC + ofsX - 1,ofsY + 3)
				term.write(" "..options[i].." ")
			end
		end
		
		printC(ofsX+2,ofsY+2,colors.black,colors.gray,string.rep(" ",boxW-4))
	end
	drawBox()
	term.setCursorPos(ofsX+2,ofsY+2)
	local co = coroutine.create(function() return readMOD(nil,nil,boxW - 4) end)
	while true do
		local event = {os.pullEvent()}
		if event[1] == "key" or event[1] == "char" then
			if event[2] == 28 then
				local test,data = coroutine.resume(co,"return")
				return data
			else
				coroutine.resume(co,unpack(event))
			end
		elseif event[1] == "mouse_click" then
			if event[4] == ofsY + 3 then
				for i = 1,#options do
					if event[3] >= range[i].s + ofC + ofsX - 1 and event[3] <= range[i].f + ofC + ofsX then
						if options[i] == "ok" then
							local test,data = coroutine.resume(co,"return")
							return data
						elseif options[i] == "cancel" then
							return false
						end
					end
				end
			end
		end
	end
end
local function startMenu()
	local function drawStartMenu()
		term.setBackgroundColor(128)
		term.setTextColor(colors.white)
		term.setCursorPos(1,2)
		print("                ")
		term.setCursorPos(1,3)
		print("  About         ")
		term.setCursorPos(1,4)
		print("  Control Panel ")
		term.setCursorPos(1,5)
		print("  File Manager  ")
		term.setCursorPos(1,6)
		print("  Reboot        ")
		term.setCursorPos(1,7)
		print("  Shutdown      ")
		term.setCursorPos(1,8)
		print("                ")
	end
	drawStartMenu()	
	

end


local function dialogBox(title,message,options, h, w)
	term.setCursorBlink(false)
	local selected = 1
	title = title or ""
	message = message or ""
	options = options or {}
	local boxW,boxH = (w or 26), (h or 3)
	local termX,termY = term.getSize()
	local ofsX,ofsY = math.ceil((termX/2) - (boxW/2)) , math.ceil((termY/2) - (boxH/2)) -- offset from top left
	
	local space = 0
	local range = {}
	for i = 1,#options do
		range[i] = {s = space,f = space + string.len(options[i])}
		space = space + string.len(options[i])+3
	end
	local ofC = math.ceil((boxW/2)) - math.ceil((space/2))
	
	local function drawBox()
		printC(ofsX,ofsY,"white","lightBlue"," "..title..string.rep(" ",boxW-#title-5).."_[]")
		term.setBackgroundColor(colors.red)
		term.setTextColor(colors.white)
		term.write("X")
		printC(ofsX,ofsY+1,"gray","lightGray",string.sub(" "..message..string.rep(" ",boxW),1,boxW))
		term.setCursorPos(ofsX,ofsY+2)
		term.write(string.rep(" ",boxW))
		term.setCursorPos(ofsX,ofsY+3)
		term.write(string.rep(" ",boxW))
		for i = 1,#options do
			if i == selected then
				printC(range[i].s + ofC + ofsX - 1,ofsY + 3,"white","gray","["..options[i].."]")
				term.setBackgroundColor(256)
				term.write(" ")
			else
				term.setCursorPos(range[i].s + ofC + ofsX - 1,ofsY + 3)
				term.write(" "..options[i].." ")
			end
		end
		term.setCursorPos(ofsX + ofC + space,ofsY + 3)
		term.write(string.rep(" ",boxW - (ofC + space)))
		term.setBackgroundColor(colors.black)
		term.setTextColor(colors.white)			
	end
	while true do
		drawBox()
		event = {os.pullEvent()}
		if event[1] == "key" then
			if event[2] == 203 then -- left
				selected = selected - 1
				if selected < 1 then
					selected = #options
				end
			elseif event[2] == 205 then -- right
				selected = selected + 1
				if selected > #options then
					selected = 1
				end
			elseif event[2] == 28 then -- enter
				return selected , options[selected]
			end
		elseif event[1] == "mouse_click" then
			
			if bugTest then term.write("M "..event[2].." X "..event[3].." Y "..event[4].."    ") end
			
			if event[2] == 1 then
				if event[4] == ofsY + 3 then
					for i = 1,#options do
						if event[3] >= range[i].s + ofC + ofsX - 1 and event[3] <= range[i].f + ofC + ofsX then
							return i , options[i]
						end
					end
				end
			end
		end
	end
end

local function rClickMenu(title,tList,posX,posY)

	term.setCursorBlink(false)
	local BoxTitle = title
	local choices = tList
	local termX,termY = term.getSize()
	local offX,offY
	
	local width = #BoxTitle + 2
	local hight = #choices + 1
	
	for i = 1,#choices do
		if width < #choices[i] + 2 then
			width = #choices[i] + 2
		end
	end
	
	offX,offY = math.ceil((termX/2) - (width/2)),math.ceil((termY/2) - (hight/2))
	
	if posX and posY then -- offX,offY = posX,posY
		if posX >= termX - width - 1 then
			offX = termX - width - 1
		else
			offX = posX
		end
		if posY >= termY - hight then
			offY = termY - hight
		else
			offY = posY
		end
	end
	
	local function reDrawer()
		printC(offX,offY,colors.white,colors.lightBlue," "..BoxTitle..string.rep(" ",width - #BoxTitle - 1))
		for i = 1,#choices do
			printC(offX,offY + i,colors.gray,colors.lightGray," "..choices[i]..string.rep(" ",width - #choices[i] - 1))
		end
	end
	
	while true do
		reDrawer()
		local event = {os.pullEvent()}
		if event[1] == "mouse_click" then
			if event[2] == 1 then -- event[3] = x event[4] = y
				if event[4] > offY and event[4] < hight + offY and event[3] >= offX and event[3] < width + offX then
					return choices[event[4] - offY]
				else
					return
				end
			elseif event[2] == 2 then
				return
			end
		end
	end
	
end

local function osRunSpaces(...)
	clear()
	return os.run(getfenv(),...)
end

local function fileSelect(mode) -- save_file open_file browse < not yet implemented
	
	local title = titleBar()
	local bRun = true
	local flag = true
	local clipboard = nil
	local cut = false
	
	local termX,termY = term.getSize()
	local offsetX,offsetY = 0,0
	local hight,width = math.ceil(termY-0),math.ceil(termX+1)
	local oldHight,oldWidth
	
	-- offsets
	local boxOffX,boxOffY = offsetX,offsetY + 2
	local boxH,boxW = hight - 2 ,width - 2
	
	local barX,barY = offsetX + 1,offsetY + 2
	local barH,barW = 1,width - 1
	
	local tbarX,tbarY = offsetX + 1,offsetY + 1
	local tbarH,tbarW = 1,width - 1
	
	local exitX,exitY = offsetX + width - 1 ,offsetY + 1
	
	local pading = string.rep(" ",boxW)
	local path = {dir:match("[^/]+")}
	local list
	
	local fSlash = "/"
	local listOff = 0
	
	local function stringPath() -- compacted this a lot
		return fSlash..table.concat(path,fSlash)
	end
	
	local sPath
	local tItemList = {}

	local function newList()
		listOff = 0
		flag = true
		tItemList = {{n = "..", id = "back"}} -- adds a back item at top of list
		sPath = stringPath()
		local folders = {}
		local files = {}
		local disks = {}
		if not fs.exists(sPath) then
			path = {}
			sPath = stringPath()
			dialogBox("ERROR:","Path no longer exists",{"ok"})
		end
		local test,list = pcall(fs.list,sPath) -- stopes fs.list crash
		if list == nil then
			list = {}
			dialogBox("ERROR : ","fs.list crashed",{"ok"})
		end
		if #path == 0 then
			for i,v in pairs(rs.getSides()) do
				if disk.isPresent(v) then
					if disk.hasData(v) then
						table.insert(tItemList,{n = disk.getMountPath(v), id = "disk",s = v})
						disks[disk.getMountPath(v)] = true
					elseif disk.hasAudio(v) then
						table.insert(tItemList,{n = disk.getAudioTitle(v), id = "audio",s = v})
					end
				end
			end
		end
		for i,v in pairs(list) do
			if fs.isDir(sPath..fSlash..v) then
				table.insert(folders,v)
			else
				table.insert(files,v)
			end
		end
		table.sort(folders)
		table.sort(files)
		for i,v in pairs(folders) do
			if disks[v] == nil then
				table.insert(tItemList,{n = v, id = "folder"})
			end
		end
		for i,v in pairs(files) do
			table.insert(tItemList,{n = v, id = "file"})
		end
	end
	
	newList()
	
	local tIcons = {
	back = {tCol = "lightBlue",bCol = "gray",txt = "<< "},
	disk = {tCol = "magenta",bCol = "gray",txt = "[*]"},
	audio = {tCol = "yellow",bCol = "gray",txt = "(o)"},
	folder = {tCol = "white",bCol = "gray",txt = "[=]"},
	file = {tCol = "lime",bCol = "gray",txt = "-~-"}}
	
	while bRun do
		if flag then
			flag = false
			-- clear
			if oldHight ~= hight and oldWidth ~= width then
				term.setBackgroundColor(colors.black)
				term.clear()
				oldHight,oldWidth = hight,width
			end
			-- draw top title bar
			titleBar()
			term.setCursorPos(23,tbarY)
			term.setTextColor(tbtColor)
			term.setBackgroundColor(tbColor)
			term.write("File Browser By BigSHinyToys")
			
			
			-- draw location bar
			term.setCursorPos(barX,barY)
			term.setTextColor(256)
			term.setBackgroundColor(1)
			local a = barW - #sPath - 1
			if a < 0 then
				a = 0
			end
			local tmppath = sPath
			if shell and shell.getDisplayName then
				tmppath = shell.getDisplayName(sPath)
				--dialogBox("yay")
			else
				--dialogBox("moop")
			end
			tmppath = tmppath or sPath
			local a = barW - #tmppath - 1
			if a < 0 then
				a = 0
			end
			term.write(string.sub(" "..tmppath,1,barW)..string.rep(" ",a))
			
			-- draw scroll bar
			if #tItemList > boxH then
				term.setBackgroundColor(colors.lightGray)
				for i = 1,boxH do
					term.setCursorPos(boxOffX+boxW+1,i + boxOffY)
					local scroll = math.floor( boxH* (listOff/(#tItemList-boxH+2)) )+1
					if i == scroll then
						term.setBackgroundColor(8)
						term.write(" ")
						term.setBackgroundColor(colors.lightGray)
					else
						term.write(" ")
					end
				end
			else
				term.setBackgroundColor(colors.gray)
				for i = 1,boxH do
					term.setCursorPos(boxOffX+boxW+1,i + boxOffY)
					term.write(" ")
				end
			end
			
			-- draw main section
			term.setTextColor(128)
			term.setBackgroundColor(1)
			for i = 1,boxH do -- listOff
				--term.setCursorPos(1+boxOffX,i+boxOffY)
				local sel = i+listOff
				if tItemList[sel] then
					printC(1+boxOffX,i+boxOffY,colors[tIcons[tItemList[sel].id].tCol],colors[tIcons[tItemList[sel].id].bCol],tIcons[tItemList[sel].id].txt)
					printC(4+boxOffX,i+boxOffY,128,1,string.sub(" "..tItemList[sel].n..pading,1,boxW-3))
				else
					printC(1+boxOffX,i+boxOffY,128,1,pading)
				end
			end
			term.setTextColor(colors.white)
			term.setBackgroundColor(colors.black)
			
			if bugTest then
				term.setCursorPos(1,1)
				term.write(listOff.." "..boxOffY.." "..boxH)
			end
			
		end
		
		-- react to events
		local event = {os.pullEvent()}
		
		if event[1] == "mouse_click" then
			if event[2] == 1 then -- left mouse
			local temp = nil
				if event[3] >= 1 and event[3] <= 6 and event[4] == 1 then
				bstart = true
					startMenu()
					
						elseif event[3] >=3 and event[3] <=15 and event[4] == 3 and bstart then 
							kernal.drawAbout()
							bstart = false
							elseif event[3] >=3 and event[3] <=15 and event[4] == 4 and bstart then 
								shell.run("programs/.system/control.nse")
								bRun = false
									elseif event[3] >=3 and event[3] <=15 and event[4] == 5 and bstart then 
										bstart = false
											elseif event[3] >=3 and event[3] <=15 and event[4] == 6 and bstart then
												kernal.osReboot()
												elseif event[3] >=3 and event[3] <=15 and event[4] == 7 and bstart then 
													kernal.osShutdown()
						
					
						
						flag = false
			
				
				elseif event[4] > boxOffY and event[4] <= boxH + boxOffY and not bstart then
					temp = tItemList[event[4]+listOff-boxOffY]
				end
				if temp and event[3] > boxOffX and event[3] <= #temp.n + 4 + boxOffX and event[3] < boxOffX + boxW then
					if temp.id == "back" then
						table.remove(path,#path)
						newList()
					elseif temp.id == "folder" or temp.id == "disk" then
						table.insert(path,temp.n)
						newList()
					elseif temp.id == "file" then
						if dialogBox("Run file ?",temp.n,{"yes","no"}) == 1 then
							local test,info = osRunSpaces(stringPath()..fSlash..temp.n)
							term.setCursorBlink(false)
							if not test then
								dialogBox("ERROR",tostring(info),{"ok"})
							end
						end
						flag = true
					end
				elseif event[3] == boxOffX+boxW+1 and event[4] > boxOffY and event[4] <= boxOffY+boxH and not bstart then
					if #tItemList > boxH then
						if event[4] == boxOffY + 1 then
							listOff = 0
						elseif event[4] == boxOffY+boxH then
							listOff = #tItemList + 1 - boxH
						else
							listOff = math.ceil((event[4] - boxOffY - 1 )*(((#tItemList - boxH+2)/boxH)))
						end
						flag = true
					end
				elseif event[3] >= 10 and event[3] <= 16 and event[4] == 1 then
					if dialogBox("Confirm","Exit application",{"yes","no"}) == 1 then
						shell.run(".var/gui")
						bRun = false
					end
					flag = true
				end				
			elseif event[2] == 2 then -- right mouse
				local temp = nil
				local sChoice = nil
				
				if event[4] > boxOffY and event[4] <= boxH + boxOffY then
					temp = tItemList[event[4]+listOff-boxOffY]
				end
				
				-- moved
				local paste
				if clipboard then
					paste = "Paste"
				end
				
				if temp and event[3] > boxOffX and event[3] <= #temp.n + 4 + boxOffX and event[3] < boxOffX + boxW then
					
					if temp.id == "disk" then
						sChoice = rClickMenu("Options",{"Open","Copy","Eject","ID label","Set label","Clear label"},event[3]+1,event[4]+1)
					elseif temp.id == "folder" then
						sChoice = rClickMenu("Options",{"Open","Copy","Delete"},event[3]+1,event[4]+1)
					elseif temp.id == "file" then
						sChoice = rClickMenu("Options",{"Cloud","Run","Open With","Rename","Delete", "Cut", "Copy", paste},event[3]+1,event[4]+1)
					elseif temp.id == "audio" then
						sChoice = rClickMenu("Options",{"Play","Eject"},event[3]+1,event[4]+1)
					end
					
				else
					if event[3] > boxOffX and event[3] <= 5 + boxOffX and event[3] < boxOffX + boxW then
						if event[4] > offsetY and event[4] < hight + offsetY then
							sChoice = rClickMenu("Options",{"New File","New Folder", paste},event[3]+1,event[4]+1)
						end
					else
						table.remove(path,#path)
						newList()
					end
				end
				if sChoice == "Open With" then
					sChoice = rClickMenu("Options",{"Notepad","NPaintPro"},event[3]+12,event[4]+1)
				elseif sChoice == "Run" then
					local runWin
					if windowDimensions then
						runWin = "Run win"
					end
					sChoice = rClickMenu("Options",{"Run","Run CMD","Debug",runWin},event[3]+12,event[4]+1)
				end
				if sChoice == "Run win" and windowDimensions then -- choice execution
					osRunSpaces("start",stringPath()..fSlash..temp.n) -- might be a probblem -- shell
					flag = true
				
				
				elseif sChoice == "Cloud" then
					sChoice = rClickMenu("Cloud",{"Upload","Remove"},event[3]+12,event[4]+1)
						if sChoice == "Upload" then
							if kernal.getLine(".var/settings", 2) == "Enable Terminal: True" then
							
								if not fs.exists(".var/.files") then
									dialogBox("Cloud","File Tree Not Foud!",{"ok"})
									else
									if fs.exists("documents/cloud"..fSlash..temp.n) then
									fs.delete("documents/cloud"..fSlash..temp.n)
									end 
										fs.copy(stringPath()..fSlash..temp.n, "documents/cloud"..fSlash..temp.n)
										kernal.fwriteFromTable(".var/.files", fs.list("documents/cloud"))
											local cloudA = io.open("documents/cloud"..fSlash..temp.n, "r")
											local cloudB = cloudA:read("*a")
											local cloudData = cloudB
											local cUser = kernal.getLine(".var/.adsnt.dll", 1)
											local cName = temp.n
											local cUSRn = kernal.getLine(".var/.adsnt.dll", 3)
											local cUSRp = kernal.getLine(".var/.adsnt.dll", 4)
										http.post(
													 cUser..textutils.urlEncode(tostring(cName)).."&data="..textutils.urlEncode(tostring(cloudData)).."&username="..textutils.urlEncode(tostring(cUSRn)).."&password="..textutils.urlEncode(tostring(cUSRp))
													  )
											cloudA:close()
											local cloudC = io.open(".var/.files", "r")
											local cloudD = cloudC:read("*a")
											local cloudDataD = cloudD
											local cUserD = kernal.getLine(".var/.adsnt.dll", 2)
											local cNameD = files
											http.post(
													 cUserD..textutils.urlEncode(tostring(cNameD)).."&data="..textutils.urlEncode(tostring(cloudDataD)).."&username="..textutils.urlEncode(tostring(cUSRn)).."&password="..textutils.urlEncode(tostring(cUSRp))
													  )
											cloudC:close()
											
										
									dialogBox("Cloud","Uploaded",{"ok"})
								end
								elseif kernal.getLine(".var/settings", 2) == "Enable Terminal: False" then
								dialogBox("Cloud","Not signed into Cloud!",{"ok"})
							end
						
						
					
					
				elseif sChoice == "Remove" then
					if kernal.getLine(".var/settings", 2) == "Enable Terminal: True" then
						if not fs.exists(".var/.files") then
							dialogBox("Cloud","File Tree Not Foud!",{"ok"})
							else
								if fs.exists("documents/cloud"..fSlash..temp.n) then
									fs.delete("documents/cloud"..fSlash..temp.n)
									end 
										kernal.fwriteFromTable(".var/.files", fs.list("documents/cloud"))
											local cloudC = io.open(".var/.files", "r")
											local cloudD = cloudC:read("*a")
											local cloudDataD = cloudD
											local cUserD = kernal.getLine(".var/.adsnt.dll", 2)
											local cNameD = files
											http.post(
													 cUserD..textutils.urlEncode(tostring(cNameD)).."&data="..textutils.urlEncode(tostring(cloudDataD))
													  )
											cloudC:close()
											
										
									dialogBox("Cloud","Removed!",{"ok"})
							end
							elseif kernal.getLine(".var/settings", 2) == "Enable Terminal: False" then
							dialogBox("Cloud","Not signed into Cloud!",{"ok"})
						end
					end
					
					
				elseif sChoice == "Play" then
					disk.playAudio(temp.s)
				elseif sChoice == "ID label" then
					dialogBox("ID label",disk.getDiskID(temp.s).." "..tostring(disk.getLabel(temp.s)),{"ok"})
				elseif sChoice == "Set label" then
					local name = InputBox("Label?")
					if name then
						disk.setLabel(temp.s,name)
					end
				elseif sChoice == "Clear label" then -- dialogBox(
					if dialogBox("Confirm","Cleal Label from "..temp.s,{"yes","no"}) == 1 then
						disk.setLabel(temp.s)
					end
				elseif sChoice == "New File" then -- experemntal
					local name = InputBox()
					if name then
						if fs.exists(stringPath()..fSlash..name) then
							dialogBox("ERROR","Name exists",{"ok"})
						else
							local file = fs.open(stringPath()..fSlash..name,"w")
							if file then
								file.write("")
								file.close()
								newList()
							else
								dialogBox("ERROR","File not created",{"ok"})
							end
						end
					end
				elseif sChoice == "New Folder" then -- experemental
					local name = InputBox()
					if name then
						if fs.exists(stringPath()..fSlash..name) then
							dialogBox("ERROR","Name exists",{"ok"})
						else
							if pcall(fs.makeDir,stringPath()..fSlash..name) then
								newList()
							else
								dialogBox("ERROR","Access Denied",{"ok"})
							end
						end
					end
				elseif sChoice == "Open" then
					table.insert(path,temp.n)
					newList()
				elseif sChoice == "Run" then
					local test,info = osRunSpaces(stringPath()..fSlash..temp.n)
					term.setCursorBlink(false)
					if not test then
						dialogBox("ERROR",tostring(info),{"ok"})
					end
				elseif sChoice == "Run CMD" or sChoice == "Debug" then
					local cmd = InputBox("Commands")
					if cmd then
						local test,info = osRunSpaces(stringPath()..fSlash..temp.n,unpack(fixArgs(cmd)))
						term.setCursorBlink(false)
						if not test then
							dialogBox("ERROR",tostring(info),{"ok"})
						else
							if sChoice == "Debug" then
								term.setCursorBlink(false)
								os.pullEvent("key")
							end
						end
					end
				elseif sChoice == "Notepad" then
					if temp.id == "file" then
						osRunSpaces("/programs/.system/word.nse",stringPath()..fSlash..temp.n)
					else
						dialogBox("ERROR","Can't edit a Folder",{"ok"})
					end
				elseif sChoice == "Delete" then
					if dialogBox("Confirm","Delete "..temp.id.." "..temp.n,{"yes","no"}) == 1 then
						if fs.isReadOnly(stringPath()..fSlash..temp.n) then
							dialogBox("ERROR",temp.id.." Is read Only",{"ok"})
						elseif fs.exists(".trash/"..temp.n) then
						fs.delete(stringPath()..fSlash..temp.n)
						newList()
						else
							fs.move(stringPath()..fSlash..temp.n, ".trash/"..temp.n)
							newList()
						end
					end
				elseif sChoice == "NPaintPro" then
					if temp.id == "file" then
						osRunSpaces("/programs/.system/npaintpro.nse",stringPath()..fSlash..temp.n)
					else
						dialogBox("ERROR","Can't edit a Folder",{"ok"})
					end
				elseif sChoice == "Eject" then
					if dialogBox("Confirm","Eject disk "..temp.s.." "..fSlash..temp.n,{"yes","no"}) == 1 then
						disk.eject(temp.s)
						newList()
					end
				elseif sChoice == "Copy" then
					clipboard = {stringPath(), temp.n}
					cut = false
				elseif sChoice == "Cut" then
					clipboard = {stringPath(), temp.n}
					cut = true
				elseif sChoice == "Paste" then
					if cut then
						local s, m = pcall(function()
							fs.move(clipboard, stringPath().."/"..temp.n)
							cut = false
							clipboard = nil
						end)
						if not s then
							dialogBox("Error", (m or "Couldn't move"), {"ok"}, 4, 30)
						end
						if bugTest then
							local x, y = term.getCursorPos()
							term.setCursorPos(1, ({term.getSize()})[2])
							write("from "..clipboard[1].."/"..clipboard[2].." to "..stringPath().."/"..clipboard[2])
						end
					else
						local s, m = pcall(function()
							fs.copy(clipboard[1].."/"..clipboard[2], stringPath().."/"..clipboard[2])
						end)
						if not s then
							dialogBox("Error", (m or "Couldn't copy"), {"ok"}, 4, 30)
						end
						if bugTest then
							local x, y = term.getCursorPos()
							term.setCursorPos(1, ({term.getSize()})[2])
							write("from "..clipboard[1].."/"..clipboard[2].." to "..stringPath().."/"..clipboard[2])
						end
					end
					newList()
				elseif sChoice == "Rename" then -- new parts of the above thanks kilo
					local sName = InputBox("New Name")
					if type(sName) == "string" and sName ~= "" then
						local s, m = pcall(function()
							fs.move(stringPath()..fSlash..temp.n,stringPath()..fSlash..sName)
						end)
						if not s then
							dialogBox("Error", (m or "Rename failed"), {"ok"})
						end
					end
					newList()
				end
				flag = true
			end
		elseif event[1] == "mouse_scroll" then -- flag this needs new math
			local old = listOff
			listOff = listOff + event[2]
			if listOff < 0 then
				listOff = 0
			end
			if #tItemList + 1 - boxH > 0 and listOff > #tItemList + 1 - boxH then
				listOff = #tItemList + 1 - boxH
			elseif listOff > 0 and #tItemList + 1 - boxH < 0 then
				listOff = 0
			end
			if listOff ~= old then
				flag = true
			end
		
		elseif event[1] == "mouse_drag" then -- test
			if event[3] == boxOffX+boxW+1 and event[4] > boxOffY and event[4] <= boxOffY+boxH then
				if #tItemList > boxH then
					if event[4] == boxOffY + 1 then
						listOff = 0
					elseif event[4] == boxOffY+boxH then
						listOff = #tItemList + 1 - boxH
					else
						listOff = math.ceil((event[4] - boxOffY - 1 )*(((#tItemList - boxH+2)/boxH)))
					end
					flag = true
				end
			end
			
		elseif event[1] == "disk" or event[1] == "disk_eject" then
			newList()
		elseif event[1] == "window_resize" then
			termX,termY = term.getSize()
			offsetX,offsetY = 1,1
			hight,width = math.ceil(termY-2),math.ceil(termX-2)
			
			boxOffX,boxOffY = offsetX,offsetY + 2
			boxH,boxW = hight - 2 ,width - 2
			
			barX,barY = offsetX + 1,offsetY + 2
			barH,barW = 1,width - 1
			
			tbarX,tbarY = offsetX + 1,offsetY + 1
			tbarH,tbarW = 1,width - 1
			
			exitX,exitY = offsetX + width - 1 ,offsetY + 1
			pading = string.rep(" ",boxW)
			
			flag = true
		end
	end
end
local function main()
	if term.isColor() then
		clear()
		fileSelect()
		clear()
	else
		error("Not an Advanced Computer (gold) ")
	end
end
local trash = (norun or main())