contract MasterChef is Ownable {
    using SafeMath for uint256;
    using SafeERC20 for IERC20;

    // Info of each user.
    struct UserInfo {
        uint256 amount; // How many LP tokens the user has provided.
        uint256 rewardDebt; // Reward debt. See explanation below.
        //
        // We do some fancy math here. Basically, any point in time, the amount of MMs
        // entitled to a user but is pending to be distributed is:
        //
        //   pending reward = (user.amount * pool.accMMPerShare) - user.rewardDebt
        //
        // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
        //   1. The pool's `accMMPerShare` (and `lastRewardBlock` and `amount`) gets updated.
        //   2. User receives the pending reward sent to his/her address.
        //   3. User's `amount` gets updated.
        //   4. User's `rewardDebt` gets updated.
    }

    // Info of each pool.
    struct PoolInfo {
        IERC20 lpToken; // Address of LP token contract.
        uint256 allocPoint; // How many allocation points assigned to this pool. MMs to distribute per block.
        uint256 lastRewardBlock; // Last block number that MMs distribution occurs.
        uint256 accMMPerShare; // Accumulated MMs per share, times 1e12. See below.
        uint256 amount; // How many LP tokens in the pool.
    }
	
    // MM staking pool id: the first pool to be added in MasterChef
    uint256 public constant mmPoolId = 0;

    // The MM TOKEN! default mining pool distribution is 70% initially
    MMToken public mm;
    // Dev fund (25% initially)
    uint256 public devFundDivRate = 28;
    // Dev address.
    address public devaddr;
    // Dev distribution multiplier
    uint256 public devMultiplier = 10;
    // Treasury fund (5% initially)
    uint256 public treasuryDivRate = 14;
    // Treasury address.
    address public treasuryAddr;
    // Treasury distribution multiplier
    uint256 public treasuryMultiplier = 1;
    // Block number when bonus MM period ends.
    uint256 public bonusEndBlock;
    // MM tokens created per block.
    uint256 public mmPerBlock;
    // Bonus muliplier for early mm makers.
    uint256 public constant BONUS_MULTIPLIER = 10;

    // Info of each pool.
    PoolInfo[] public poolInfo;
    // Info of each user that stakes LP tokens.
    mapping(uint256 => mapping(address => UserInfo)) public userInfo;
    // Total allocation points. Must be the sum of all allocation points in all pools.
    uint256 public totalAllocPoint = 0;
    // The block number when MM mining starts.
    uint256 public startBlock;	
    // The buyback notifiers: usually earning strategy.
    mapping(address => bool) public buybackNotifiers;

    // Events
    event Recovered(address token, uint256 amount);
    event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
    event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
    event EmergencyWithdraw(
        address indexed user,
        uint256 indexed pid,
        uint256 amount
    );
    event BuybackMM(uint256 _buybackAmount, uint256 _preAmount);

    constructor(
        MMToken _mm,
        address _devaddr,
        address _treasuryAddr,
        uint256 _mmPerBlock,
        uint256 _startBlock,
        uint256 _bonusEndBlock
    ) public {
        mm = _mm;
        devaddr = _devaddr;
        treasuryAddr = _treasuryAddr;
        mmPerBlock = _mmPerBlock;
        bonusEndBlock = _bonusEndBlock;
        startBlock = _startBlock;
    }

    function poolLength() external view returns (uint256) {
        return poolInfo.length;
    }

    // Add a new lp to the pool. Can only be called by the owner.
    // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
    function add(
        uint256 _allocPoint,
        IERC20 _lpToken,
        bool _withUpdate
    ) public onlyOwner {
        if (_withUpdate) {
            massUpdatePools();
        }
        uint256 lastRewardBlock = block.number > startBlock
            ? block.number
            : startBlock;
        totalAllocPoint = totalAllocPoint.add(_allocPoint);
        poolInfo.push(
            PoolInfo({
                lpToken: _lpToken,
                allocPoint: _allocPoint,
                lastRewardBlock: lastRewardBlock,
                accMMPerShare: 0,
                amount: 0
            })
        );
    }

    // Update the given pool's MM allocation point. Can only be called by the owner.
    function set(
        uint256 _pid,
        uint256 _allocPoint,
        bool _withUpdate
    ) public onlyOwner {
        if (_withUpdate) {
            massUpdatePools();
        }
        totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
            _allocPoint
        );
        poolInfo[_pid].allocPoint = _allocPoint;
    }

    // Return reward multiplier over the given _from to _to block.
    function getMultiplier(uint256 _from, uint256 _to)
        public
        view
        returns (uint256)
    {
        if (_to <= bonusEndBlock) {
            return _to.sub(_from).mul(BONUS_MULTIPLIER);
        } else if (_from >= bonusEndBlock) {
            return _to.sub(_from);
        } else {
            return
                bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
                    _to.sub(bonusEndBlock)
                );
        }
    }

    // View function to see pending MMs on frontend.
    function pendingMM(uint256 _pid, address _user)
        external
        view
        returns (uint256)
    {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][_user];
        uint256 accMMPerShare = pool.accMMPerShare;
        uint256 lpSupply = getLpSupply(_pid);
        if (block.number > pool.lastRewardBlock && lpSupply != 0) {
            uint256 multiplier = getMultiplier(
                pool.lastRewardBlock,
                block.number
            );
            uint256 mmReward = multiplier
                .mul(mmPerBlock)
                .mul(pool.allocPoint)
                .div(totalAllocPoint);
            accMMPerShare = accMMPerShare.add(mmReward.mul(1e12).div(lpSupply));
        }
        return user.amount.mul(accMMPerShare).div(1e12).sub(user.rewardDebt);
    }

    // Update reward vairables for all pools. Be careful of gas spending!
    function massUpdatePools() public {
        uint256 length = poolInfo.length;
        for (uint256 pid = 0; pid < length; ++pid) {
            updatePool(pid);
        }
    }
	
    // return Lp supply of given pool
    function getLpSupply(uint256 _pid) public view returns (uint256) {	
        PoolInfo storage pool = poolInfo[_pid];
        uint256 lpSupply = 0;
        if (_pid == mmPoolId) {
            lpSupply = pool.amount;
        } else {
            lpSupply = pool.lpToken.balanceOf(address(this));
        }
        return lpSupply;
    }
	
    // update the pool's `accMMPerShare`
    function updateAccMMPerShare(uint256 _pid, uint256 _delta, uint256 lpSupply) internal {
        PoolInfo storage pool = poolInfo[_pid];
        pool.accMMPerShare = pool.accMMPerShare.add(_delta.mul(1e12).div(lpSupply));
    }
	
    // Update MM staking pool with given _amount reward received from buyback.
    function notifyBuybackReward(uint256 _amount) external {
        require(buybackNotifiers[msg.sender] == true, "!buybackNotifier");
        require(_amount > 0 && _amount < mm.totalSupply(), "!_amount");	
		
        PoolInfo storage pool = poolInfo[mmPoolId];	
        require(pool.amount > 0, "!mmPoolActivated");
        
        updateAccMMPerShare(mmPoolId, _amount, pool.amount);
        emit BuybackMM(_amount, pool.amount);
    }

    // Update reward variables of the given pool to be up-to-date.
    function updatePool(uint256 _pid) public {
        PoolInfo storage pool = poolInfo[_pid];
        if (block.number <= pool.lastRewardBlock) {
            return;
        }
        uint256 lpSupply = getLpSupply(_pid);
        if (lpSupply == 0) {
            pool.lastRewardBlock = block.number;
            return;
        }
        uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
        uint256 mmReward = multiplier
            .mul(mmPerBlock)
            .mul(pool.allocPoint)
            .div(totalAllocPoint);
        updateAccMMPerShare(_pid, mmReward, lpSupply);	
        mm.mint(devaddr, mmReward.div(devFundDivRate).mul(devMultiplier));	
        mm.mint(treasuryAddr, mmReward.div(treasuryDivRate).mul(treasuryMultiplier));
        mm.mint(address(this), mmReward);
        pool.lastRewardBlock = block.number;
    }

    // Deposit LP tokens to MasterChef for MM allocation.
    function deposit(uint256 _pid, uint256 _amount) public {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        updatePool(_pid);
        if (user.amount > 0) {
            uint256 pending = user
                .amount
                .mul(pool.accMMPerShare)
                .div(1e12)
                .sub(user.rewardDebt);
            safeMMTransfer(msg.sender, pending);
        }
        pool.lpToken.safeTransferFrom(
            address(msg.sender),
            address(this),
            _amount
        );
        user.amount = user.amount.add(_amount);
        pool.amount = pool.amount.add(_amount);
        user.rewardDebt = user.amount.mul(pool.accMMPerShare).div(1e12);
        emit Deposit(msg.sender, _pid, _amount);
    }

    // Withdraw LP tokens from MasterChef.
    function withdraw(uint256 _pid, uint256 _amount) public {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        require(user.amount >= _amount, "withdraw: not good");
        updatePool(_pid);
        uint256 pending = user.amount.mul(pool.accMMPerShare).div(1e12).sub(
            user.rewardDebt
        );
        safeMMTransfer(msg.sender, pending);
        user.amount = user.amount.sub(_amount);
        pool.amount = pool.amount.sub(_amount);
        user.rewardDebt = user.amount.mul(pool.accMMPerShare).div(1e12);
        pool.lpToken.safeTransfer(address(msg.sender), _amount);
        emit Withdraw(msg.sender, _pid, _amount);
    }

    // Withdraw without caring about rewards. EMERGENCY ONLY.
    function emergencyWithdraw(uint256 _pid) public {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        pool.lpToken.safeTransfer(address(msg.sender), user.amount);
        emit EmergencyWithdraw(msg.sender, _pid, user.amount);
        pool.amount = pool.amount.sub(user.amount);
        user.amount = 0;
        user.rewardDebt = 0;
    }

    // Safe mm transfer function, just in case if rounding error causes pool to not have enough MMs.
    function safeMMTransfer(address _to, uint256 _amount) internal {
        uint256 mmBal = mm.balanceOf(address(this));
        if (_amount > mmBal) {
            mm.transfer(_to, mmBal);
        } else {
            mm.transfer(_to, _amount);
        }
    }

    // Update dev address by the previous dev.
    function dev(address _devaddr) public {
        require(msg.sender == devaddr, "dev: wut?");
        devaddr = _devaddr;
    }

    // Update treasury address by the previous treasury.
    function setTreasury(address _treasuryAddr) public {
        require(msg.sender == treasuryAddr, "treasury: wut?");
        treasuryAddr = _treasuryAddr;
    }

    // **** Additional functions separate from the original masterchef contract ****

    function setMMPerBlock(uint256 _mmPerBlock) public onlyOwner {
        require(_mmPerBlock > 0, "!mmPerBlock-0");

        mmPerBlock = _mmPerBlock;
    }

    function setBonusEndBlock(uint256 _bonusEndBlock) public onlyOwner {
        bonusEndBlock = _bonusEndBlock;
    }

    function setDevFundDivRate(uint256 _devFundDivRate) public onlyOwner {
        require(_devFundDivRate > 0, "!devFundDivRate-0");
        devFundDivRate = _devFundDivRate;
    }

    function setTreasuryDivRate(uint256 _treasuryDivRate) public onlyOwner {
        require(_treasuryDivRate > 0, "!treasuryDivRate-0");
        treasuryDivRate = _treasuryDivRate;
    }
	
    function setDevMultiplier(uint256 _devMultiplier) public onlyOwner {
        require(_devMultiplier > 0, "!devMultiplier-0");
        devMultiplier = _devMultiplier;
    }

    function setTreasuryMultiplier(uint256 _treasuryMultiplier) public onlyOwner {
        require(_treasuryMultiplier > 0, "!treasuryMultiplier-0");
        treasuryMultiplier = _treasuryMultiplier;
    }

    function setBuybackNotifier(address _notifier, bool _enable) public onlyOwner {
        require(_notifier != address(0), "!invalid-notifier");
        buybackNotifiers[_notifier] = _enable;
    }
	
    // in case we need to migrate to new MM owner
    function transferMMOwnership() public onlyOwner {
        require(mm.owner() == address(this), "!notMMOwner");
        mm.transferOwnership(owner());
    }
}
// MasterChef was the master of mm. He now governs over MMS. He can make mm and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once MMS is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
function getLpSupply(uint256 _pid) public view returns (uint256) {	
    PoolInfo storage pool = poolInfo[_pid];
    uint256 lpSupply = 0;
    if (_pid == mmPoolId) {
        lpSupply = pool.amount;
    } else {
        lpSupply = pool.lpToken.balanceOf(address(this));
    }
    return lpSupply;
}

// return Lp supply of given pool