function [sX,vx] = fContestEquilibrium(vN,fG)
  % This function computes the equilibria in sequential contests as
  % described in "Optimal sequential contests" by Toomas Hinnosaar, 
  % avalable at http://toomas.hinnosaar.net/contests.pdf
  % Matlab code written by Toomas Hinnosaar (toomas@hinnosaar.net)
  % Inputs: vN     = [n_1,...,n_T]
  %         fG     = g(X) function (symbolic), for example 
  %                       @(X)(X*(1-X))   for Tullock payoff X*(1-X)
  %                       @(X)(0.3*(1-X)) for Linear 0.3*(1-X)
  syms X;
  fdG = matlabFunction(symfun(simplify(-diff(fG(X),X)),X));
  sAlpha = fdG(1);
  [sXapprox,vxapprox] = fContestEquilibriumLinear(vN,sAlpha);
  bUseapprox = 0;
  sT     = max(size(vN));
  mS     = zeros(sT,sT);    % Matrix to hold all information measures
  fF{1}  = symfun(X,X);     % f_t functions
  sX     = 0;
  for k  = 1:sT
    if k>1
      mS(k,:) = mS(k-1,:)+[1 mS(k-1,1:sT-1)]*vN(sT+1-k);
      fGk{k} = symfun(simplify(-diff(fGk{k-1}(X),X)*fG(X)),X); % g_k(X) = -g_k'(X)*g(X)
    else
      mS(1,1)= vN(sT); % Information before the last period is just S=(n_T) 
      fGk{1} = symfun(fG(X),X); % g_k functions  
    end
    fTemp = symfun(X,X);
    for t=1:k
      fTemp = symfun(simplify(fTemp(X)-mS(k,t)*fGk{t}(X)),X);
    end
    fF{k+1} = matlabFunction(fTemp);
    sX      = fCondition1(fF{k+1},sX);
    if sX<0
      %disp('Condition 1 is not satisfied for f_%d (part %d)',k+1,-sX)
      fprintf('Condition 1 is not satisfied for f_%d',sT-k);
      break  
    else      
    end
    if max(abs(1-sX),abs(sXapprox-sX))<1e-6 
      bUseapprox = 1;
      disp('Approximation seems to be good enough ');
      break
    end
  end
  if sX<1e-6 % Includes the case when sX=0
   vx = [];   
  elseif bUseapprox>0
    vx = vxapprox;
    sX = sXapprox;
  else        
    vx = zeros(sum(vN),1);
    sfkX = sX;
    for k=1:sT
      t = sT+1-k;  
      sfkX1 = fF{k+1}(sX);
      vx(sum(vN(1:t-1))+[1:vN(t)]) = (sfkX-sfkX1)/vN(t);
      sfkX  = sfkX1;
    end
  end
end
