--[[
  Copyright (c) 2021 by Plexim GmbH
  All rights reserved.

  A free license is granted to anyone to use this software for any legal
  non safety-critical purpose, including commercial applications, provided
  that:
  1) IT IS NOT USED TO DIRECTLY OR INDIRECTLY COMPETE WITH PLEXIM, and
  2) THIS COPYRIGHT NOTICE IS PRESERVED in its entirety.

  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 CLA = {}

-- Control Law Accelerator, aka CLA
-- this harness allows super users to write handcode for the CLA
function CLA.generateClaCode(filename, recipe)
  local file, e = io.open(filename, "w")
  if file == nil then
    error(e)
  end
  io.output(file)
  local header = [[
  /*
  * CLA code file
  * Generated with                 : PLECS |<PLECS_VER>|
  * Generated on                   : |<DATE>|
  */
  ]]
  header = string.gsub(header, '|<TARGET>|', Target.Name)
  header = string.gsub(header, '|<DATE>|', tostring(os.date()))
  header = string.gsub(header, '|<PLECS_VER>|', Target.Variables.PLECS_VERSION)
  io.write(header .. '\n')

  local includes_posted = {}
  for _, v in ipairs(recipe.ClaInclude) do
    if includes_posted[v] == nil then
      includes_posted[v] = true
      io.write('#include "%s"\n' % {v})
    end
  end
  io.write('\n')

  for _, v in ipairs(recipe.ClaDeclarations) do
    io.write('%s\n' % {v});
  end
  io.write('\n')

  for _, v in ipairs(recipe.ClaCode) do
    io.write('%s\n' % {v});
  end
  io.write('\n')
  
  io.close(file)

  Plecs:Beautify(filename)
end

return CLA
