function [model, nodesets, elsets] = mfs_import(msg, fname, format, tdata)

# usage: [model, nodesets, elsets] = mfs_import(msg, fname, format, tdata)
#
# Input  msg       File handle of message file
#        fname     Name of input file
#        format    Format of input file
#        tdata     Structure with translation data
#
# Output model     Structure with model definition
#        nodesets  Structure with node sets (optional)
#        elsets    Structure with element sets (optional)
#
# -----------------------------------------------------------------------------

# Copyright (c) 2015 by Johannes Wandinger

  t0 = clock();

  model = struct();

# Check arguments

  if (nargin != 4 || nargout == 0 || nargout > 3)
     print_usage();
  endif

  if (! is_valid_file_id(msg))
     error("mfs_import: first argument does not refer to an open file\n");
  endif
  if (! ischar(fname))
     fclose(msg);
     error("mfs_import: second argument must be a file name\n");
  endif
  if (! ischar(format))
     fclose(msg);
     error("mfs_import: third argument must be a string\n");
  endif
  if (! isstruct(tdata))
     fclose(msg);
     error("mfs_import: fourth argument must be a structure\n");
  endif

# Check model type

  if (! isfield(tdata, "type"))
     fclose(msg);
     error("mfs_import: model type undefined\n");
  endif

  switch tdata.type

  case {"solid", "structure"}
     tdata.type = "solid";
  otherwise
     fclose(msg);
     error("mfs_import: model type \"%s\" not supported\n", 
           tdata.type);
  endswitch

# Branch according to file format

  rc = 0;

  switch format

  case "msh"
     if (ispc)
        fmode = "r";
     else
        fmode = "rt";
     endif
     if ((fid = fopen(fname, fmode)) == -1)
        fclose(msg);
        error("mfs_import: could not open file \"%s\"\n", fname);
     endif
     time_stamp = ignore_function_time_stamp("all");
     vers = mfs_mshfileversion(msg, fid, fname);
     mfs_paths("add", "mfs_import.m", "util", "msh/util", 
               ["msh/", tdata.type], ["msh/", tdata.type, "/", vers],
               ["msh/util/", vers]);
     [model, nodesets, elsets, rc] = mfs_importx(msg, fid, tdata, fname);
     mfs_paths("remove");
     ignore_function_time_stamp(time_stamp);
     fclose(fid);

  case "matfem"
     nodesets = []; elsets = [];
     time_stamp = ignore_function_time_stamp("all");
     mfs_paths("add", "mfs_import.m", "util", "matfem");
     [model, rc] = mfs_importx(msg, tdata, fname);
     mfs_paths("remove");
     ignore_function_time_stamp(time_stamp);

  otherwise
     fclose(msg);
     error("mfs_import: File format %s not supported\n", format);      

  endswitch

  if (rc)
     text   = sprintf("mfs_import: Errors found while reading file %s",
                    fname);
     mfs_errexit(text, msg);
  endif

# End

  elapsed_time = etime(clock(), t0);
  printf("%10.4f seconds needed to read file %s\n", ...
          elapsed_time, fname);

  fflush(stdout);

endfunction
