function values = hcomputeMTMValues(swaps,simulationDates,scenarios,Tenor)
%

%   Copyright 2012-2017 The MathWorks, Inc.

% Computes the mark-to-market value of a portfolio of swaps
numDates = numel(simulationDates);
numSwaps = numel(swaps.Maturity);
numScenarios = size(scenarios,3);

% Allocate values matrix.
values = zeros(numDates,numSwaps,numScenarios);

% Since the swaps are priced on dates that are different from the cash flow
% dates, the swaps' current floating rate will not be specified in the
% provided zero curve (the zero curve at that pricing date).  To accurately
% price the swaps we need the floating rate from the previous cash flow
% date, when the swap's floating leg was set for the current period. We
% estimate these latest floating rates by interpolating between the rate
% curves that we do have in each interest rate path.  The latest floating
% rate we use is simply the interpolated 1-year rate (these swaps have
% period == 1) at the previous coupon date, interpolated between the rate
% curves that we did simulate.
oneYearIdx = find(Tenor == 12,1,'first');
oneYearRates = squeeze(scenarios(:,oneYearIdx,:));

latestFloatingRates = zeros(numDates,numSwaps,numScenarios);
for swapIdx = 1:numSwaps
    latestFloatingRates(:,swapIdx,:) = interp1(simulationDates,oneYearRates,...
        swaps.FloatingResetDates(swapIdx,:)','linear',swaps.LatestFloatingRate(swapIdx));
end

% Price the swaps at each simulation date
compounding = -1;
for dateIdx = 1:numel(simulationDates)

    % Get interest rate curves for this simulation date
    simDate    = simulationDates(dateIdx);
    curveDates = datemnth(simDate,Tenor);
    curves     = squeeze(scenarios(dateIdx,:,:));
    lastFloats = latestFloatingRates(dateIdx,:,:);
    lastFloats = reshape(lastFloats,size(lastFloats,2),size(lastFloats,3));
    
    % We only value swaps which have not matured yet
    validIdx   = swaps.Maturity > simDate;
    maturedIdx = swaps.Maturity <= simDate;
    
    % compute values for all valid instruments
    if sum(validIdx(:)) > 0
        
        prices = hswapapprox(curveDates, curves, compounding, simDate,...
            swaps.LegRate (validIdx,:),...
            swaps.Maturity (validIdx),...
            swaps.Principal (validIdx),...
            swaps.LegType (validIdx,:),...
            lastFloats (validIdx,:),...
            swaps.LegReset (validIdx,:));

        values(dateIdx, validIdx, :) = prices;
        
        % Matured instruments have zero values
        values(dateIdx, maturedIdx, :) = 0;
        
    end
    
end
