function [ data ] = pnImputeField(data, field)
%PNIMPUTEFEATURE	Impute a feature into the data cell
%	[ stat ] = pnImputeFeature(data) 
%
%	Inputs:
%		data    - Cell array of data.
%				Column 1 - Subject IDs
%				Column 2 - Time stamp vectors for each subject
%				Column 3 - Feature name vectors for each subject
%				Column 4 - Data value vectors for each subject
%       
%		field   - Cell array of identical format to data. However,
%           there should only be one type of feature.
%
%	Outputs:
%		data    - Cell array of data with feature imputed at the correct
%		time locations.
%
%	Example
% 		bpath = './set-a/';
% 		data = pnLoadTextFilesCell(bpath);
%       field = pnBodySurface(data);
%       data = pnImputeField(data,field);
%   
%	See also PNEXTRACTFIELD PNGENERATEFEATURES

%	References:
%		Physionet Challenge 2012

%	Copyright 2012 Alistair Johnson

%	$LastChangedBy: alistair $
%	$LastChangedDate: 2012-06-04 15:40:13 -0400 (Mon, 04 Jun 2012) $
%	$Revision: 28 $
%	Originally written on GLNXA64 by Alistair Johnson, 09-May-2012 11:52:57
%	Contact: alistairewj@gmail.com

if nargin<2
    error('2 arguments required.');
end
if ~iscell(field) || ...
        size(field,1) ~= size(data,1) || size(field,2) ~= size(data,2) 
    error('Field must be a cell array of equal size to data');
end

N = size(data,1);
for k=1:N
    f_t = field{k,2}; % field time
    d_t = data{k,2}; % data time
    
    %=== Sort field time into data time
    t = [f_t;d_t];
    [t,idxSort] = sort(t,1,'ascend');
    idxSortNew = idxSort <= numel(f_t);
    idxSortF = find(idxSortNew==1);
    idxSortD = find(idxSortNew==0);
    
    %=== Preallocate space for new values etc
    M = numel(t); % Number of recordings for the observation
    v = zeros(M,1); % values
    l = cell(M,1); % labels
    
    %=== Combine values
    v(idxSortF) = field{k,4};
    v(idxSortD) = data{k,4};
    
    %=== Combine labels
    l(idxSortF) = field{k,3};
    l(idxSortD) = data{k,3};
    
    %=== Push to output
    data{k,2} = t;
    data{k,3} = l;
    data{k,4} = v;
end


end