contract StabilizeStrategyBACMICArb is Ownable {
    using SafeMath for uint256;
    using SafeERC20 for IERC20;
    using Address for address;
    
    address public treasuryAddress; // Address of the treasury
    address public stakingAddress; // Address to the STBZ staking pool
    address public zsTokenAddress; // The address of the controlling zs-Token
    
    uint256 constant divisionFactor = 100000;
    uint256 public lastTradeTime;
    uint256 public maxPoolSize = 3000000e18; // The maximum amount of seigniorage tokens this strategy can hold, 3 mil by default
    uint256 public lastActionBalance = 0; // Balance before last deposit or withdraw
    uint256 public percentTradeTrigger = 10000; // 10% change in value will trigger a trade
    uint256 public percentSell = 10000; // 10% of the tokens are sold to the cheapest token
    uint256 public maxAmountSell = 100000; // The maximum amount of tokens that can be sold at once
    uint256 public percentDepositor = 50000; // 1000 = 1%, depositors earn 50% of all gains
    uint256 public percentExecutor = 20000; // 20000 = 20% of WETH goes to executor
    uint256 public percentStakers = 50000; // 50% of non-depositors WETH goes to stakers, can be changed
    uint256 public minTradeSplit = 1000; // If the balance is less than or equal to this, it trades the entire balance
    uint256 constant minGain = 1e16; // Minimum amount of gain (0.01 coin) before buying WETH and splitting it
    
    // Token information
    // BAC, MIC
    // BAC / DAI is most liquid on Uniswap
    // MIC / USDT is most liquid on Sushiswap
    
    // To get from BAC to MIC, route: BAC -> DAI (Uniswap) -> USDT (Curve 3pool) -> MIC (Sushiswap)
    // Opposite to go in reverse
    // To get to WETH from BAC, route: BAC -> DAI -> WETH (Uniswap)
    // To get to WETH from MIC, route: MIC -> USDT -> WETH (Sushiswap)
    struct TokenInfo {
        IERC20 token; // Reference of token
        uint256 decimals; // Decimals of token
    }
    
    TokenInfo[] private tokenList; // An array of tokens accepted as deposits

    // Strategy specific variables
    address constant curveAddress = address(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7); // Curve pool for 3pool
    address constant uniswapRouterAddress = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //Address of Uniswap
    address constant sushiswapRouterAddress = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // Sushiswap router
    address constant usdtAddress = address(0xdAC17F958D2ee523a2206206994597C13D831ec7);
    address constant wethAddress = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
    address constant daiAddress = address(0x6B175474E89094C44Da98b954EedeAC495271d0F);

    constructor(
        address _treasury,
        address _staking,
        address _zsToken
    ) public {
        treasuryAddress = _treasury;
        stakingAddress = _staking;
        zsTokenAddress = _zsToken;
        setupWithdrawTokens();
    }

    // Initialization functions
    
    function setupWithdrawTokens() internal {
        // Start with BAC
        IERC20 _token = IERC20(address(0x3449FC1Cd036255BA1EB19d65fF4BA2b8903A69a));
        tokenList.push(
            TokenInfo({
                token: _token,
                decimals: _token.decimals()
            })
        );
        
        // MIC
         _token = IERC20(address(0x368B3a58B5f49392e5C9E4C998cb0bB966752E51));
        tokenList.push(
            TokenInfo({
                token: _token,
                decimals: _token.decimals()
            })
        );
    }
    
    // Modifier
    modifier onlyZSToken() {
        require(zsTokenAddress == _msgSender(), "Call not sent from the zs-Token");
        _;
    }
    
    // Read functions
    
    function rewardTokensCount() external view returns (uint256) {
        return tokenList.length;
    }
    
    function rewardTokenAddress(uint256 _pos) external view returns (address) {
        require(_pos < tokenList.length,"No token at that position");
        return address(tokenList[_pos].token);
    }
    
    function balance() public view returns (uint256) {
        return getNormalizedTotalBalance(address(this));
    }
    
    function getNormalizedTotalBalance(address _address) public view returns (uint256) {
        uint256 _balance = 0;
        for(uint256 i = 0; i < tokenList.length; i++){
            uint256 _bal = tokenList[i].token.balanceOf(_address);
            _bal = _bal.mul(1e18).div(10**tokenList[i].decimals);
            _balance = _balance.add(_bal); // This has been normalized to 1e18 decimals
        }
        return _balance;
    }
    
    function withdrawTokenReserves() public view returns (address, uint256) {
        // This function will return the address and amount of the token with the highest balance
        uint256 length = tokenList.length;
        uint256 targetID = 0;
        uint256 targetNormBalance = 0;
        for(uint256 i = 0; i < length; i++){
            uint256 _normBal = tokenList[i].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i].decimals);
            if(_normBal > 0){
                if(targetNormBalance == 0 || _normBal >= targetNormBalance){
                    targetNormBalance = _normBal;
                    targetID = i;
                }
            }
        }
        if(targetNormBalance > 0){
            return (address(tokenList[targetID].token), tokenList[targetID].token.balanceOf(address(this)));
        }else{
            return (address(0), 0); // No balance
        }
    }
    
    // Write functions
    
    function enter() external onlyZSToken {
        deposit(false);
    }
    
    function exit() external onlyZSToken {
        // The ZS token vault is removing all tokens from this strategy
        withdraw(_msgSender(),1,1, false);
    }
    
    function deposit(bool nonContract) public onlyZSToken {
        // Only the ZS token can call the function
        
        // No trading is performed on deposit
        if(nonContract == true){ }
        lastActionBalance = balance();
        require(lastActionBalance <= maxPoolSize,"This strategy has reached its maximum balance");
    }
    
    function withdraw(address _depositor, uint256 _share, uint256 _total, bool nonContract) public onlyZSToken returns (uint256) {
        require(balance() > 0, "There are no tokens in this strategy");
        if(nonContract == true){
            if(_share > _total.mul(percentTradeTrigger).div(divisionFactor)){
                checkAndSwapTokens(_depositor);
            }
        }
        
        uint256 withdrawAmount = 0;
        uint256 _balance = balance();
        if(_share < _total){
            uint256 _myBalance = _balance.mul(_share).div(_total);
            withdrawPerBalance(_depositor, _myBalance, false); // This will withdraw based on token balance
            withdrawAmount = _myBalance;
        }else{
            // We are all shares, transfer all
            withdrawPerBalance(_depositor, _balance, true);
            withdrawAmount = _balance;
        }       
        lastActionBalance = balance();
        
        return withdrawAmount;
    }
    
    // This will withdraw the tokens from the contract based on their balance, from highest balance to lowest
    function withdrawPerBalance(address _receiver, uint256 _withdrawAmount, bool _takeAll) internal {
        uint256 length = tokenList.length;
        if(_takeAll == true){
            // Send the entire balance
            for(uint256 i = 0; i < length; i++){
                uint256 _bal = tokenList[i].token.balanceOf(address(this));
                if(_bal > 0){
                    tokenList[i].token.safeTransfer(_receiver, _bal);
                }
            }
            return;
        }
        bool[4] memory done;
        uint256 targetID = 0;
        uint256 targetNormBalance = 0;
        for(uint256 i = 0; i < length; i++){
            
            targetNormBalance = 0; // Reset the target balance
            // Find the highest balanced token to withdraw
            for(uint256 i2 = 0; i2 < length; i2++){
                if(done[i2] == false){
                    uint256 _normBal = tokenList[i2].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i2].decimals);
                    if(targetNormBalance == 0 || _normBal >= targetNormBalance){
                        targetNormBalance = _normBal;
                        targetID = i2;
                    }
                }
            }
            done[targetID] = true;
            
            // Determine the balance left
            uint256 _normalizedBalance = tokenList[targetID].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[targetID].decimals);
            if(_normalizedBalance <= _withdrawAmount){
                // Withdraw the entire balance of this token
                if(_normalizedBalance > 0){
                    _withdrawAmount = _withdrawAmount.sub(_normalizedBalance);
                    tokenList[targetID].token.safeTransfer(_receiver, tokenList[targetID].token.balanceOf(address(this)));                    
                }
            }else{
                // Withdraw a partial amount of this token
                if(_withdrawAmount > 0){
                    // Convert the withdraw amount to the token's decimal amount
                    uint256 _balance = _withdrawAmount.mul(10**tokenList[targetID].decimals).div(1e18);
                    _withdrawAmount = 0;
                    tokenList[targetID].token.safeTransfer(_receiver, _balance);
                }
                break; // Nothing more to withdraw
            }
        }
    }
    
    function simulateExchange(address _inputToken, address _outputToken, uint256 _amount) internal view returns (uint256) {
        // This will follow the route from token 1 to token 2 and simulate an output per the input
        address bac = address(tokenList[0].token);
        address mic = address(tokenList[1].token);
        if(_inputToken == bac && _outputToken == mic){
            // BAC to MIC
            TradeRouter router = TradeRouter(uniswapRouterAddress);
            address[] memory path = new address[](2);
            path[0] = bac;
            path[1] = daiAddress; // BAI / DAI is most liquid pair
            uint256[] memory estimates = router.getAmountsOut(_amount, path);
            _amount = estimates[estimates.length - 1]; // This is the amount of DAI returned
            // Now run through Curve
            CurvePool pool = CurvePool(curveAddress);
            _amount = pool.get_dy(0, 2, _amount); // DAI -> USDT, amount is now USDT
            // Finally run through Sushiswap
            router = TradeRouter(sushiswapRouterAddress);
            path = new address[](2);
            path[0] = usdtAddress;
            path[1] = mic; // MIC / USDT is the most liquid pair
            estimates = router.getAmountsOut(_amount, path);
            _amount = estimates[estimates.length - 1]; // This is the amount of MIC returned
            return _amount;
        }else if(_inputToken == mic && _outputToken == bac){
            // MIC to BAC
            TradeRouter router = TradeRouter(sushiswapRouterAddress);
            address[] memory path = new address[](2);
            path[0] = mic;
            path[1] = usdtAddress; // MIC / USDT is most liquid pair
            uint256[] memory estimates = router.getAmountsOut(_amount, path);
            _amount = estimates[estimates.length - 1]; // This is the amount of USDT returned
            // Now run through Curve
            CurvePool pool = CurvePool(curveAddress);
            _amount = pool.get_dy(2, 0, _amount); // USDT -> DAI, amount is now DAI
            // Finally run through Uniswap
            router = TradeRouter(uniswapRouterAddress);
            path = new address[](2);
            path[0] = daiAddress;
            path[1] = bac; // BAC / DAI is the most liquid pair
            estimates = router.getAmountsOut(_amount, path);
            _amount = estimates[estimates.length - 1]; // This is the amount of BAC returned
            return _amount;            
        }else if(_inputToken == bac && _outputToken == wethAddress){
            // BAC to WETH, simple
            TradeRouter router = TradeRouter(uniswapRouterAddress);
            address[] memory path = new address[](3);
            path[0] = bac;
            path[1] = daiAddress; // BAI / DAI is most liquid pair
            path[2] = wethAddress;
            uint256[] memory estimates = router.getAmountsOut(_amount, path);
            _amount = estimates[estimates.length - 1]; // This is the amount of WETH returned
            return _amount;
        }else if(_inputToken == mic && _outputToken == wethAddress){
            // MIC to WETH, simple
            TradeRouter router = TradeRouter(sushiswapRouterAddress);
            address[] memory path = new address[](3);
            path[0] = mic;
            path[1] = usdtAddress; // MIC / USDT is most liquid pair
            path[2] = wethAddress;
            uint256[] memory estimates = router.getAmountsOut(_amount, path);
            _amount = estimates[estimates.length - 1]; // This is the amount of WETH returned    
            return _amount;
        }
        return 0;
    }
    
    function getCheaperToken() internal view returns (uint256) {
        // This will give us the ID of the cheapest token
        // We will estimate the return for trading 1000 BAC
        // The higher the return, the lower the price of the other token
        uint256 targetID = 0; // Our target ID is BAC first
        uint256 bacAmount = uint256(1000).mul(10**tokenList[0].decimals);
        uint256 highAmount = bacAmount;
        for(uint256 i = 1; i < tokenList.length; i++){
            // Normalize the estimate into BAC decimals
            uint256 estimate = simulateExchange(address(tokenList[0].token),address(tokenList[i].token),bacAmount);
            estimate = estimate.mul(10**tokenList[0].decimals).div(10**tokenList[i].decimals);
            if(estimate > highAmount){
                // This token is worth less than the BAC
                highAmount = estimate;
                targetID = i;
            }
        }
        return targetID;
    }
    
    function exchange(address _inputToken, address _outputToken, uint256 _amount) internal {
        // This will follow the route from token 1 to token 2 and do a real exchange
        address bac = address(tokenList[0].token);
        address mic = address(tokenList[1].token);
        IERC20 bacToken = IERC20(bac);
        IERC20 micToken = IERC20(mic);
        if(_inputToken == bac && _outputToken == mic){
            // BAC to MIC
            TradeRouter router = TradeRouter(uniswapRouterAddress);
            address[] memory path = new address[](2);
            path[0] = bac;
            path[1] = daiAddress; // BAI / DAI is most liquid pair
            
            bacToken.safeApprove(uniswapRouterAddress, 0);
            bacToken.safeApprove(uniswapRouterAddress, _amount);
            router.swapExactTokensForTokens(_amount, 1, path, address(this), now.add(60)); // Get DAI from BAC
            IERC20 daiToken = IERC20(daiAddress);
            _amount = daiToken.balanceOf(address(this)); // Since DAI is temp, get the entire balance

            // Now run through Curve
            CurvePool pool = CurvePool(curveAddress);
            daiToken.safeApprove(curveAddress, 0);
            daiToken.safeApprove(curveAddress, _amount);
            pool.exchange(0, 2, _amount, 1); // Get USDT from DAI
            IERC20 usdtToken = IERC20(usdtAddress);
            _amount = usdtToken.balanceOf(address(this)); // Since USDT is temp, get the entire balance
            
            // Finally run through Sushiswap
            router = TradeRouter(sushiswapRouterAddress);
            path = new address[](2);
            path[0] = usdtAddress;
            path[1] = mic; // MIC / USDT is the most liquid pair
            
            usdtToken.safeApprove(sushiswapRouterAddress, 0);
            usdtToken.safeApprove(sushiswapRouterAddress, _amount);
            router.swapExactTokensForTokens(_amount, 1, path, address(this), now.add(60)); // Get MIC from USDT
        }else if(_inputToken == mic && _outputToken == bac){
            // MIC to BAC
            TradeRouter router = TradeRouter(sushiswapRouterAddress);
            address[] memory path = new address[](2);
            path[0] = mic;
            path[1] = usdtAddress; // MIC / USDT is most liquid pair
            
            micToken.safeApprove(sushiswapRouterAddress, 0);
            micToken.safeApprove(sushiswapRouterAddress, _amount);
            router.swapExactTokensForTokens(_amount, 1, path, address(this), now.add(60)); // Get USDT from MIC
            IERC20 usdtToken = IERC20(usdtAddress);
            _amount = usdtToken.balanceOf(address(this)); // Since USDT is temp, get the entire balance

            // Now run through Curve
            CurvePool pool = CurvePool(curveAddress);
            usdtToken.safeApprove(curveAddress, 0);
            usdtToken.safeApprove(curveAddress, _amount);
            pool.exchange(2, 0, _amount, 1); // Get DAI from USDT
            IERC20 daiToken = IERC20(daiAddress);
            _amount = daiToken.balanceOf(address(this)); // Since DAI is temp, get the entire balance
            
            // Finally run through Uniswap
            router = TradeRouter(uniswapRouterAddress);
            path = new address[](2);
            path[0] = daiAddress;
            path[1] = bac; // BAC / DAI is the most liquid pair
            
            daiToken.safeApprove(uniswapRouterAddress, 0);
            daiToken.safeApprove(uniswapRouterAddress, _amount);
            router.swapExactTokensForTokens(_amount, 1, path, address(this), now.add(60)); // Get BAC from DAI           
        }else if(_inputToken == bac && _outputToken == wethAddress){
            // BAC to WETH, simple
            TradeRouter router = TradeRouter(uniswapRouterAddress);
            address[] memory path = new address[](3);
            path[0] = bac;
            path[1] = daiAddress; // BAI / DAI is most liquid pair
            path[2] = wethAddress;
            
            bacToken.safeApprove(uniswapRouterAddress, 0);
            bacToken.safeApprove(uniswapRouterAddress, _amount);
            router.swapExactTokensForTokens(_amount, 1, path, address(this), now.add(60)); // Get WETH from BAC
        }else if(_inputToken == mic && _outputToken == wethAddress){
            // MIC to WETH, simple
            TradeRouter router = TradeRouter(sushiswapRouterAddress);
            address[] memory path = new address[](3);
            path[0] = mic;
            path[1] = usdtAddress; // MIC / USDT is most liquid pair
            path[2] = wethAddress;
            
            micToken.safeApprove(sushiswapRouterAddress, 0);
            micToken.safeApprove(sushiswapRouterAddress, _amount);
            router.swapExactTokensForTokens(_amount, 1, path, address(this), now.add(60)); // Get USDT from MIC
        }
    }
    
    function checkAndSwapTokens(address _executor) internal {
        lastTradeTime = now;

        // Now find our target token to sell into
        uint256 targetID = getCheaperToken();
        uint256 length = tokenList.length;

        // Now sell all the other tokens into this token
        uint256 _totalBalance = balance(); // Get the token balance at this contract, should increase
        bool _expectIncrease = false;
        for(uint256 i = 0; i < length; i++){
            if(i != targetID){
                uint256 localTarget = targetID;
                uint256 sellBalance = 0;
                uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[i].decimals);
                uint256 _maxTradeTarget = maxAmountSell.mul(10**tokenList[i].decimals); // Determine the maximum amount of tokens to sell at once
                if(tokenList[i].token.balanceOf(address(this)) <= _minTradeTarget){
                    // If balance is too small,sell all tokens at once
                    sellBalance = tokenList[i].token.balanceOf(address(this));
                }else{
                    sellBalance = tokenList[i].token.balanceOf(address(this)).mul(percentSell).div(divisionFactor);
                }
                if(sellBalance > _maxTradeTarget){
                    // If greater than the maximum trade allowed, match it
                    sellBalance = _maxTradeTarget;
                }
                uint256 minReceiveBalance = sellBalance.mul(10**tokenList[localTarget].decimals).div(10**tokenList[i].decimals); // Change to match decimals of destination
                if(sellBalance > 0){
                    uint256 estimate = simulateExchange(address(tokenList[i].token), address(tokenList[localTarget].token), sellBalance);
                    if(estimate > minReceiveBalance){
                        _expectIncrease = true;
                        // We are getting a greater number of tokens, complete the exchange
                        exchange(address(tokenList[i].token), address(tokenList[localTarget].token), sellBalance);
                    }                        
                }
            }
        }
        uint256 _newBalance = balance();
        if(_expectIncrease == true){
            // There may be rare scenarios where we don't gain any by calling this function
            require(_newBalance > _totalBalance, "Failed to gain in balance from selling tokens");
        }
        uint256 gain = _newBalance.sub(_totalBalance);
        if(gain >= minGain){
            // Minimum gain required to buy WETH is about 0.01 tokens
            
            // Buy WETH from Uniswap with tokens
            uint256 sellBalance = gain.mul(10**tokenList[targetID].decimals).div(1e18); // Convert to target decimals
            uint256 holdBalance = sellBalance.mul(percentDepositor).div(divisionFactor);
            sellBalance = sellBalance.sub(holdBalance); // We will buy WETH with this amount
            if(sellBalance <= tokenList[targetID].token.balanceOf(address(this))){
                IERC20 weth = IERC20(wethAddress);
                
                // Perform swap and sell some of our gained token for WETH
                exchange(address(tokenList[targetID].token), address(wethAddress), sellBalance);

                uint256 _wethBalance = weth.balanceOf(address(this));
                if(_wethBalance > 0){
                    // Split the amount sent to the treasury, stakers and executor if one exists
                    if(_executor != address(0)){
                        // First send the executor a percentage of the profit
                        uint256 executorAmount = _wethBalance.mul(percentExecutor).div(divisionFactor);
                        if(executorAmount > 0){
                            weth.safeTransfer(_executor, executorAmount);
                            _wethBalance = weth.balanceOf(address(this)); // Recalculate WETH in contract                          
                        }
                    }
                    uint256 stakersAmount = _wethBalance.mul(percentStakers).div(divisionFactor);
                    uint256 treasuryAmount = _wethBalance.sub(stakersAmount);
                    if(treasuryAmount > 0){
                        weth.safeTransfer(treasuryAddress, treasuryAmount);
                    }
                    if(stakersAmount > 0){
                        if(stakingAddress != address(0)){
                            weth.safeTransfer(stakingAddress, stakersAmount);
                            StabilizeStakingPool(stakingAddress).notifyRewardAmount(stakersAmount);                                
                        }else{
                            // No staking pool selected, just send to the treasury
                            weth.safeTransfer(treasuryAddress, stakersAmount);
                        }
                    }
                }
            }
        }
    }
    
    function expectedProfit(bool inWETHForExecutor) external view returns (uint256) {
        // This view will return the amount of gain a forced swap will make on next call
        // And alternatively it can return expected WETH profit from trade for executor
        
        // Now find our target token to sell into
        uint256 targetID = getCheaperToken();
        uint256 length = tokenList.length;

        uint256 _normalizedGain = 0;
        for(uint256 i = 0; i < length; i++){
            if(i != targetID){

                uint256 localTarget = targetID;
                uint256 sellBalance = 0;
                uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[i].decimals);
                uint256 _maxTradeTarget = maxAmountSell.mul(10**tokenList[i].decimals); // Determine the maximum amount of tokens to sell at once
                if(tokenList[i].token.balanceOf(address(this)) <= _minTradeTarget){
                    // If balance is too small,sell all tokens at once
                    sellBalance = tokenList[i].token.balanceOf(address(this));
                }else{
                    sellBalance = tokenList[i].token.balanceOf(address(this)).mul(percentSell).div(divisionFactor);
                }
                if(sellBalance > _maxTradeTarget){
                    // If greater than the maximum trade allowed, match it
                    sellBalance = _maxTradeTarget;
                }
                uint256 minReceiveBalance = sellBalance.mul(10**tokenList[localTarget].decimals).div(10**tokenList[i].decimals); // Change to match decimals of destination
                if(sellBalance > 0){
                    uint256 estimate = simulateExchange(address(tokenList[i].token), address(tokenList[localTarget].token), sellBalance);
                    if(estimate > minReceiveBalance){
                        uint256 _gain = estimate.sub(minReceiveBalance).mul(1e18).div(10**tokenList[localTarget].decimals); // Normalized gain
                        _normalizedGain = _normalizedGain.add(_gain);
                    }                        
                }
            }
        }
        if(inWETHForExecutor == false){
            return _normalizedGain;
        }else{
            if(_normalizedGain == 0){
                return 0;
            }
            // Calculate how much WETH the executor would make as profit
            uint256 sellBalance = _normalizedGain.mul(10**tokenList[targetID].decimals).div(1e18); // Convert to target decimals
            uint256 holdBalance = sellBalance.mul(percentDepositor).div(divisionFactor);
            sellBalance = sellBalance.sub(holdBalance); // We will buy WETH with this amount
            // Estimate output
            uint256 estimate = simulateExchange(address(tokenList[targetID].token), wethAddress, sellBalance);
            return estimate.mul(percentExecutor).div(divisionFactor); // Executor amount
        }
           
    }
    
    function executorSwapTokens(address _executor, uint256 _minSecSinceLastTrade) external {
        // Function designed to promote trading with incentive. Users get 20% of WETH from profitable trades
        // Only 1 executor per block allowed
        require(now.sub(lastTradeTime) > _minSecSinceLastTrade, "The last trade was too recent");
        require(_msgSender() == tx.origin, "Contracts cannot interact with this function");
        checkAndSwapTokens(_executor);
    }
    
    // Governance functions
    function governanceSwapTokens() external onlyGovernance {
        // This is function that force trade tokens at anytime. It can only be called by governance
        checkAndSwapTokens(governance());
    }
    
    // Timelock variables
    
    uint256 private _timelockStart; // The start of the timelock to change governance variables
    uint256 private _timelockType; // The function that needs to be changed
    uint256 constant _timelockDuration = 86400; // Timelock is 24 hours
    
    // Reusable timelock variables
    address private _timelock_address;
    uint256 private _timelock_data_1;
    uint256 private _timelock_data_2;
    
    modifier timelockConditionsMet(uint256 _type) {
        require(_timelockType == _type, "Timelock not acquired for this function");
        _timelockType = 0; // Reset the type once the timelock is used
        if(balance() > 0){ // Timelock only applies when balance exists
            require(now >= _timelockStart + _timelockDuration, "Timelock time not met");
        }
        _;
    }
    
    // Change the owner of the token contract
    // --------------------
    function startGovernanceChange(address _address) external onlyGovernance {
        _timelockStart = now;
        _timelockType = 1;
        _timelock_address = _address;       
    }
    
    function finishGovernanceChange() external onlyGovernance timelockConditionsMet(1) {
        transferGovernance(_timelock_address);
    }
    // --------------------
    
    // Change the treasury address
    // --------------------
    function startChangeTreasury(address _address) external onlyGovernance {
        _timelockStart = now;
        _timelockType = 2;
        _timelock_address = _address;
    }
    
    function finishChangeTreasury() external onlyGovernance timelockConditionsMet(2) {
        treasuryAddress = _timelock_address;
    }
    // --------------------
    
    // Change the percent going to depositors for WETH
    // --------------------
    function startChangeDepositorPercent(uint256 _percent) external onlyGovernance {
        require(_percent <= 100000,"Percent cannot be greater than 100%");
        _timelockStart = now;
        _timelockType = 3;
        _timelock_data_1 = _percent;
    }
    
    function finishChangeDepositorPercent() external onlyGovernance timelockConditionsMet(3) {
        percentDepositor = _timelock_data_1;
    }
    // --------------------
    
    // Change the staking address
    // --------------------
    function startChangeStakingPool(address _address) external onlyGovernance {
        _timelockStart = now;
        _timelockType = 4;
        _timelock_address = _address;
    }
    
    function finishChangeStakingPool() external onlyGovernance timelockConditionsMet(4) {
        stakingAddress = _timelock_address;
    }
    // --------------------
    
    // Change the zsToken address
    // --------------------
    function startChangeZSToken(address _address) external onlyGovernance {
        _timelockStart = now;
        _timelockType = 5;
        _timelock_address = _address;
    }
    
    function finishChangeZSToken() external onlyGovernance timelockConditionsMet(5) {
        zsTokenAddress = _timelock_address;
    }
    // --------------------
    
    // Change the percent going to stakers for WETH
    // --------------------
    function startChangeStakersPercent(uint256 _percent) external onlyGovernance {
        require(_percent <= 100000,"Percent cannot be greater than 100%");
        _timelockStart = now;
        _timelockType = 6;
        _timelock_data_1 = _percent;
    }
    
    function finishChangeStakersPercent() external onlyGovernance timelockConditionsMet(6) {
        percentStakers = _timelock_data_1;
    }
    // --------------------
    
    // Change the percent sold and max sellable of each token
    // --------------------
    function startChangePercentAndAmountSold(uint256 _percent, uint256 _maxSell) external onlyGovernance {
        require(_percent <= 100000,"Percent cannot be greater than 100%");
        _timelockStart = now;
        _timelockType = 7;
        _timelock_data_1 = _percent;
        _timelock_data_2 = _maxSell;
    }
    
    function finishChangePercentAndAmountSold() external onlyGovernance timelockConditionsMet(7) {
        percentSell = _timelock_data_1;
        maxAmountSell = _timelock_data_2;
    }
    // --------------------
    
    // Change percent of balance to trigger trade
    // --------------------
    function startChangePercentTradeTrigger(uint256 _percent) external onlyGovernance {
        require(_percent <= 100000,"Percent cannot be greater than 100%");
        _timelockStart = now;
        _timelockType = 8;
        _timelock_data_1 = _percent;
    }
    
    function finishChangePercentTradeTrigger() external onlyGovernance timelockConditionsMet(8) {
        percentTradeTrigger = _timelock_data_1;
    }
    // --------------------
    
    // Change the minimum trade size before splitting, otherwise sells entire amount
    // --------------------
    function startChangeMinTradeSplit(uint256 _split) external onlyGovernance {
        _timelockStart = now;
        _timelockType = 9;
        _timelock_data_1 = _split;
    }
    
    function finishChangeMinTradeSplit() external onlyGovernance timelockConditionsMet(9) {
        minTradeSplit = _timelock_data_1;
    }
    // --------------------
    
    // Change the maximum amount of tokens allowed in this strategy
    // --------------------
    function startChangeMaximumPoolSize(uint256 _amount) external onlyGovernance {
        _timelockStart = now;
        _timelockType = 10;
        _timelock_data_1 = _amount;
    }
    
    function finishChangeMaximumPoolSize() external onlyGovernance timelockConditionsMet(10) {
        maxPoolSize = _timelock_data_1;
    }
    // --------------------
    
    // Change the percent that goes to the executor for non-depositors profit
    // --------------------
    function startChangePercentExecutor(uint256 _percent) external onlyGovernance {
        require(_percent <= 100000,"Percent cannot be greater than 100%");
        _timelockStart = now;
        _timelockType = 11;
        _timelock_data_1 = _percent;
    }
    
    function finishChangePercentExecutor() external onlyGovernance timelockConditionsMet(11) {
        percentExecutor = _timelock_data_1;
    }
    // --------------------
}
function startChangeMaximumPoolSize(uint256 _amount) external onlyGovernance {
        _timelockStart = now;
        _timelockType = 10;
        _timelock_data_1 = _amount;
    }
// --------------------
// Change the maximum amount of tokens allowed in this strategy
// --------------------