## Copyright (C) 2013 Marco Vassallo <gedeone-octave@users.sourceforge.net>
##
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 3 of the License, or (at your option) any later
## version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public License along with
## this program; if not, see <http://www.gnu.org/licenses/>.


## -*- texinfo -*-
## function for internal usage only
## @end deftypefn
function output = generate_fs (ufl_name)

STRING ="\n\
#include <fem-fenics/functionspace.h>\n\
#include <fem-fenics/mesh.h>\n\
#include ""@@UFL_NAME@@.h""\n\
#include <fem-fenics/dolfin_compat.h>\n\
\n\
DEFUN_DLD (@@UFL_NAME@@_FunctionSpace, args, , ""initialize a fs from a mesh declared with fem_init_mesh"")\n\
{\n\
  int nargin = args.length ();\n\
  octave_value retval;\n\
\n\
  if (nargin < 1 || nargin > 1)\n\
    print_usage ();\n\
  else\n\
    {\n\
\n\
      if (! mesh_type_loaded)\n\
        {\n\
          mesh::register_type ();\n\
          mesh_type_loaded = true;\n\
          mlock ();\n\
        }\n\
\n\
      if (args(0).type_id () == mesh::static_type_id ())\n\
        {\n\
          const mesh & msho = static_cast<const mesh&> (args(0).get_rep ());\n\
          const dolfin::Mesh & mshd = msho.get_msh ();\n\
          SHARED_PTR <const dolfin::FunctionSpace> g (new @@UFL_NAME@@::FunctionSpace (mshd));\n\
\n\
          if (! functionspace_type_loaded)\n\
            {\n\
              functionspace::register_type ();\n\
              functionspace_type_loaded = true;\n\
              mlock ();\n\
            }\n\
\n\
          retval = new functionspace(g);\n\
        }\n\
    }\n\
  return retval;\n\
}";

STRING =  strrep (STRING, "@@UFL_NAME@@", ufl_name);

fid = fopen (sprintf ("%s_FunctionSpace.cc", ufl_name), 'w');
if (fid >= 0)
  fputs (fid, STRING);
  output = fclose (fid);
else
  error ("cannot open file");
  output = 1;
endif

endfunction
