function [f, g, y] = basicfg_skew(w,X,data);

% 11/5/00. From JP. Modified. 
% function [f, g] = basicfg_skew(w, X)
% 
% pdf has exp(ax) on lhs, and epx(-bx) on rhs of bias.
% Evaluate cost and gradient for skew ICA
%
% w    = unmixing matrix as col (k+1)*k-vector
% data = data structure with fields:
%        data.P = 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

global num_funevals;
global global_data;

if nargin<2 
	data=global_data;
end;

% Augment data here.
%[m, k] = size(data.P);
[m, k] = size(X);

w=reshape(w,k+1,k);

%X = data.P;
X=[X ones(m,1)];

[m, k] = size(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=w;
% Get square matrix W1.
W1 = W(1:k, :);

% FInd extracted signals with bias added.
% jsize(X,'X');jsize(W,'W');
y = X*W;			% jfig(201);plot(y);drawnow;

% jsize(y,'y');jsize(X,'X');jsize(W,'W');jsize(amb,'amb');
s = sqrt(1+y.^2); 	%jfig(202);plot(s);drawnow;
A = amb.*y;			% jfig(203);plot(A);drawnow;
B=apb.*s; 			% jfig(204);plot(B); drawnow;
% jsize(A);jsize(B);pr;
logp=A-B;

%if rem(num_funevals,50)==0
%temp=logp(:,1);
%jfig(111);hist(y(:,1),50);
%jfig(112);hist(exp(temp),50);
%end;

L = sum(mean(logp));
DET=  log(abs(det(W1)));
f= - L - DET;
% fprintf('L=%.3f DET=%.3f\n',L, DET);

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

% jsize(g,'g'); % 5x4 NOTE colon collapses by column!

g = g(:);

% CLUDGE
% SET BIAS TO ZERO.
%g=g.*[ones(k*k,1); zeros(k,1)];

% Need to negate f and g for minimisation procedure.
f=-f;
g=-g;
