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 CYNs
        // entitled to a user but is pending to be distributed is:
        //
        //   pending reward = (user.amount * pool.accCynPerShare) - user.rewardDebt
        //
        // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
        //   1. The pool's `accCynPerShare` (and `lastRewardBlock`) 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. CYNs to distribute per block.
        uint256 lastRewardBlock;  // Last block number that DIFs distribution occurs.
        uint256 accCynPerShare; // Accumulated CYNs per share, times 1e12. See below.
    }

    // The CYN TOKEN!
    CynToken public cyn;
    // Dev address.
    address public devaddr;
    // weth address.
    address public weth;
    // The migrator contract. It has a lot of power. Can only be set through governance (owner).
    IMigratorChef public migrator;

    // Info of each pool.
    PoolInfo[] public poolInfo;
    // Info of each user that stakes LP tokens.
    mapping (uint256 => mapping (address => UserInfo)) public userInfo;
    // Total allocation poitns. Must be the sum of all allocation points in all pools.
    // The block number when CYN mining starts.
    uint256 public startBlock;

    uint256 public capacity = 1000000000 * 10**18;
    uint256 public totalSupply = 0;

    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);

    constructor(
        CynToken _cyn,
        address _devaddr,
        uint256 _startBlock,
        address _weth
    ) public {
        cyn = _cyn;
        devaddr = _devaddr;
        startBlock = _startBlock;
        weth = _weth;
    }

    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;
        poolInfo.push(PoolInfo({
            lpToken: _lpToken,
            allocPoint: _allocPoint,
            lastRewardBlock: lastRewardBlock,
            accCynPerShare: 0
        }));
    }

    function setCapacity(uint256 _capacity) public onlyOwner {
        require(_capacity > totalSupply, "New capacity must be larger than totalSupply");
        capacity = _capacity;
    }

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

    // Set the migrator contract. Can only be called by the owner.
    function setMigrator(IMigratorChef _migrator) public onlyOwner {
        migrator = _migrator;
    }

    // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
    function migrate(uint256 _pid) public {
        require(address(migrator) != address(0), "migrate: no migrator");
        PoolInfo storage pool = poolInfo[_pid];
        IERC20 lpToken = pool.lpToken;
        uint256 bal = lpToken.balanceOf(address(this));
        lpToken.safeApprove(address(migrator), bal);
        IERC20 newLpToken = migrator.migrate(lpToken);
        require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
        pool.lpToken = newLpToken;
    }

    // View function to see pending CYNs on frontend.
    function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {
        PoolInfo storage pool = poolInfo[_pid];
        // Stack too deep, try removing local variables. 
        // UserInfo storage user = userInfo[_pid][_user];
        uint256 accCynPerShare = pool.accCynPerShare;
        uint256 lpSupply = pool.lpToken.balanceOf(address(this));
        if (block.number > pool.lastRewardBlock && lpSupply != 0) {
            //uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
            //uint256 cynReward = multiplier.mul(cynPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
            // IUniswapV2Pair pair = IUniswapV2Pair(address(pool.lpToken));
            // if (address(pair) == address(0)) {
            //     return 0;
            // }
            // address token0 = pair.token0();
            // address token1 = pair.token1();
            // if (token0 != weth && token1 != weth)
            // {
            //     return 0;
            // }
            // (uint reserve0, uint reserve1,) = pair.getReserves();
            // uint reserveEth = token0 == weth ? reserve0 : reserve1;
            uint lptokenAmount = getLptokenAmount(pool.lpToken ,lpSupply);
            uint256 cynReward = MintRewardLibrary.getReward(lptokenAmount).mul(block.number.sub(pool.lastRewardBlock)).mul(pool.allocPoint).div(100);
            if (cynReward.add(totalSupply) > capacity) {
                cynReward = capacity.sub(totalSupply);
            }
            accCynPerShare = accCynPerShare.add(cynReward.mul(1e12).div(lpSupply));
        }
        return userInfo[_pid][_user].amount.mul(accCynPerShare).div(1e12).sub(userInfo[_pid][_user].rewardDebt);
    }

    function getLptokenAmount(IERC20 lpToken, uint256 lpSupply) internal view returns (uint256) {
        IUniswapV2Pair pair = IUniswapV2Pair(address(lpToken));
        if (address(pair) == address(0)) {
            return 0;
        }
        address token0 = pair.token0();
        address token1 = pair.token1();
        if (token0 != weth && token1 != weth)
        {
            return 0;
        }
        (uint reserve0, uint reserve1,) = pair.getReserves();
        uint reserveEth = token0 == weth ? reserve0 : reserve1;
        return reserveEth.mul(2).mul(lpSupply).div(pair.totalSupply());
    }

    // 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);
        }
    }

    // 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 = pool.lpToken.balanceOf(address(this));
        if (lpSupply == 0) {
            pool.lastRewardBlock = block.number;
            return;
        }
        //uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
        //uint256 cynReward = multiplier.mul(cynPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
        IUniswapV2Pair pair = IUniswapV2Pair(address(pool.lpToken));
        if (address(pair) == address(0)) {
            return;
        }
        address token0 = pair.token0();
        address token1 = pair.token1();
        if (token0 != weth && token1 != weth)
        {
            pool.lastRewardBlock = block.number;
            return;
        }
        (uint reserve0, uint reserve1,) = pair.getReserves();
        uint reserveEth = token0 == weth ? reserve0 : reserve1;
        uint256 libAmount = MintRewardLibrary.getReward(reserveEth.mul(2).mul(lpSupply).div(pair.totalSupply()));
        uint256 cynReward = libAmount.mul(block.number.sub(pool.lastRewardBlock)).mul(pool.allocPoint).div(100);
        if (cynReward.add(totalSupply) > capacity) {
            cynReward = capacity.sub(totalSupply);
        }
        if (cynReward == 0) {
            pool.lastRewardBlock = block.number;
            return ;
        }
        cyn.mint(devaddr, cynReward.div(10));
        cyn.mint(address(this), cynReward);
        // mining for devaddr is additional, don't count
        totalSupply = totalSupply.add(cynReward);
        pool.accCynPerShare = pool.accCynPerShare.add(cynReward.mul(1e12).div(lpSupply));
        pool.lastRewardBlock = block.number;
    }

    // Deposit LP tokens to MasterChef for CYN 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.accCynPerShare).div(1e12).sub(user.rewardDebt);
            safeCynTransfer(msg.sender, pending);
        }
        pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
        user.amount = user.amount.add(_amount);
        user.rewardDebt = user.amount.mul(pool.accCynPerShare).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.accCynPerShare).div(1e12).sub(user.rewardDebt);
        safeCynTransfer(msg.sender, pending);
        user.amount = user.amount.sub(_amount);
        user.rewardDebt = user.amount.mul(pool.accCynPerShare).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);
        user.amount = 0;
        user.rewardDebt = 0;
    }

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

    // Update dev address by the previous dev.
    function dev(address _devaddr) public {
        require(msg.sender == devaddr, "dev: wut?");
        devaddr = _devaddr;
    }
}
// MasterChef is the master of cyn. He can make cyn 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 CYN is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
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);
        user.amount = 0;
        user.rewardDebt = 0;
    }
// Withdraw without caring about rewards. EMERGENCY ONLY.