-- luafiler (c) 2006 mallchin, http://www.mallchin.com/luafm/
-- You are free to distribute this file without modifications.

function in_array(haystack, needle)
  local tbl = {}
  local found_needle = false
  for k,v in pairs(haystack) do
    if (v == needle) then
      found_needle = true
    end
  end
  return found_needle
end

function array_search(haystack, needle)
  local tbl = {}
  local array_key = false
  for k,v in pairs(haystack) do
    if (v == needle) then
      array_key = k
    end
  end
  return array_key
end

function gettime()

  time = os.time()
  dateFields = os.date("*t", time)

  hour = dateFields.hour
  if hour < 10 then hour = "0" .. hour end

  min = dateFields.min
  if min < 10 then min = "0" .. min end

  sec = dateFields.sec
  if sec < 10 then sec = "0" .. sec end

  return hour .. ":" .. min .. ":" .. sec

end

function screenshot()
    dir="ms0:/"
    name="screenshot_"
    counter=0
    extension=".png"
    while io.open(dir .. name .. counter .. extension, "r") do
        counter=counter+1
        io.close()
    end
    screen:save(dir .. name .. counter .. extension)
end

function pad_string(side, maxlength, str)
  npad = string.rep(" ", (maxlength-string.len(str)))
  if side == "left" then
    return npad .. str
  end
  if side == "right" then
    return str .. npad
  end
end

function add_trailing_slash(str)
  if string.sub(str, -1) ~= "/" then
    return str .. "/"
  else
    return str
  end
end

function remove_trailing_slash(str)
  if string.sub(str, -1) == "/" then
    return string.sub(str, 1, (string.len(str) - 1))
  else
    return str
  end
end

function is_lowbatt()
--  if System.powerIsLowBattery() then return true else return false end
  if System.powerIsPowerOnline() or System.powerGetBatteryLifePercent() > 10 then return false else return true end
end

function lowbattmsg()
--  return "Low battery (" .. System.powerGetBatteryLifePercent() .. "%). Please plug in mains power."
  return "Low battery. Please plug in mains power."
end

function on_ms(str)
  if string.sub(str, 0, 3) == "ms0" then return true else return false end
end

function rm(file)
  if on_ms(file) then System.removeFile(file) end
end

function rm_dir(dir)
  if on_ms(dir) then System.removeDirectory(dir) end
end

function md(dir)
  if on_ms(dir) then System.createDirectory(dir) end
end

function cp(src, dest)

  if on_ms(dest) then

    -- open files
    io.input(src)
    io.output(dest)

    -- copy files
    local size = 2^13      -- good buffer size (8K)
    while true do
      local block = io.read(size)
      if not block then break end
      io.write(block)
    end

    -- close files
    io.input():close()
    io.output():close()

  end

end
