/* 3.1. Model */


/* 

The timing of game is as follows.

Stage 1: The retailer chooses its output qr.
Stage 2: The intermediary chooses its output qi.
Stage 3: Suppliers choose thier outputs qsj.

*/


/* profit function */

pr:d1-d2*qr$

pir:(pr-pI)*qr$
pii:(pI-ps)*qi$
pisj:ps*qsj-(s1*qsj+(s2/2)*qsj^2)$

/* 3.1.1. Supplier Tier */

diff(pisj,qsj)$
solve([%=0],[qsj])$
OutcomeStage3:%;

/* Lemma 1. */
/*

The aggregate output of suppliers Qs is as follows.
That is, we have (2).

*/

S*qsj$
ev(%,OutcomeStage3)$
Qs:%;

/*

Since we have Qs=qi, 
in order to obtain the inverse supply fuction,
we solve Qs=qi for ps.

*/

solve([Qs=qi],[ps])$
InverseSupplyStage2:%;

/* 3.1.2. Intermediary Tier */

pii$
ev(%,InverseSupplyStage2)$
diff(%,qi)$
solve([%=0],[qi])$
OutcomeStage2:%;

/*

Since we have qi=qr, 
in order to obtain the inverse supply fuction,
we solve qi=qr for pI.

*/

qi$
ev(%,OutcomeStage2)$
solve([%=qr],[pI])$
InverseSupplyStage1:%;

/* 3.1.3. Retailer Tier */

pir$
ev(%,InverseSupplyStage1)$
diff(%,qr)$
solve([%=0],[qr])$
factor(%)$
OutcomeStage1:%;

/* 3.2. Equilibrium and Intermediary Profits */

/* Theorem 1. Equilibrium outcomes */


"Equilibrium outputs (qr,qi,Qs) are";
[qr,qi,S*qsj]$
ev(%,OutcomeStage3)$
ev(%,InverseSupplyStage2)$
ev(%,OutcomeStage2)$
ev(%,InverseSupplyStage1)$
ev(%,OutcomeStage1)$
factor(%)$
[Eqqr,Eqqi,EqQs]:%;
"";


"Equilibrium prices (pr, pI, ps) are";
[pr,pI,ps]$
ev(%,OutcomeStage3)$
ev(%,InverseSupplyStage2)$
ev(%,OutcomeStage2)$
ev(%,InverseSupplyStage1)$
ev(%,OutcomeStage1)$
factor(%)$
[Eqpr,EqpI,Eqps]:%;
"";


"Equilibrium Profits (pir, pii, pisj) are";
[pir,pii,pisj]$
ev(%,OutcomeStage3)$
ev(%,InverseSupplyStage2)$
ev(%,OutcomeStage2)$
ev(%,InverseSupplyStage1)$
ev(%,OutcomeStage1)$
factor(%)$
[Eqpir,Eqpii,Eqpisj]:%;

/* Theorem 2.Optimal number of suppliers for the intermediary */

"The first derivative of equilibrium profit of intermediary Eqpii 
with respect to the number of suppliers S is";

Eqpii$
diff(%,S)$
factor(%);

"Hence, the equilibrium profit of intermediary achieves a maximum 
at the following number of suppliers.";
Eqpii$
diff(%,S)$
solve([%=0],[S]);