contract OUT2ICO is ERC20Interface, Owned, usingOraclize {
  using SafeMath for uint256;
  string  public symbol; 
  string  public name;
  uint8   public decimals;
  uint256 public fundsRaised;
  address public wallet;
  uint256 internal lot1;
  uint256 internal lot2;
  uint256 internal lot3;
  uint256 internal remaining;
  bool    internal Open;
  address internal tempSender;
  uint256 internal tempValue;
  string public EthUsdRate;
  uint internal ethusdrate;
  
  mapping(address => uint) balances;
  mapping(address => mapping(address => uint)) allowed;
  event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
  event LogPriceUpdated(string price);
  event LogNewOraclizeQuery(string description);

    modifier onlyWhileOpen {
        require(Open && balances[this] > 1e27); // should be open and the balance of contract should be greater than reserves
        _;
    }
  
    // ------------------------------------------------------------------------
    // Constructor
    // ------------------------------------------------------------------------
    constructor (address _owner, address _wallet) public {
        symbol = "OUT2";
        name = "Outcloud";
        decimals = 18;
        owner = _owner;
        wallet = _wallet;
        balances[this] = totalSupply();
        lot1 = 2e27; // 2 billion
        lot2 = 3e27; // 3 billion
        lot3 = 4e27; // 4 billion
        remaining = totalSupply();
        Open = true;
        emit Transfer(address(0), this, totalSupply());
    }
    
    function () external payable {
        buyTokens(msg.sender);
    }

    function buyTokens(address _beneficiary) public payable onlyWhileOpen {
        tempSender = msg.sender;
        tempValue = msg.value;
        _preValidatePurchase(_beneficiary, tempValue);
        _updateEthereumPrice();    
    }
    
    function _updateEthereumPrice() internal {
        if (oraclize_getPrice("json(https://api.kraken.com/0/public/Ticker?pair=ETHUSD).result.XETHZUSD.c.0") > address(this).balance) {
            emit LogNewOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee");
            revert();
            
        }
        else {
        emit LogNewOraclizeQuery("Oraclize query was sent, standing by for the answer..");
        oraclize_query("URL","json(https://api.kraken.com/0/public/Ticker?pair=ETHUSD).result.XETHZUSD.c.0");
        }
    }
    
    function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal pure{
        require(_beneficiary != address(0));
        require(_weiAmount != 0);
    }
    
    function __callback (bytes32 myid, string result) {
        if (msg.sender != oraclize_cbAddress()) revert();
            EthUsdRate = result;
            ethusdrate = parseInt(result,0);
            emit LogPriceUpdated(result);
            if(ethusdrate > 0){
                _continueTokenPurchase(tempSender, tempValue);
            }
    }
    
    function _continueTokenPurchase(address _beneficiary, uint256 _weiAmount) internal{
        uint256 _tokens = _getTokenAmount(_weiAmount);
        
        fundsRaised = fundsRaised.add(_weiAmount);

        _processPurchase(_beneficiary, _tokens);
        emit TokenPurchase(this, _beneficiary, _weiAmount, _tokens);
    }
    
    function _getTokenAmount(uint256 _weiAmount) internal constant returns (uint256) {
        uint256 rate = _getRate();
        return _weiAmount.mul(rate);
    }
    
    function _getRate() internal constant returns (uint256){
        uint256 rate;
        if (lot1 > 0){ // ICO lot1
            // set rate 0.003
            rate = _setPriceFactor(3);
        } else if(lot2 > 0) { // ICO lot2
            // do something 0.005
            rate = _setPriceFactor(5);
        } else if (lot3 > 0){ // ICO lot3
            // third phase ICO 0.007
            rate = _setPriceFactor(7);
        }
        return rate;
    }
    
    function _setPriceFactor(uint cents) internal constant returns (uint256){
      uint256 ETHUSD2CENTS = ethusdrate.mul(100); // convert USD price per ethers to cents
      uint256 tokenRatePerWei = ((ETHUSD2CENTS.mul(1000)).div(cents)); // calculates the rate of the tokens to be given per wei, checking the rate in cents  
      return tokenRatePerWei;
    }
    
    function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
        _deliverTokens(_beneficiary, _tokenAmount);
    }
    
    function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
        _transfer(_beneficiary, _tokenAmount);
        _updateLots(_tokenAmount);
    }
    
    function _updateLots(uint256 _tokenAmount) internal {
        if(lot1 != 0){
            if(_tokenAmount > lot1){
                lot2 = lot2.add(lot1); // add lot1 to lot2
                lot1 = lot1.sub(lot1); // make lot1 empty
                lot2 = lot2.sub(_tokenAmount); // subtract the distributed tokens from lot2
            }
            else {
                lot1 = lot1.sub(_tokenAmount); // subtract the distributed tokens from lot1
            }
        }
        else if(lot2 != 0){
            if(_tokenAmount > lot2){
                lot3 = lot3.add(lot2);  // add lot2 to lot3
                lot2 = lot2.sub(lot2); // make lot2 empty
                lot3 = lot3.sub(_tokenAmount); //subtract the distributed tokens from lot3
            }
            else {
                lot2 = lot2.sub(_tokenAmount); // subtract the distributed tokens from lot2
            }
        }
        else if(lot3 != 0){
            lot3 = lot3.sub(_tokenAmount); //subtract the distributed tokens from lot3
        }
    }
    
    function _forwardFunds() internal {
        wallet.transfer(address(this).balance);
    }
    
    function _transfer(address to, uint tokens) internal returns (bool success) {
        // prevent transfer to 0x0, use burn instead
        require(to != 0x0);
        require(balances[this] >= tokens );
        require(balances[to] + tokens >= balances[to]);
        balances[this] = balances[this].sub(tokens);
        balances[to] = balances[to].add(tokens);
        emit Transfer(this,to,tokens);
        return true;
    }
    
    function freeTokens(address receiver, uint tokenAmount) external onlyOwner {
        require(balances[this] != 0);
        _transfer(receiver,tokenAmount*10**uint(decimals));
    }
    
    function drainFunds() external onlyOwner {
        _forwardFunds();
    }
    
    function changeWallet(address _newWallet) external onlyOwner {
        wallet = _newWallet;
    }
    
    function stopICO() external onlyOwner {
        Open = false;
    }
    
    /* ERC20Interface function's implementation */
    function totalSupply() public constant returns (uint){
       return 12e27; // 12 billion 
    }
    
    // ------------------------------------------------------------------------
    // Get the token balance for account `tokenOwner`
    // ------------------------------------------------------------------------
    function balanceOf(address tokenOwner) public constant returns (uint balance) {
        return balances[tokenOwner];
    }

    // ------------------------------------------------------------------------
    // Transfer the balance from token owner's account to `to` account
    // - Owner's account must have sufficient balance to transfer
    // - 0 value transfers are allowed
    // ------------------------------------------------------------------------
    function transfer(address to, uint tokens) public returns (bool success) {
        // prevent transfer to 0x0, use burn instead
        require(to != 0x0);
        require(balances[msg.sender] >= tokens );
        require(balances[to] + tokens >= balances[to]);
        balances[msg.sender] = balances[msg.sender].sub(tokens);
        balances[to] = balances[to].add(tokens);
        emit Transfer(msg.sender,to,tokens);
        return true;
    }
    
    function transferWithMsg(address to, uint tokens, string message) public returns (bool success){
        // prevent transfer to 0x0, use burn instead
        require(to != 0x0);
        require(balances[msg.sender] >= tokens );
        require(balances[to] + tokens >= balances[to]);
        balances[msg.sender] = balances[msg.sender].sub(tokens);
        balances[to] = balances[to].add(tokens);
        emit Transfer(msg.sender,to,tokens);
        emit TransferWithMsg(msg.sender, to, tokens, message);
        return true;
    }
    
    // ------------------------------------------------------------------------
    // Token owner can approve for `spender` to transferFrom(...) `tokens`
    // from the token owner's account
    // ------------------------------------------------------------------------
    function approve(address spender, uint tokens) public returns (bool success){
        allowed[msg.sender][spender] = tokens;
        emit Approval(msg.sender,spender,tokens);
        return true;
    }

    // ------------------------------------------------------------------------
    // Transfer `tokens` from the `from` account to the `to` account
    // 
    // The calling account must already have sufficient tokens approve(...)-d
    // for spending from the `from` account and
    // - From account must have sufficient balance to transfer
    // - Spender must have sufficient allowance to transfer
    // - 0 value transfers are allowed
    // ------------------------------------------------------------------------
    function transferFrom(address from, address to, uint tokens) public returns (bool success){
        require(tokens <= allowed[from][msg.sender]); //check allowance
        require(balances[from] >= tokens);
        balances[from] = balances[from].sub(tokens);
        balances[to] = balances[to].add(tokens);
        allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
        emit Transfer(from,to,tokens);
        return true;
    }
    // ------------------------------------------------------------------------
    // Returns the amount of tokens approved by the owner that can be
    // transferred to the spender's account
    // ------------------------------------------------------------------------
    function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
        return allowed[tokenOwner][spender];
    }

}
/**
 * @title OUT2ICO
 * @dev   OUT2ICO accepting contributions only within a time frame.
 */
function balanceOf(address tokenOwner) public constant returns (uint balance) {
        return balances[tokenOwner];
    }
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------