% x, y, yExpected are all cell arrays OR matrices
% W, b, Phi are matrices

function [ z, y ] = roundingW(x, w, b, yExpected, Phi, mu, nu, params)

%ROUNDING Summary of this function goes here
%   Detailed explanation goes here

if iscell(x) % is cell type: recursive call %TODO use bsxfun
    y = cell(size(y));
    z = y;
    for k=1:numel(y)
        [z{k}, y{k}] = roundingW_matrix(x{k}, w, b, yExpected{k}, Phi, mu, nu, params);
    end
    z = cell2mat(z);
else
    [z, y] = roundingW_matrix(x, w, b, yExpected, Phi, mu, nu, params);
end

end

function [z, y] = roundingW_matrix(x, w, b, yExpected, Phi, mu, nu, params)

[T, K] = size(yExpected);

if params.silence == 0
    %TODO
    %z = [zeros(size(z, 1), 1), -.5 * ones(size(z)) + z];
else
    Delta = nu * ones(T);
    L = tril(ones(K));
    Sigma = ones(T,1)*diag(Phi*Phi.' + mu*(L*L.')).' - 2*(x*w+b)*Phi.' - 2*(mu*L + Delta)*yExpected;
    y = optimizeTrYY_Y(Delta.', Sigma.');
    y = y.';
    z = y * Phi;
end

end
