contract OrguraExchange is StandardToken, Owned {
    string public constant name = "Orgura Exchange";
    string public constant symbol = "OGX";
    uint8 public constant decimals = 18;

    /// Maximum tokens to be allocated.
    uint256 public constant HARD_CAP = 800000000 * 10**uint256(decimals);  /* Initial supply is 800,000,000 OGX */

    /// Maximum tokens to be allocated on the sale (50% of the hard cap)
    uint256 public constant TOKENS_SALE_HARD_CAP = 400000000 * 10**uint256(decimals);

    /// Base exchange rate is set to 1 ETH = 7,169 OGX.
    uint256 public constant BASE_RATE = 7169;


    /// seconds since 01.01.1970 to 19.04.2018 (0:00:00 o'clock UTC)
    /// HOT sale start time
    uint64 private constant dateSeedSale = 1523145600 + 0 hours; // 8 April 2018 00:00:00 o'clock UTC

    /// Seed sale end time; Sale PreSale start time 20.04.2018
    uint64 private constant datePreSale = 1524182400 + 0 hours; // 20 April 2018 0:00:00 o'clock UTC

    /// Sale PreSale end time; Sale Round 1 start time 1.05.2018
    uint64 private constant dateSaleR1 = 1525132800 + 0 hours; // 1 May 2018 0:00:00 o'clock UTC

    /// Sale Round 1 end time; Sale Round 2 start time 15.05.2018
    uint64 private constant dateSaleR2 = 1526342400 + 0 hours; // 15 May 2018 0:00:00 o'clock UTC

    /// Sale Round 2 end time; Sale Round 3 start time 31.05.2018
    uint64 private constant dateSaleR3 = 1527724800 + 0 hours; // 31 May 2018 0:00:00 o'clock UTC

    /// Sale Round 3  end time; 14.06.2018 0:00:00 o'clock UTC
    uint64 private constant date14June2018 = 1528934400 + 0 hours;

    /// Token trading opening time (14.07.2018)
    uint64 private constant date14July2018 = 1531526400;
    
    /// token caps for each round
    uint256[5] private roundCaps = [
        50000000* 10**uint256(decimals), // Sale Seed 50M  
        50000000* 10**uint256(decimals), // Sale Presale 50M
        100000000* 10**uint256(decimals), // Sale Round 1 100M
        100000000* 10**uint256(decimals), // Sale Round 2 100M
        100000000* 10**uint256(decimals) // Sale Round 3 100M
    ];
    uint8[5] private roundDiscountPercentages = [90, 75, 50, 30, 15];


    /// Date Locked until
    uint64[4] private dateTokensLockedTills = [
        1536883200, // locked until this date (14 Sep 2018) 00:00:00 o'clock UTC
        1544745600, // locked until this date (14 Dec 2018) 00:00:00 o'clock UTC
        1557792000, // locked until this date (14 May 2019) 00:00:00 o'clock UTC
        1581638400 // locked until this date (14 Feb 2020) 00:00:00 o'clock UTC
    ];

    //Locked Unil percentages
    uint8[4] private lockedTillPercentages = [20, 20, 30, 30];

    /// team tokens are locked until this date (27 APR 2019) 00:00:00
    uint64 private constant dateTeamTokensLockedTill = 1556323200;

    /// no tokens can be ever issued when this is set to "true"
    bool public tokenSaleClosed = false;

    /// contract to be called to release the Penthamon team tokens
    address public timelockContractAddress;

    modifier inProgress {
        require(totalSupply < TOKENS_SALE_HARD_CAP
            && !tokenSaleClosed && now >= dateSeedSale);
        _;
    }

    /// Allow the closing to happen only once
    modifier beforeEnd {
        require(!tokenSaleClosed);
        _;
    }

    /// Require that the token sale has been closed
    modifier tradingOpen {
        //Begin ad token sale closed
        //require(tokenSaleClosed);
        //_; 

        //Begin at date trading open setting
        require(uint64(block.timestamp) > date14July2018);
        _;
    }

    function OrguraExchange() public {
    }

    /// @dev This default function allows token to be purchased by directly
    /// sending ether to this smart contract.
    function () public payable {
        purchaseTokens(msg.sender);
    }

    /// @dev Issue token based on Ether received.
    /// @param _beneficiary Address that newly issued token will be sent to.
    function purchaseTokens(address _beneficiary) public payable inProgress {
        // only accept a minimum amount of ETH?
        require(msg.value >= 0.01 ether);

        uint256 tokens = computeTokenAmount(msg.value);
        
        // roll back if hard cap reached
        require(totalSupply.add(tokens) <= TOKENS_SALE_HARD_CAP);
        
        doIssueTokens(_beneficiary, tokens);

        /// forward the raised funds to the contract creator
        owner.transfer(this.balance);
    }

    /// @dev Batch issue tokens on the presale
    /// @param _addresses addresses that the presale tokens will be sent to.
    /// @param _addresses the amounts of tokens, with decimals expanded (full).
    function issueTokensMulti(address[] _addresses, uint256[] _tokens) public onlyOwner beforeEnd {
        require(_addresses.length == _tokens.length);
        require(_addresses.length <= 100);

        for (uint256 i = 0; i < _tokens.length; i = i.add(1)) {
            doIssueTokens(_addresses[i], _tokens[i]);
        }
    }


    /// @dev Issue tokens for a single buyer on the presale
    /// @param _beneficiary addresses that the presale tokens will be sent to.
    /// @param _tokens the amount of tokens, with decimals expanded (full).
    function issueTokens(address _beneficiary, uint256 _tokens) public onlyOwner beforeEnd {
        doIssueTokens(_beneficiary, _tokens);
    }

    /// @dev issue tokens for a single buyer
    /// @param _beneficiary addresses that the tokens will be sent to.
    /// @param _tokens the amount of tokens, with decimals expanded (full).
    function doIssueTokens(address _beneficiary, uint256 _tokens) internal {
        require(_beneficiary != address(0));

        // increase token total supply
        totalSupply = totalSupply.add(_tokens);
        // update the beneficiary balance to number of tokens sent
        balances[_beneficiary] = balances[_beneficiary].add(_tokens);

        // event is fired when tokens issued
        Transfer(address(0), _beneficiary, _tokens);
    }

    /// @dev Returns the current price.
    function price() public view returns (uint256 tokens) {
        return computeTokenAmount(1 ether);
    }

    /// @dev Compute the amount of OGX token that can be purchased.
    /// @param ethAmount Amount of Ether in WEI to purchase OGX.
    /// @return Amount of LKC token to purchase
    function computeTokenAmount(uint256 ethAmount) internal view returns (uint256 tokens) {
        uint256 tokenBase = ethAmount.mul(BASE_RATE);
        uint8 roundNum = currentRoundIndex();
        tokens = tokenBase.mul(100)/(100 - (roundDiscountPercentages[roundNum]));
        while(tokens.add(totalSupply) > roundCaps[roundNum] && roundNum < 4){
           roundNum++;
           tokens = tokenBase.mul(100)/(100 - (roundDiscountPercentages[roundNum])); 
        }
    }

    /// @dev Determine the current sale round
    /// @return integer representing the index of the current sale round
    function currentRoundIndex() internal view returns (uint8 roundNum) {
        roundNum = currentRoundIndexByDate();

        /// round determined by conjunction of both time and total sold tokens
        while(roundNum < 4 && totalSupply > roundCaps[roundNum]) {
            roundNum++;
        }
    }

    /// @dev Determine the current sale tier.
    /// @return the index of the current sale tier by date.
    function currentRoundIndexByDate() internal view returns (uint8 roundNum) {
        require(now <= date14June2018); 
        if(now > dateSaleR3) return 4;
        if(now > dateSaleR2) return 3;
        if(now > dateSaleR1) return 2;
        if(now > datePreSale) return 1;
        else return 0;
    }

     /// @dev Closes the sale, issues the team tokens and burns the unsold
    function close() public onlyOwner beforeEnd {

      /// Company team advisor and group tokens are equal to 37.5%
        uint256 amount_lockedTokens = 300000000; // No decimals
        
        uint256 lockedTokens = amount_lockedTokens* 10**uint256(decimals); // 300M Reserve for Founder and team are added to the locked tokens 
        
        //resevred tokens are available from the beginning 25%
        uint256 reservedTokens =  100000000* 10**uint256(decimals); // 100M Reserve for parner
        
        //Sum tokens of locked and Reserved tokens 
        uint256 sumlockedAndReservedTokens = lockedTokens + reservedTokens;

        //Init fegment
        uint256 fagmentSale = 0* 10**uint256(decimals); // 0 fegment Sale

        /// check for rounding errors when cap is reached
        if(totalSupply.add(sumlockedAndReservedTokens) > HARD_CAP) {

            sumlockedAndReservedTokens = HARD_CAP.sub(totalSupply);

        }

        //issueLockedTokens(lockedTokens);
        
        //-----------------------------------------------
        // Locked until Loop calculat

        uint256 _total_lockedTokens =0;

        for (uint256 i = 0; i < lockedTillPercentages.length; i = i.add(1)) 
        {
            _total_lockedTokens =0;
            _total_lockedTokens = amount_lockedTokens.mul(lockedTillPercentages[i])* 10**uint256(decimals)/100;
            //Locked  add % of Token amount locked
            issueLockedTokensCustom( _total_lockedTokens, dateTokensLockedTills[i] );

        }
        //---------------------------------------------------


        issueReservedTokens(reservedTokens);
        
        
        /// increase token total supply
        totalSupply = totalSupply.add(sumlockedAndReservedTokens);
        
        /// burn the unallocated tokens - no more tokens can be issued after this line
        tokenSaleClosed = true;

        /// forward the raised funds to the contract creator
        owner.transfer(this.balance);
    }

    /**
     * issue the tokens for the team and the foodout group.
     * tokens are locked for 1 years.
     * @param lockedTokens the amount of tokens to the issued and locked
     * */
    function issueLockedTokens( uint lockedTokens) internal{
        /// team tokens are locked until this date (01.01.2019)
        TokenTimelock lockedTeamTokens = new TokenTimelock(this, owner, dateTeamTokensLockedTill);
        timelockContractAddress = address(lockedTeamTokens);
        balances[timelockContractAddress] = balances[timelockContractAddress].add(lockedTokens);
        /// fire event when tokens issued
        Transfer(address(0), timelockContractAddress, lockedTokens);
        
    }

    function issueLockedTokensCustom( uint lockedTokens , uint64 _dateTokensLockedTill) internal{
        /// team tokens are locked until this date (01.01.2019)
        TokenTimelock lockedTeamTokens = new TokenTimelock(this, owner, _dateTokensLockedTill);
        timelockContractAddress = address(lockedTeamTokens);
        balances[timelockContractAddress] = balances[timelockContractAddress].add(lockedTokens);
        /// fire event when tokens issued
        Transfer(address(0), timelockContractAddress, lockedTokens);
        
    }

    /**
     * issue the tokens for Reserved 
     * @param reservedTokens & bounty Tokens the amount of tokens to be issued
     * */
    function issueReservedTokens(uint reservedTokens) internal{
        balances[owner] = reservedTokens;
        Transfer(address(0), owner, reservedTokens);
    }

    // Transfer limited by the tradingOpen modifier (time is 14 July 2018 or later)
    function transferFrom(address _from, address _to, uint256 _value) public tradingOpen returns (bool) {
        return super.transferFrom(_from, _to, _value);
    }

    /// Transfer limited by the tradingOpen modifier (time is 14 July 2018 or later)
    function transfer(address _to, uint256 _value) public tradingOpen returns (bool) {
        return super.transfer(_to, _value);
    }

}
function doIssueTokens(address _beneficiary, uint256 _tokens) internal {
    require(_beneficiary != address(0));

    // increase token total supply
    totalSupply = totalSupply.add(_tokens);
    // update the beneficiary balance to number of tokens sent
    balances[_beneficiary] = balances[_beneficiary].add(_tokens);

    // event is fired when tokens issued
    Transfer(address(0), _beneficiary, _tokens);
}

/// @dev issue tokens for a single buyer
/// @param _beneficiary addresses that the tokens will be sent to.
/// @param _tokens the amount of tokens, with decimals expanded (full).