%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  NAME :
%      bookproduction.pl
%
% VERSION :
%     0
%
% AUTHOR : Matthieu Petit and Arnaud Gotlieb
%
% FUNCTION :
%      Model of the book production problem
%      
% REMARKS : any problem, contact petit@(without advertissement)irisa.fr
%
% NOTE TO THE USER :  need ctr_proba_v0.pl to work
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


%%%%%%%%%%%%%%%%%%%%%%%
% Book Production
%%%%%%%%%%%%%%%%%%%%%%%

book_production(C,N,Distribution,M,Opt) :-     	  
        init_env(Env),
        domain(Distribution,1,10),
        exec(C),
        Prod in 1..N,
        construct_domain(N,Domain),
        choose(Demand,Domain-Distribution,[],Opt,Env),
        Prod#>=Demand,
        Surplus #= Prod-Demand,
        Cost #= Surplus+Cost_Rest,        
        M1 is M-1,
        book_production_rec(N,Domain-Distribution,M1,Production_Rest,Surplus,Cost_Rest,Opt,Env),
        lists:append([Prod|Production_Rest],Distribution,Labeling_List),
        labeling([minimize(Cost)],Labeling_List).
        
book_production_rec(_N,_Domain-_Distribution,0,[],_Surplus,0,_Opt,_Env).

book_production_rec(N,Domain-Distribution,M,[Prod|Production_Rest],Surplus,Cost,Opt,Env) :-
        Prod in 1..N,
	choose(Demand,Domain-Distribution,[],Opt,Env),
        Prod#>=Demand-Surplus,
        Surplus2 #= Prod-Demand+Surplus,
        Cost #= Prod-Demand+Surplus+Cost_Rest,
        M1 is M-1,
        book_production_rec(N,Domain-Distribution,M1,Production_Rest,Surplus2,Cost_Rest,Opt,Env).


construct_domain(0,[]) :-
        !.

construct_domain(N,Res) :-
        !,
        N1 is N-1,
        construct_domain(N1,List),
        lists:append(List,[N],Res).
