function [newdemand, cost, inventory] = nextweek(x);
% [newdemand, cost, inventory] = nextweek(x);
% Input: x = Beslut om produktion i denna vecka.
% Output: newdemand = efterfrågan i denna vecka.
%         inventory = utgående lagerposition i denna vecka.
%         cost      = kostnad för produktion, lager, restorder i denna
%                     vecka.
% Obs: Utdata beror även på beslut om  produktion i tidigare veckor!

global DEMAND TOTALCOST PRODUCTION INVENTORY DEMANDINIT DRIFT ...
     TBREAK DEMANDSIGMA;

N          = 3;
Lagerranta = 0.20;
Setupcost  = [2100 2200 2400];
Unitcost   = [260 230 215];
Backcost   = [100 100 100];
Leadtime   = [2 3 4];
Invencost  = Lagerranta*Unitcost/52;
INVENTORY(1,1:N) = [263 280 300];
Trendshiftprob = 0.01;

[T] = size(PRODUCTION,1) + 1;

% Check input
if (size(x,1) > 1) error('x måste vara en radvektor'); end
if (size(x,2) ~= N) error('Fel dimension på x'); end
if (length(find(x < 0)) > 0) error('x måste vara icke-negativ'); end
if (length(find(x-round(x) ~= 0)) > 0) error('x måste vara heltalig'); end

PRODUCTION = [PRODUCTION; x];

if (T == 1)
  % Initiering
  DEMANDINIT  = [100 85 70];
  DRIFT       = [0.7 0 0];
  TBREAK      = [0 0 0];
  DEMANDSIGMA = [10 7 9];
  TOTALCOST = 0;
end

% Break of trend
for i = 1:N
  if (rand(1) < Trendshiftprob)
    DEMANDINIT(i) =  DEMANDINIT(i)+(T-TBREAK(i))*DRIFT(i); 
    DRIFT(i)      =  rand(1);
    TBREAK(i)     = T;
  end    
end

newdemand = max(0, ...
 floor(DEMANDINIT+DRIFT.*(T-TBREAK)+DEMANDSIGMA.*randn(size(x))));  

DEMAND = [DEMAND; newdemand];

% Beräkna nytt lager
inventory = zeros(1,N);

for i = 1:N
  if  T-Leadtime(i) > 0
    inventory(i) = INVENTORY(T,i)+ ...
	PRODUCTION(T-Leadtime(i),i)-newdemand(i);
  else
    inventory(i) = INVENTORY(T,i)-newdemand(i);
  end
end

INVENTORY = [INVENTORY; inventory];

tmp  = zeros(size(x));
tmp1 = find(x > 0);
tmp(tmp1) = ones(length(tmp1),1);

cost = Invencost*(max(0,inventory'))+Backcost*(max(0,-inventory'))+ ...
       Setupcost*tmp';

TOTALCOST = TOTALCOST + cost;






