function newval = meshinterp(fromval, elemid, elembary, fromelem, initval)
%
% newval=meshinterp(fromval,elemid,elembary,fromelem,initval)
%
% Interpolate nodal values from the source mesh to the target mesh based on
% a linear interpolation
%
% author: Qianqian Fang (q.fang at neu.edu)
%
% input:
%    fromval: values defined at the source mesh nodes, the row or column
%             number must be the same as the source mesh node number, which
%             is the same as the elemid length
%    elemid: the IDs of the source mesh element that encloses the nodes of
%            the target mesh nodes; a vector of length of target mesh node
%            count; elemid and elembary can be generated by calling
%
%           [elemid,elembary]=tsearchn(node_src, elem_src, node_target);
%
%           note that the mapping here is inverse to that in meshremap()
%
%    elembary: the bary-centric coordinates of each target mesh nodes
%            within the source mesh elements, sum of each row is 1, expect
%            3 or 4 columns (or can be N-D)
%    fromelem: the element list of the source mesh
%
%
% output:
%    newval: a 2D array with rows equal to the target mesh nodes (nodeto),
%            and columns equals to the value numbers defined at each source
%            mesh node
% example:
%
%    [n1,f1,e1]=meshabox([0 0 0],[10 20 5],1); % target mesh
%    [n2,f2,e2]=meshabox([0 0 0],[10 20 5],2); % src mesh
%    [id, ww]=tsearchn(n2,e2,n1);              % project target to src mesh
%    value_src=n2(:,[2 1 3]);             % create dummy values at src mesh
%    newval=meshinterp(value_src,id, ww, e2);
%
% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)
%

if (size(fromval, 1) == 1)
    fromval = fromval(:);
end

idx = find(~isnan(elemid));

allval = reshape(fromval(fromelem(elemid(idx), :), :), length(idx), size(elembary, 2), size(fromval, 2));
tmp = cellfun(@(x) sum(elembary(idx, :) .* x, 2), num2cell(allval, [1 2]), 'UniformOutput', false);
if (nargin > 4)
    newval = initval;
else
    newval = nan(length(elemid), size(fromval, 2));
end
newval(idx, :) = squeeze(cat(3, tmp{:}));
