contract ARBITRAGECrowdsale {
    
    struct Stakeholder
    {
        address stakeholderAddress;
        uint stakeholderPerc;
    }
  using SafeMath for uint256;
 
  // The token being sold
  ARBITRAGEToken public token;
  OldXRPCToken public prevXRPCToken;
  
  // start and end timestamps where investments are allowed (both inclusive)
  uint256 public startTime;
  Stakeholder[] ownersList;
  
  // address where funds are collected
  // address where tokens are deposited and from where we send tokens to buyers
  address public walletOwner;
  Stakeholder stakeholderObj;
  

  uint256 public coinPercentage = 5;

    // how many token units a buyer gets per wei
    uint256 public ratePerWei = 1657;
    uint256 public maxBuyLimit=2000;
    uint256 public tokensSoldInThisRound=0;
    uint256 public totalTokensSold = 0;

    // amount of raised money in wei
    uint256 public weiRaised;


    bool public isCrowdsalePaused = false;
    address partnerHandler;
  
  /**
   * event for token purchase logging
   * @param purchaser who paid for the tokens
   * @param beneficiary who got the tokens
   * @param value weis paid for purchase
   * @param amount amount of tokens purchased
   */
  event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);


  function ARBITRAGECrowdsale(address _walletOwner, address _partnerHandler) public {
      
        prevXRPCToken = OldXRPCToken(0xAdb41FCD3DF9FF681680203A074271D3b3Dae526); 
        
        startTime = now;
        
        require(_walletOwner != 0x0);
        walletOwner=_walletOwner;

         stakeholderObj = Stakeholder({
         stakeholderAddress: walletOwner,
         stakeholderPerc : 100});
         
         ownersList.push(stakeholderObj);
        partnerHandler = _partnerHandler;
        token = createTokenContract(_walletOwner);
  }

  // creates the token to be sold.
  function createTokenContract(address wall) internal returns (ARBITRAGEToken) {
    return new ARBITRAGEToken(wall);
  }


  // fallback function can be used to buy tokens
  function () public payable {
    buyTokens(msg.sender);
  }

  
  // low level token purchase function

  function buyTokens(address beneficiary) public payable {
    require (isCrowdsalePaused != true);
        
    require(beneficiary != 0x0);
    require(validPurchase());
    uint256 weiAmount = msg.value;
    // calculate token amount to be created

    uint256 tokens = weiAmount.mul(ratePerWei);
    require(tokensSoldInThisRound.add(tokens)<=maxBuyLimit);
    // update state
    weiRaised = weiRaised.add(weiAmount);

    token.mint(walletOwner, beneficiary, tokens); 
    tokensSoldInThisRound=tokensSoldInThisRound+tokens;
    TokenPurchase(walletOwner, beneficiary, weiAmount, tokens);
    totalTokensSold = totalTokensSold.add(tokens);
    uint partnerCoins = tokens.mul(coinPercentage);
    partnerCoins = partnerCoins.div(100);
    forwardFunds(partnerCoins);
  }

   // send ether to the fund collection wallet(s)
    function forwardFunds(uint256 partnerTokenAmount) internal {
      for (uint i=0;i<ownersList.length;i++)
      {
         uint percent = ownersList[i].stakeholderPerc;
         uint amountToBeSent = msg.value.mul(percent);
         amountToBeSent = amountToBeSent.div(100);
         ownersList[i].stakeholderAddress.transfer(amountToBeSent);
         
         if (ownersList[i].stakeholderAddress!=walletOwner &&  ownersList[i].stakeholderPerc>0)
         {
             token.mint(walletOwner,ownersList[i].stakeholderAddress,partnerTokenAmount);
         }
      }
    }
    
    function updateOwnerShares(address[] partnersAddresses, uint[] partnersPercentages) public{
        require(msg.sender==partnerHandler);
        require(partnersAddresses.length==partnersPercentages.length);
        
        uint sumPerc=0;
        for(uint i=0; i<partnersPercentages.length;i++)
        {
            sumPerc+=partnersPercentages[i];
        }
        require(sumPerc==100);
        
        delete ownersList;
        
        for(uint j=0; j<partnersAddresses.length;j++)
        {
            delete stakeholderObj;
             stakeholderObj = Stakeholder({
             stakeholderAddress: partnersAddresses[j],
             stakeholderPerc : partnersPercentages[j]});
             ownersList.push(stakeholderObj);
        }
    }


  // @return true if the transaction can buy tokens
  function validPurchase() internal constant returns (bool) {
    bool nonZeroPurchase = msg.value != 0;
    return nonZeroPurchase;
  }

  
   function showMyTokenBalance() public view returns (uint256 tokenBalance) {
        tokenBalance = token.showMyTokenBalance(msg.sender);
    }
    
    /**
     * The function to pull back tokens from a  notorious user
     * Can only be called from owner wallet
     **/
    function pullBack(address buyer) public {
        require(msg.sender==walletOwner);
        uint bal = token.balanceOf(buyer);
        token.pullBack(walletOwner,buyer,bal);
    }
    

    /**
     * function to set the new price 
     * can only be called from owner wallet
     **/ 
    function setPriceRate(uint256 newPrice) public returns (bool) {
        require(msg.sender==walletOwner);
        ratePerWei = newPrice;
    }
    
    /**
     * function to set the max buy limit in 1 transaction 
     * can only be called from owner wallet
     **/ 
    
      function setMaxBuyLimit(uint256 maxlimit) public returns (bool) {
        require(msg.sender==walletOwner);
        maxBuyLimit = maxlimit *10 ** 18;
    }
    
      /**
     * function to start new ICO round 
     * can only be called from owner wallet
     **/ 
    
      function startNewICORound(uint256 maxlimit, uint256 newPrice) public returns (bool) {
        require(msg.sender==walletOwner);
        setMaxBuyLimit(maxlimit);
        setPriceRate(newPrice);
        tokensSoldInThisRound=0;
    }
    
      /**
     * function to get this round information 
     * can only be called from owner wallet
     **/ 
    
      function getCurrentICORoundInfo() public view returns 
      (uint256 maxlimit, uint256 newPrice, uint tokensSold) {
       return(maxBuyLimit,ratePerWei,tokensSoldInThisRound);
    }
    
    /**
     * function to pause the crowdsale 
     * can only be called from owner wallet
     **/
     
    function pauseCrowdsale() public returns(bool) {
        require(msg.sender==walletOwner);
        isCrowdsalePaused = true;
    }

    /**
     * function to resume the crowdsale if it is paused
     * can only be called from owner wallet
     * if the crowdsale has been stopped, this function would not resume it
     **/ 
    function resumeCrowdsale() public returns (bool) {
        require(msg.sender==walletOwner);
        isCrowdsalePaused = false;
    }
    
    /**
     * Shows the remaining tokens in the contract i.e. tokens remaining for sale
     **/ 
    function tokensRemainingForSale() public view returns (uint256 balance) {
        balance = token.balanceOf(walletOwner);
    }
    
    /**
     * function to show the equity percentage of an owner - major or minor
     * can only be called from the owner wallet
     **/
    function checkOwnerShare (address owner) public constant returns (uint share) {
        require(msg.sender==walletOwner);
        
        for(uint i=0;i<ownersList.length;i++)
        {
            if(ownersList[i].stakeholderAddress==owner)
            {
                return ownersList[i].stakeholderPerc;
            }
        }
        return 0;
    }

    /**
     * function to change the coin percentage awarded to the partners
     * can only be called from the owner wallet
     **/
    function changePartnerCoinPercentage(uint percentage) public {
        require(msg.sender==walletOwner);
        coinPercentage = percentage;
    }
    
    /**
     * airdrop to old token holders
     **/ 
    function airDropToOldTokenHolders(address[] oldTokenHolders) public {
        require(msg.sender==walletOwner);
        for(uint i = 0; i<oldTokenHolders.length; i++){
            if(prevXRPCToken.balanceOf(oldTokenHolders[i])>0)
            {
                token.mint(walletOwner,oldTokenHolders[i],prevXRPCToken.balanceOf(oldTokenHolders[i]));
            }
        }
    }
    
    function changeWalletOwner(address newWallet) public {
        require(msg.sender==walletOwner);
        walletOwner = newWallet;
    }
}
function changePartnerCoinPercentage(uint percentage) public {
    require(msg.sender==walletOwner);
    coinPercentage = percentage;
}

/**
 * function to change the coin percentage awarded to the partners
 * can only be called from the owner wallet
 **/