function [f,g,H]=logist_phi_fgH(w, phi,Y,alpha)
  
  % constants
  eps_inc=1E-5;
  
  % get inputs
  C=max(Y);
  n=size(phi{1},1);
  kall=length(w);
  ks=cellfun('size',phi,2);k2=[0;cumsum(ks(:))];
  assert(k2(end)==kall);
  y=double(repmat(Y(:),1,C)==repmat([1:C],n,1));

  
  % compute u and mu
  u=zeros(n,C);
  mu=zeros(n,C);
  for i=1:C
    u(:,i)=phi{i}*w(k2(i)+1:k2(i+1));
  end
  u=u-repmat(max(u,[],2),1,C);  % to avoid getting exp(u)=Inf
  expu=exp(u);
  mu=expu./repmat(sum(expu,2),1,C);
  assert(norm(sum(mu,2)-1)<1E-3);
  
% get f g and H
  if nargout>=1
    f=-sum(sum(log(mu+eps_inc).*y))+1/2*sum(w.^2.*alpha);
  end
  if nargout>=2
    g=zeros(kall,1);
    for c=1:C
      g(k2(c)+1:k2(c+1))=phi{c}'*(mu(:,c)-y(:,c));
    end
    g=g+w.*alpha;
  end
  if nargout>=3
    H=zeros(kall,kall);
    for i=1:C
      for j=1:C
        delta=double(i==j);
        t=mu(:,i).*(delta-mu(:,j));
        Hblock=phi{i}'*(repmat(t,1,ks(j)).*phi{j});
        H(k2(i)+1:k2(i+1),k2(j)+1:k2(j+1))=Hblock;
      end
    end
    H=H+diag(alpha);
  end
