function [f, g] = sicafg(w, data)

% function [f, g] = sicafg(w, X)
% 
% Evaluate cost and gradient for skew ICA
%
% w    = unmixing matrix as col (k+1)*k-vector
% data = data structure with fields:
%        data.X = m x (k+1) augmented data matrix
%        data.a = pdf left  exponents (1 x k) a=4
%        data.b = pdf right exponents (1 x k) b=1
%
% f = output entropy
% g = analytic gradient of f

[m, k] = size(data.X);
k = k-1; % k = num components.

apb = repmat((data.a+data.b)/2, m, 1);
amb = repmat((data.a-data.b)/2, m, 1);

W = reshape(w, k+1, k); W1 = W(1:k, :);
y = data.X*W;

% eps = 1e-10;

s = sqrt(1+y.^2);
logp = amb.*y-apb.*s;
f = -sum(mean(logp))-log(abs(det(W1)));

% Deriv of log pdf.
dlogp = amb-apb.*y./s;
g = -1/m*data.X'*dlogp-[inv(W1'); zeros(1, k)];
g = g(:);
