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

    // The HYDG TOKEN!
    HydronG public hydg;
    AtmosphereArcERC20 public hydron;
    //AtmosphereArcERC20 public atmos;
    //AtmosphereArcERC20 public atmosg;
    // Dev address.
    address public devaddr;
    // Block number when bonus HYDG period ends.
    uint256 public bonusEndBlock;
    // HYDG tokens created per block.
    uint256 public hydgPerBlock;
    // Bonus muliplier for early HYDG makers.
    uint256 public constant BONUS_MULTIPLIER = 10;
    // The migrator contract. It has a lot of power. Can only be set through governance (owner).
    IMigrator public migrator;
    mapping (address => bool) public whitelist;
    // 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.
    uint256 public totalAllocPoint = 0;
    // The block number when HYDG mining starts.
    uint256 public startBlock;
    uint256 public emissionCap;
    
    mapping (address => uint256) public balancesHyd;
    mapping (address => uint256) public balancesAtm;

    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(
        HydronG _hydg,
        AtmosphereArcERC20 _hydron,
        //AtmosphereArcERC20 _atmos,
        //AtmosphereArcERC20 _atmosg,
        address _devaddr,
        uint256 _hydgPerBlock,
        uint256 _startBlock,
        uint256 _bonusEndBlock,
        uint256 _emissionCap,
        address [] memory _whitelist
    ) public {
        hydg = _hydg;
        hydron= _hydron;
        //atmos= _atmos;
        //atmosg= _atmosg;
        devaddr = _devaddr;
        hydgPerBlock = _hydgPerBlock;
        bonusEndBlock = _bonusEndBlock;
        startBlock = _startBlock;
        emissionCap = _emissionCap;
        for(uint256 i=0;i<_whitelist.length;i++){
            whitelist[_whitelist[i]]=true;
        }
    }

    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,
            accHydgPerShare: 0
        }));
    }
    
    function convertHydron(uint256 amount) public{
        require(hydron.balanceOf(msg.sender)>=amount,"not enough hydron");
        require(whitelist[msg.sender],"forbidden");
        require(amount>100,"amount too small");
        require(amount.add(balancesHyd[msg.sender])<=(((hydron.balanceOf(msg.sender)).add(balancesHyd[msg.sender])).mul(emissionCap)).div(100),string(abi.encodePacked("you can't convert more than ",emissionCap,"% of your hydron capital")));
        hydron.transferFrom(msg.sender,address(this),amount);
        balancesHyd[msg.sender]=balancesHyd[msg.sender].add(amount);
        hydg.mint(msg.sender,amount.mul(100));
    }
    
   /* function convertHydAtmosg(uint256 amount) public{
        require(hydron.balanceOf(msg.sender)>=amount,"not enough hydron");
        require(whitelist[msg.sender],"forbidden");
        require(amount<=(emissionCap.div(100)).mul(amount),string(abi.encodePacked("you can't convert more than ",emissionCap,"% of your balance")));
        hydron.transferFrom(msg.sender,address(this),amount);
        balancesAtm[msg.sender]=balancesAtm[msg.sender].add(amount);
        atmosg.mintToken(msg.sender,amount.mul(100));
    }
    
    function convertAtmosAtmosg(uint256 amount) public{
        require(atmos.balanceOf(msg.sender)>=amount,"not enough atmos");
        atmos.transferFrom(msg.sender,address(this),amount);
        atmos.burn(amount);
        atmosg.mintToken(msg.sender,amount.mul(20));
    }
    
    function convertAtmosgAtmos(uint256 amount) public{
        require(atmosg.balanceOf(msg.sender)>=amount,"not enough atmos g");
        atmosg.transferFrom(msg.sender,address(this),amount);
        atmosg.burn(amount);
        atmos.mintToken(msg.sender,amount.mul(20));
    }
    
     function convertHydrongAtmosg(uint256 amount) public{
        require(hydg.balanceOf(msg.sender)>=amount,"not enough hydron g");
        hydg.transferFrom(msg.sender,address(this),amount);
        hydg.burn(amount);
        atmosg.mintToken(msg.sender,amount);
    }
    
    function convertAtmosgHydrong(uint256 amount) public{
        require(atmosg.balanceOf(msg.sender)>=amount,"not enough atmos g");
        atmosg.transferFrom(msg.sender,address(this),amount);
        atmosg.burn(amount);
        hydg.mint(msg.sender,amount);
    }*/
    
    function changeHydCap(uint256 newcap) public onlyOwner{
        emissionCap=newcap;
    }
    
    function addWhitelist(address wAdd) public onlyOwner{
        whitelist[wAdd]=true;
    }
    
     function removeWhitelist(address wAdd) public onlyOwner{
        whitelist[wAdd]=false;
    }
    
    /*function getAtmosgforAtmos(uint256 amount) public{
        require(atmos.balanceOf(msg.sender)>=amount,"not enough hydron");
        atmos.transferFrom(msg.sender,address(this),amount);
        balancesAtm[msg.sender]=balancesAtm[msg.sender].add(amount);
    }*/
    
    function releaseHydronForHydrong(uint256 amount) public{
        require(balancesHyd[msg.sender]>=amount,"too many hydrons");
        require(hydg.balanceOf(msg.sender)>=amount.mul(100),"not enough tokens");
        hydg.transferFrom(msg.sender,address(this),amount.mul(100));
        hydg.burn(amount.mul(100));
        balancesHyd[msg.sender]=balancesHyd[msg.sender].sub(amount);
        hydron.transfer(msg.sender,amount);
    }
    
    function changeHydgPerBlock(uint256 newAmount) public onlyOwner{
        hydgPerBlock=newAmount;
    }
    
   /* function releaseHydronForAtmosg(uint256 amount) public{
        require(balancesAtm[msg.sender]>=amount,"too many hydrons");
        require(atmosg.balanceOf(msg.sender)>=amount.mul(100),"not enough tokens");
        atmosg.transferFrom(msg.sender,address(this),amount.mul(100));
        atmosg.burn(amount.mul(100));
        balancesAtm[msg.sender]=balancesAtm[msg.sender].sub(amount);
        hydron.transfer(msg.sender,amount);
    }*/
    
    function hydronhgBalance(address _add) public view returns(uint256){
        return balancesHyd[_add];
    }
    
    
    /*function hydronAtmBalance(address _add) public view returns(uint256){
        return balancesAtm[_add];
    }*/
    
    // Update the given pool's HYDG 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;
    }

    // Set the migrator contract. Can only be called by the owner.
    function setMigrator(IMigrator _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;
    }

    // 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 HYDGs on frontend.
    function pendingHydg(uint256 _pid, address _user) external view returns (uint256) {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][_user];
        uint256 accHydgPerShare = pool.accHydgPerShare;
        uint256 lpSupply = pool.lpToken.balanceOf(address(this));
        if (block.number > pool.lastRewardBlock && lpSupply != 0) {
            uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
            uint256 hydgReward = multiplier.mul(hydgPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
            accHydgPerShare = accHydgPerShare.add(hydgReward.mul(1e12).div(lpSupply));
        }
        return user.amount.mul(accHydgPerShare).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);
        }
    }

    // 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 hydgReward = multiplier.mul(hydgPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
        hydg.mint(devaddr, hydgReward.div(10));
        hydg.mint(address(this), hydgReward);
        pool.accHydgPerShare = pool.accHydgPerShare.add(hydgReward.mul(1e12).div(lpSupply));
        pool.lastRewardBlock = block.number;
    }

    // Deposit LP tokens to MasterContract for Hydg 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.accHydgPerShare).div(1e12).sub(user.rewardDebt);
            safeHydgTransfer(msg.sender, pending);
        }
        pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
        user.amount = user.amount.add(_amount);
        user.rewardDebt = user.amount.mul(pool.accHydgPerShare).div(1e12);
        emit Deposit(msg.sender, _pid, _amount);
    }

    // Withdraw LP tokens from MasterContract.
    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.accHydgPerShare).div(1e12).sub(user.rewardDebt);
        safeHydgTransfer(msg.sender, pending);
        user.amount = user.amount.sub(_amount);
        user.rewardDebt = user.amount.mul(pool.accHydgPerShare).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 hydg transfer function, just in case if rounding error causes pool to not have enough HYDGs.
    function safeHydgTransfer(address _to, uint256 _amount) internal {
        uint256 hydgBal = hydg.balanceOf(address(this));
        if (_amount > hydgBal) {
            hydg.transfer(_to, hydgBal);
        } else {
            hydg.transfer(_to, _amount);
        }
    }

    // Update dev address by the previous dev.
    function dev(address _devaddr) public {
        require(msg.sender == devaddr, "dev: wut?");
        devaddr = _devaddr;
    }
}
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.accHydgPerShare).div(1e12).sub(user.rewardDebt);
    safeHydgTransfer(msg.sender, pending);
    user.amount = user.amount.sub(_amount);
    user.rewardDebt = user.amount.mul(pool.accHydgPerShare).div(1e12);
    pool.lpToken.safeTransfer(address(msg.sender), _amount);
    emit Withdraw(msg.sender, _pid, _amount);
}

// Withdraw LP tokens from MasterContract.