function [ML,MS] = MarFut(ML0, MS0, G, R, N)
% Octave/MATLAB function to find margin balances for
% the Long and Short side of a Futures contract with
% modeled prices G and riskless returns R.
% INPUTS:                                  (Example)
%   ML0 = Long-side initial margin             (200)
%   MS0 = Short-side initial margin            (200)
%   G = Futures price matrix             (N+1 x N+1)
%   R = riskless returns matrix              (N x N)
%   N = binomial tree height, must be >1         (3)
% OUTPUTS:
%   ML = Long margin, non-recombining tree array 
%   MS = Short margin, non-recombining tree array
% EXAMPLE:
%  S=[100,0,0,0;87,115,0,0;75,100,133,0;65,87,115,152]
%  R=[1.025,0,0;1.03,1.02,0;1.035,1.025,1.01]
%  [F,G]= FwdFut(S,R,3);
%  [ML,MS]=MarFut(200,200,G,R,3)
%
  ML = zeros(1,2*2^N-1);  ML(1) = ML0;
  MS = zeros(1,2*2^N-1);  MS(1) = MS0;
  [nm,jm] = NJfromM(N); % recombining index functions
  for(m=1:2^N-1)
    Rnj=R(nm(m)+1,jm(m)+1); Gnj=G(nm(m)+1,jm(m)+1);
    Gup=G(nm(m)+2,jm(m)+2); Gdown=G(nm(m)+2,jm(m)+1);
    dGup = Gup-Gnj;    dGdown = Gdown-Gnj;
    ML(2*m)=ML(m)*Rnj+dGdown; ML(2*m+1)=ML(m)*Rnj+dGup;
    MS(2*m)=MS(m)*Rnj-dGdown; MS(2*m+1)=MS(m)*Rnj-dGup;
  end
  return
end
