%This is a function for resource dynamics of nospec species and one resource
function n = res2(nospec,specpara,supply1,loss1,supply2,loss2,nostep)
% species parameters
% growth1,2: growth per unit resource 1 and 2
% uptake1,2: uptake per unit growth
% mortality
% n0 initial size

%resource parameters:
%           supply1, 2: resource 1 and 2 supply 
%           loss1, 2: rate at which resource 1 and 2 is removed

for i=1:nospec
  growth1 =specpara(:,1);
  growth2 =specpara(:,2);
  uptake1=specpara(:,3);
  uptake2=specpara(:,4);
  mortality=specpara(:,5);
  n0=specpara(:,6);
end


resource1 =[supply1/loss1];
resource2 =[supply2/loss2];
x1=[n0'];

for t=1:nostep
   for i=1:nospec
      xtemp(i)= x1(t,i) + x1(t,i)*(min(growth1(i)*resource1(t),growth2(i)*resource2(t)) - mortality(i));
      if xtemp(i)<0
         xtemp(i) = 0;
      end
   end
   g=(x1(t,:).*min([growth1.*resource1(t),growth2*resource2(t)]') + mortality'.*x1(t,:))';

   %restemp1= resource1(t) + supply1 - loss1*resource1(t) - sum(growth1.*uptake1.*x1(t,:)')*resource1(t);
   %restemp2= resource2(t) + supply2 - loss2*resource2(t) - sum(growth2.*uptake2.*x1(t,:)')*resource2(t);
   restemp1= resource1(t) + supply1 - loss1*resource1(t) - sum(g.*uptake1);
   restemp2= resource2(t) + supply2 - loss2*resource2(t) - sum(g.*uptake2);
   if restemp1 < 0
      restemp1=0;
   end
   if restemp2 < 0
      restemp2=0;
   end
   
   resource1 =[resource1 restemp1 ];
   resource2 =[resource2 restemp2 ];
   x1 = [x1; xtemp];
end
n = [resource1;resource2;transpose(x1)];


   
