function [ c ] = pnLastValue(data, featStr)
%PNLASTVALUE	Last measurement recorded
%	[ c ] = pnLastValue(data) calculates the first measurement recorded.
%	For each feature, the above names are used as suffixes in the output
%	feature label, i.e. for Albumin, the function would output
%	AlbuminLast, etc.
%   
%	[ c ] = pnLastValue(data, featStr) allows specification of a subset
%	of features to extract granularity values for. featStr should be a
%	string if features are extracted from a single field, or a cell array 
%	of strings for feature extraction from multiple fields.
%
%	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
%		
%       featStr - String of single field to extract features from OR cell
%           array of strings of multiple fields to extract features from.
%       
%	Outputs:
%		c    - A cell of the same size as data in standard format (above)
%           There exist multiple feature labels in Column 3.
%		
%
%	Example
%		bpath = './set-a/';
%		data = pnLoadTextFilesCell(bpath);
%		c = pnLastValue(data(1,:)) %	
%	See also 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, 11-May-2012 09:12:20
%	Contact: alistairewj@gmail.com

N = size(data,1);
c = cell(N,4);
c(:,1) = data(:,1);

genFeatStr = 'Last';

%=== Last, get index of elements with recordings
idxTime = cellfun(@(x) ~isempty(x), data(:,2));

Nexist = sum(idxTime);
idxExist=idxTime;
%=== Feature labels
featStrCell = {strcat(featStr,genFeatStr)};
c(idxTime,3) = cellfun(@(x) [x;featStrCell],...
    c(idxTime,3), 'UniformOutput',false);

%=== Time stamps
c(idxTime,2) = cellfun(@(x,y) [x;y(end)],...
    c(idxTime,2), data(idxTime,2), 'UniformOutput',false);

%=== Calculate features
c(idxTime,4) = cellfun(@(x,y) [x;y(end)],...
    c(idxTime,4), data(idxTime,4), 'UniformOutput', false);

N_notexist = N - Nexist;
c(~idxExist,4) = repmat({NaN},N_notexist,1);
c(~idxExist,2) = repmat({0},N_notexist,1);
c(~idxExist,3) = repmat({featStrCell},N_notexist,1);

end