function [ave_daily_cost] = MC_Inventory(demand_rate, delivery_cost, storage_cost, Total_Days)

%	Input Variables:
%	demand_rate -- gallons per day (e.g., 1500 gallons/day.)
%	delivery_cost -- delivery costs in dollars per delivery (e.g., $1000)
%	storage_cost -- storage cost per gallon per day (e.g., $.03)
%	Total_Days -- number of days to run the simulation (e.g., 30 days)
%
%	Output Variables:
%	ave_daily_cost -- average daily cost
%
%	Local variables:
%	Inventory -- current inventory in gallons
%     Days_Left -- days remaining in simulation
%	x -- random value  in [0,1]
%	daily_demand -- daily demand
%	FLAG -- an indicator used to terminate the algorithm
%	Delivery_Quantity -- delivery quantity of gasoline in gallons
%	Delivery_Interval -- time between deliveries in days
%	Total_Cost -- total running cost

%display input variables
demand_rate
delivery_cost
storage_cost
Total_Days

%calculate T, Q.
Delivery_Interval = round(sqrt((2*delivery_cost)/(storage_cost*demand_rate))) %optimized value
Delivery_Quantity = demand_rate*Delivery_Interval %optimized value


Days_Left = Total_Days;
Inventory = 0;
Total_Cost = 0;
FLAG = 0;
day = 1;

while FLAG==0% begin the next inventory cycle with a delivery
	Inventory = Inventory + Delivery_Quantity;
	Total_Cost = Total_Cost + delivery_cost;

	%determine whether silmulation will terminate during this cycle:
	if Delivery_Interval >= Days_Left
   		Delivery_Interval=Days_Left;
   		FLAG = 1;
	end

	%simulate each day in the inventory cycle:
      for i = 1:Delivery_Interval
   		x = rand(1);
            daily_demand = demand_submodel(x);
   		Inventory = Inventory - daily_demand %update the current inventory
         if Inventory <= 0%any inventory left?
               sprintf('Ran out of gas!!\n')
               Inventory
               Inventory = 0;%if not, then don't increase cost
       %        FLAG=1
       %        break;
            else%add expenses for storage of remaining fuel
      		Total_Cost = Total_Cost +Inventory*storage_cost;
            end
            Days_Left = Days_Left-1;
            Keep_Inventory(day) = Inventory;
            Keep_daily_demand(day) = daily_demand;
            day = day+1;
	end
end%while
   Days_Left
   %compute average daily cost
   ave_daily_cost = Total_Cost/day;
   
   subplot(2,1,1),plot(Keep_Inventory)
   ylabel('inventory')
   subplot(2,1,2),plot(Keep_daily_demand)
   ylabel('daily demand')
   % 
%--------------------------------------------------------------
function [q] = demand_submodel(x)
   q = (1+x)*1000;%fit historgram with a line!
return


