--[[
Filename: ls.lua
License: MIT

Copyright (c) 2013 Odd Strabo <oddstr13@openshell.no>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]


local argv = {...}
local DIRCOLOR = "$b"

local dirs
local files
local orig_write

local function printlist(base)
  if base == nil or base == "" or base == shell.dir() then
  else
    print(DIRCOLOR .. base .. "$0/:")
  end
  table.sort(dirs)
  table.sort(files)
  for _,v in pairs(files) do
    table.insert(dirs, v)
  end
  textutils.tabulate(dirs)
end


local function coloredWrite(s)
  assert(type(s) == "string", "string expected, got '"..type(s).."'.")
  
  local color = false
  for i=1,#s do
    c = s:sub(i,i)
    if c == "$" then
      if color then
        orig_write(c)
        color = false
      else
        color = true
      end
    elseif color then
      cn = tonumber('0x' .. c)
      if cn then
        if term.isColor() then
          term.setTextColor(2^cn)
        end
      else
        orig_write("$"..c)
      end
      color = false
    else
      orig_write(c)
    end
  end
end

local function listdir(dir)
  dirs = {}
  files = {}
  for _,v in pairs(fs.list(dir)) do
    if fs.isDir(dir.."/"..v) then
      table.insert(dirs, DIRCOLOR .. v .. "$0/")
    else
      table.insert(files, v)
    end
  end
  printlist(dir)
end

orig_write = term.write
term.write = coloredWrite

if #argv > 0 then
  for k,v in pairs(argv) do
    listdir(shell.resolve(v))
    if k ~= #argv then
      print()
    end
  end
else
  listdir(shell.dir())
end

term.write = orig_write