-- GPSReport.lua
--
-- Summary
--
--	lua GPSReport.lua {<max-lines> {<min-time> {<max-time>}}}
--
-- Parameters
--
--	
function split(str, pat)
   local t = {}  -- NOTE: use {n = 0} in Lua-5.0
   local fpat = "(.-)" .. pat
   local last_end = 1
   local s, e, cap = str:find(fpat, 1)
   while s do
      if s ~= 1 or cap ~= "" then
	 table.insert(t,cap)
      end
      last_end = e+1
      s, e, cap = str:find(fpat, last_end)
   end
   if last_end <= #str then
      cap = str:sub(last_end)
      table.insert(t, cap)
   end
   return t
end

numArgs = table.getn(arg)		-- number of arguments passed on command line
numFilter = false			-- set to true if a filter is in place
minNum = 0				-- minimum value for time number if filter in place
maxNum = 999999				-- maximum value for time number if filter in place
maxLines = 400000			-- maximum number of lines to pass thru

if numArgs >= 1 then

    if arg[1] then
	n = tonumber(arg[1])
	if n then maxLines = n end
    end

    if numArgs >= 2 then

	if arg[2] and (arg[2] ~= "-") then
	    n = tonumber(arg[2])
	    if n then minNum = n ; numFilter = true end
	end

    	if numArgs >= 3 then
	    if arg[3] and (arg[3] ~= "-") then
	    	n = tonumber(arg[3])
	    	if n then maxNum = n ; numFilter = true end
	    end
    	end

    end

end

numLines = 0				-- number of lines accumulated so far
readSuccess = true			-- boolean indicating success or failure of read

-- continue reading until failure or max lines reached
while readSuccess and (numLines < maxLines)
do

    local line = io.read("*line")	-- read the next line

    readSuccess = not not line		-- successful if line is not nil

    -- if successful read and it starts with GPS, ...
    if readSuccess and (string.sub(line,0,4) == "GPS,") then

	local filtered = numFilter	-- copy the filter-in-place variable

	-- if filter in place, split the string and filter only if the time
	-- number does not exist or is out of range
	if filtered then

	    local splitTab = split(line,",")
	    timeNum = tonumber(splitTab[2])

	    if timeNum then
	        filtered = (timeNum < minNum) or (timeNum > maxNum)
	    end
	
	end

	-- print the line and increment the count of not filtered
	if not filtered then
	    print(line)
	    numLines = numLines+1
	end

    end

end

