

function stringifyKernel(filenameIn, filenameOut, kernelMethod)
  local BUFSIZE = 10*1024*1024     -- 10MB
	local f = io.open(filenameIn,"r");
   	local fw = io.open(filenameOut,"w");
   	fw:write("//this file is autogenerated using stringify.bat (premake --stringify) in the build folder of this project\n")
   	fw:write("static const char* " .. kernelMethod .. "= \\\n")
    local cc, lc, wc = 0, 0, 0   -- char, line, and word counts
    while true do
      local lines, rest = f:read(BUFSIZE, "*line")
      if not lines then break end
      
      local i = 0
      local startpos = 0
      local slen = string.len(lines)
      local endpos = 0
    	while true do
      	i = string.find(lines, "\n", i+1)    -- find 'next' newline
      	if i == nil then 
      		endpos = slen
      	else
      	  endpos = i
      	end
      	
	      	oneline = string.sub(lines,startpos,endpos)
	      	oneline = string.gsub(oneline,"\n","")
					oneline = string.gsub(oneline,"\"","\\\"");
	      	oneline = '\"' .. oneline .. '\\n\"'
	      	oneline = string.gsub(oneline,"\\\\n","")
	      	oneline = oneline .. "\n"
	      	--print(oneline)
					fw:write(oneline);      	
      	
      	if i == nil then break end
      	startpos = i+1
      end
      
      if rest then lines = lines .. rest .. '\n' end
      cc = cc + string.len(lines)
      -- count words in the chunk
      local _,t = string.gsub(lines, "%S+", "")
      wc = wc + t
      -- count newlines in the chunk
      _,t = string.gsub(lines, "\n", "\n")
      lc = lc + t
    end
    --print("stringified " .. filenameIn .. " into " .. filenameOut .. " processed " .. lc .. " lines")
    print(filenameIn .. " (" .. lc .. " lines)")

 		f:close()
 		fw:write(";\n")
 		fw:close()
 end


 
function preprocessKernel(kernelfile, filenameOut, kernelMethod)
	lcpp=require('lcpp');
	local out=lcpp.compileFile(kernelfile);
	local embedFileName = kernelfile .. ".embed"
	local fw = io.open(embedFileName,"w");
	fw:write(out)
	fw:close()
	stringifyKernel(embedFileName,filenameOut, kernelMethod);
end


 newoption {
    trigger     = "kernelfile",
    value				=	"kernelpath",
    description = "full path to the kernel source input file"
  }

 newoption {
    trigger     = "headerfile",
    value				=	"path",
    description = "full path to the header output file"
  }

 newoption {
    trigger     = "stringname",
    value				=	"var",
    description = "name of the kernel string variable"
  }
  


 newaction {
   trigger     = "stringify",
   description = "stringify kernels source code into strings",
   execute = 	function()
   preprocessKernel( _OPTIONS["kernelfile"] , _OPTIONS["headerfile"], _OPTIONS["stringname"])
   end
}



