function motion = mfs_buildmotion(nofmot, mot)

# usage:  motion = mfs_buildmotion(nofmot, mot)
#
# Input  nofmot   Number of definitions in mot
#        mot      Structure with definitions of motion
#
# Output motion   Structure array with definition of motion as expected
#                 by mfs_new
#
# Fields of structure mot:
#   mot.ids(nofmot, 1)   Nodal point identifier
#   mot.ids(nofmot, 2)   Loadcase identifier
#   mot.ids(nofmat, 3)   Index of data in cell array data
#   mot.data{:}          Motion data
#
# As the nodal point identifiers are collected from element definitions,
# the same nodal point identifier can appear more than once.
#
# ------------------------------------------------------------------------

  mot.ids = sortrows(mot.ids);

  nd = 0;
  id = mot.ids(1, 1); lc = mot.ids(1, 2); k = mot.ids(1, 3);
  dt = mot.data{k};

  for n = 2 : nofmot
      if (mot.ids(n, 1) != id || mot.ids(n, 2) != lc)
         motion(++nd).id = id;
         motion(nd).data = dt;
         motion(nd).lc   = lc;
         id = mot.ids(n, 1); lc = mot.ids(n, 2); k = mot.ids(n, 3);
         dt = mot.data{k};
      elseif (k != (kn = mot.ids(n, 3)))
         dn = mot.data{kn};
         ix = find(dn);
         dt(ix) = dn(ix);
      end
  end

  motion(++nd).id = id;
  motion(nd).data = dt;
  motion(nd).lc   = lc;

end
