contract EtherNumbers is ERC721 {

  /*** EVENTS ***/

  /// @dev The Birth event is fired whenever a new Gem comes into existence.
  event Birth(uint256 tokenId, string name, address owner);

  /// @dev The TokenSold event is fired whenever a token is sold.
  event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name);

  /// @dev Transfer event as defined in current draft of ERC721.
  ///  ownership is assigned, including births.
  event Transfer(address from, address to, uint256 tokenId);

  /*** CONSTANTS ***/

  /// @notice Name and symbol of the non fungible token, as defined in ERC721.
  string public constant NAME = "EtherNumbers"; // solhint-disable-line
  string public constant SYMBOL = "NumberToken"; // solhint-disable-line

  uint256 private startingPrice = 0.001 ether;
  uint256 private constant PROMO_CREATION_LIMIT = 10000;
  uint256 private firstStepLimit =  0.053613 ether;
  uint256 private secondStepLimit = 0.564957 ether;

  /*** STORAGE ***/

  /// @dev A mapping from gem IDs to the address that owns them. All gems have
  ///  some valid owner address.
  mapping (uint256 => address) public gemIndexToOwner;

  // @dev A mapping from owner address to count of tokens that address owns.
  //  Used internally inside balanceOf() to resolve ownership count.
  mapping (address => uint256) private ownershipTokenCount;

  /// @dev A mapping from GemIDs to an address that has been approved to call
  ///  transferFrom(). Each Gem can only have one approved address for transfer
  ///  at any time. A zero value means no approval is outstanding.
  mapping (uint256 => address) public gemIndexToApproved;

  // @dev A mapping from GemIDs to the price of the token.
  mapping (uint256 => uint256) private gemIndexToPrice;

  // The addresses of the accounts (or contracts) that can execute actions within each roles.
  address public ceoAddress;
  address public cooAddress;

  uint256 public promoCreatedCount;

  /*** DATATYPES ***/
  struct Gem {
    string name;
  }

  Gem[] private gems;

  /*** ACCESS MODIFIERS ***/
  /// @dev Access modifier for CEO-only functionality
  modifier onlyCEO() {
    require(msg.sender == ceoAddress);
    _;
  }

  /// @dev Access modifier for COO-only functionality
  modifier onlyCOO() {
    require(msg.sender == cooAddress);
    _;
  }

  /// Access modifier for contract owner only functionality
  modifier onlyCLevel() {
    require(
      msg.sender == ceoAddress ||
      msg.sender == cooAddress
    );
    _;
  }

  /*** CONSTRUCTOR ***/
  function EtherNumbers() public {
    ceoAddress = msg.sender;
    cooAddress = msg.sender;
  }

  /*** PUBLIC FUNCTIONS ***/
  /// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom().
  /// @param _to The address to be granted transfer approval. Pass address(0) to
  ///  clear all approvals.
  /// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
  /// @dev Required for ERC-721 compliance.
  function approve(
    address _to,
    uint256 _tokenId
  ) public {
    // Caller must own token.
    require(_owns(msg.sender, _tokenId));

    gemIndexToApproved[_tokenId] = _to;

    Approval(msg.sender, _to, _tokenId);
  }

  /// For querying balance of a particular account
  /// @param _owner The address for balance query
  /// @dev Required for ERC-721 compliance.
  function balanceOf(address _owner) public view returns (uint256 balance) {
    return ownershipTokenCount[_owner];
  }

  /// @dev Creates a new promo Person with the given name, with given _price and assignes it to an address.
  function createPromoNumber(address _owner, string _name, uint256 _price) public onlyCOO {
    require(promoCreatedCount < PROMO_CREATION_LIMIT);

    address personOwner = _owner;
    if (personOwner == address(0)) {
      personOwner = cooAddress;
    }

    if (_price <= 0) {
      _price = startingPrice;
    }

    promoCreatedCount++;
    _createGem(_name, personOwner, _price);
  }


  /// @dev Creates a new Gem with the given name.
  function createContractGem(string _name) public onlyCLevel {
    _createGem(_name, address(this), startingPrice);
  }

  /// @notice Returns all the relevant information about a specific gem.
  /// @param _tokenId The tokenId of the gem of interest.
  function getGem(uint256 _tokenId) public view returns (
    string gemName,
    uint256 sellingPrice,
    address owner
  ) {
    Gem storage gem = gems[_tokenId];
    gemName = gem.name;
    sellingPrice = gemIndexToPrice[_tokenId];
    owner = gemIndexToOwner[_tokenId];
  }

  function implementsERC721() public pure returns (bool) {
    return true;
  }

  /// @dev Required for ERC-721 compliance.
  function name() public pure returns (string) {
    return NAME;
  }

  /// For querying owner of token
  /// @param _tokenId The tokenID for owner inquiry
  /// @dev Required for ERC-721 compliance.
  function ownerOf(uint256 _tokenId)
    public
    view
    returns (address owner)
  {
    owner = gemIndexToOwner[_tokenId];
    require(owner != address(0));
  }

  function payout(address _to) public onlyCLevel {
    _payout(_to);
  }

  // Allows someone to send ether and obtain the token
  function purchase(uint256 _tokenId) public payable {
    address oldOwner = gemIndexToOwner[_tokenId];
    address newOwner = msg.sender;

    uint256 sellingPrice = gemIndexToPrice[_tokenId];

    // Making sure token owner is not sending to self
    require(oldOwner != newOwner);

    // Safety check to prevent against an unexpected 0x0 default.
    require(_addressNotNull(newOwner));

    // Making sure sent amount is greater than or equal to the sellingPrice
    require(msg.value >= sellingPrice);

    uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 82), 100));
    uint256 dividends = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 10), 100));
    uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice);

    // Update prices
    if (sellingPrice < firstStepLimit) {
      // first stage
      gemIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 92);
    } else if (sellingPrice < secondStepLimit) {
      // second stage
      gemIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 140), 92);
    } else {
      // third stage
      gemIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 125), 92);
    }


    if (balanceOf(ownerOf(0)) >= 3 || ownerOf(0) == ownerOf(getNumberOne()) || ownerOf(0) == ownerOf(getNumberTwo()) || ownerOf(0) == ownerOf(getNumberThree()) && oldOwner != address(this)) {
        ownerOf(0).transfer(SafeMath.mul(SafeMath.div(dividends, 100), 15));
    } else {
        oldOwner.transfer(SafeMath.mul(SafeMath.div(dividends, 100), 15));
    }

    if (balanceOf(ownerOf(1)) >= 3 || ownerOf(1) == ownerOf(getNumberOne()) || ownerOf(1) == ownerOf(getNumberTwo()) || ownerOf(1) == ownerOf(getNumberThree()) && oldOwner != address(this)) {
        ownerOf(1).transfer(SafeMath.mul(SafeMath.div(dividends, 100), 14));
    } else {
        oldOwner.transfer(SafeMath.mul(SafeMath.div(dividends, 100), 14));
    }

    if (balanceOf(ownerOf(2)) >= 3 || ownerOf(2) == ownerOf(getNumberOne()) || ownerOf(2) == ownerOf(getNumberTwo()) || ownerOf(2) == ownerOf(getNumberThree()) && oldOwner != address(this)) {
        ownerOf(2).transfer(SafeMath.mul(SafeMath.div(dividends, 100), 13));
    } else {
        oldOwner.transfer(SafeMath.mul(SafeMath.div(dividends, 100), 13));
    }

    if (balanceOf(ownerOf(3)) >= 3 || ownerOf(3) == ownerOf(getNumberOne()) || ownerOf(3) == ownerOf(getNumberTwo()) || ownerOf(3) == ownerOf(getNumberThree()) && oldOwner != address(this)) {
        ownerOf(3).transfer(SafeMath.mul(SafeMath.div(dividends, 100), 12));
    } else {
        oldOwner.transfer(SafeMath.mul(SafeMath.div(dividends, 100), 12));
    }

    if (balanceOf(ownerOf(4)) >= 3 || ownerOf(4) == ownerOf(getNumberOne()) || ownerOf(4) == ownerOf(getNumberTwo()) || ownerOf(4) == ownerOf(getNumberThree()) && oldOwner != address(this)) {
        ownerOf(4).transfer(SafeMath.mul(SafeMath.div(dividends, 100), 11));
    } else {
        oldOwner.transfer(SafeMath.mul(SafeMath.div(dividends, 100), 11));
    }

    if (balanceOf(ownerOf(5)) >= 3 || ownerOf(5) == ownerOf(getNumberOne()) || ownerOf(5) == ownerOf(getNumberTwo()) || ownerOf(5) == ownerOf(getNumberThree()) && oldOwner != address(this)) {
        ownerOf(5).transfer(SafeMath.mul(SafeMath.div(dividends, 100), 9));
    } else {
        oldOwner.transfer(SafeMath.mul(SafeMath.div(dividends, 100), 9));
    }

    if (balanceOf(ownerOf(6)) >= 3 || ownerOf(6) == ownerOf(getNumberOne()) || ownerOf(6) == ownerOf(getNumberTwo()) || ownerOf(6) == ownerOf(getNumberThree()) && oldOwner != address(this)) {
        ownerOf(6).transfer(SafeMath.mul(SafeMath.div(dividends, 100), 8));
    } else {
        oldOwner.transfer(SafeMath.mul(SafeMath.div(dividends, 100), 8));
    }

    if (balanceOf(ownerOf(7)) >= 3 || ownerOf(7) == ownerOf(getNumberOne()) || ownerOf(7) == ownerOf(getNumberTwo()) || ownerOf(7) == ownerOf(getNumberThree()) && oldOwner != address(this)) {
        ownerOf(7).transfer(SafeMath.mul(SafeMath.div(dividends, 100), 7));
    } else {
        oldOwner.transfer(SafeMath.mul(SafeMath.div(dividends, 100), 7));
    }

    if (balanceOf(ownerOf(8)) >= 3 || ownerOf(8) == ownerOf(getNumberOne()) || ownerOf(8) == ownerOf(getNumberTwo()) || ownerOf(8) == ownerOf(getNumberThree()) && oldOwner != address(this)) {
        ownerOf(8).transfer(SafeMath.mul(SafeMath.div(dividends, 100), 6));
    } else {
        oldOwner.transfer(SafeMath.mul(SafeMath.div(dividends, 100), 6));
    }

    if (balanceOf(ownerOf(9)) >= 3 || ownerOf(9) == ownerOf(getNumberOne()) || ownerOf(9) == ownerOf(getNumberTwo()) || ownerOf(9) == ownerOf(getNumberThree()) && oldOwner != address(this)) {
        ownerOf(9).transfer(SafeMath.mul(SafeMath.div(dividends, 100), 5));
    } else {
        oldOwner.transfer(SafeMath.mul(SafeMath.div(dividends, 100), 5));
    }


    _transfer(oldOwner, newOwner, _tokenId);

    // Pay previous tokenOwner if owner is not contract
    if (oldOwner != address(this)) {
      oldOwner.transfer(payment); //(1-0.08)
    }




    TokenSold(_tokenId, sellingPrice, gemIndexToPrice[_tokenId], oldOwner, newOwner, gems[_tokenId].name);

    msg.sender.transfer(purchaseExcess);
  }


    uint256 numberOne;
    uint256 numberTwo;
    uint256 numberThree;


  function setNumberOne(uint256 number) public onlyCEO {
      numberOne = number;
  }

  function setNumberTwo(uint256 number) public onlyCEO {
      numberTwo = number;
  }

  function setNumberThree(uint256 number) public onlyCEO {
      numberThree = number;
  }

  function getNumberOne() public view returns (uint256 dailyNumber) {
      return numberOne;
  }

  function getNumberTwo() public view returns (uint256 dailyNumber) {
      return numberTwo;
  }

  function getNumberThree() public view returns (uint256 dailyNumber) {
      return numberThree;
  }




  function changePrice(uint256 _tokenId) public  {
    require(_owns(msg.sender, _tokenId));

    uint256 currentPrice = gemIndexToPrice[_tokenId];
    uint256 onePercent = SafeMath.div(currentPrice, 100);
    uint256 newPrice = SafeMath.mul(onePercent,95);
    gemIndexToPrice[_tokenId] = newPrice;

  }

  function priceOf(uint256 _tokenId) public view returns (uint256 price) {
    return gemIndexToPrice[_tokenId];
  }

  /// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
  /// @param _newCEO The address of the new CEO
  function setCEO(address _newCEO) public onlyCEO {
    require(_newCEO != address(0));

    ceoAddress = _newCEO;
  }

  /// @dev Assigns a new address to act as the COO. Only available to the current COO.
  /// @param _newCOO The address of the new COO
  function setCOO(address _newCOO) public onlyCEO {
    require(_newCOO != address(0));

    cooAddress = _newCOO;
  }

  /// @dev Required for ERC-721 compliance.
  function symbol() public pure returns (string) {
    return SYMBOL;
  }

  /// @notice Allow pre-approved user to take ownership of a token
  /// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
  /// @dev Required for ERC-721 compliance.
  function takeOwnership(uint256 _tokenId) public {
    address newOwner = msg.sender;
    address oldOwner = gemIndexToOwner[_tokenId];

    // Safety check to prevent against an unexpected 0x0 default.
    require(_addressNotNull(newOwner));

    // Making sure transfer is approved
    require(_approved(newOwner, _tokenId));

    _transfer(oldOwner, newOwner, _tokenId);
  }

  /// @param _owner The owner whose celebrity tokens we are interested in.
  /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
  ///  expensive (it walks the entire Gems array looking for gems belonging to owner),
  ///  but it also returns a dynamic array, which is only supported for web3 calls, and
  ///  not contract-to-contract calls.
  function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) {
    uint256 tokenCount = balanceOf(_owner);
    if (tokenCount == 0) {
        // Return an empty array
      return new uint256[](0);
    } else {
      uint256[] memory result = new uint256[](tokenCount);
      uint256 totalGems = totalSupply();
      uint256 resultIndex = 0;

      uint256 gemId;
      for (gemId = 0; gemId <= totalGems; gemId++) {
        if (gemIndexToOwner[gemId] == _owner) {
          result[resultIndex] = gemId;
          resultIndex++;
        }
      }
      return result;
    }
  }

  /// For querying totalSupply of token
  /// @dev Required for ERC-721 compliance.
  function totalSupply() public view returns (uint256 total) {
    return gems.length;
  }

  /// Owner initates the transfer of the token to another account
  /// @param _to The address for the token to be transferred to.
  /// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
  /// @dev Required for ERC-721 compliance.
  function transfer(
    address _to,
    uint256 _tokenId
  ) public {
    require(_owns(msg.sender, _tokenId));
    require(_addressNotNull(_to));

    _transfer(msg.sender, _to, _tokenId);
  }

  /// Third-party initiates transfer of token from address _from to address _to
  /// @param _from The address for the token to be transferred from.
  /// @param _to The address for the token to be transferred to.
  /// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
  /// @dev Required for ERC-721 compliance.
  function transferFrom(
    address _from,
    address _to,
    uint256 _tokenId
  ) public {
    require(_owns(_from, _tokenId));
    require(_approved(_to, _tokenId));
    require(_addressNotNull(_to));

    _transfer(_from, _to, _tokenId);
  }

  /*** PRIVATE FUNCTIONS ***/
  /// Safety check on _to address to prevent against an unexpected 0x0 default.
  function _addressNotNull(address _to) private pure returns (bool) {
    return _to != address(0);
  }

  /// For checking approval of transfer for address _to
  function _approved(address _to, uint256 _tokenId) private view returns (bool) {
    return gemIndexToApproved[_tokenId] == _to;
  }

  /// For creating Gem
  function _createGem(string _name, address _owner, uint256 _price) private {
    Gem memory _gem = Gem({
      name: _name
    });
    uint256 newGemId = gems.push(_gem) - 1;

    // It's probably never going to happen, 4 billion tokens are A LOT, but
    // let's just be 100% sure we never let this happen.
    require(newGemId == uint256(uint32(newGemId)));

    Birth(newGemId, _name, _owner);

    gemIndexToPrice[newGemId] = _price;

    // This will assign ownership, and also emit the Transfer event as
    // per ERC721 draft
    _transfer(address(0), _owner, newGemId);
  }

  /// Check for token ownership
  function _owns(address claimant, uint256 _tokenId) private view returns (bool) {
    return claimant == gemIndexToOwner[_tokenId];
  }

  /// For paying out balance on contract
  function _payout(address _to) private {
    if (_to == address(0)) {
      ceoAddress.transfer(this.balance);
    } else {
      _to.transfer(this.balance);
    }
  }

  /// @dev Assigns ownership of a specific Gem to an address.
  function _transfer(address _from, address _to, uint256 _tokenId) private {
    // Since the number of gems is capped to 2^32 we can't overflow this
    ownershipTokenCount[_to]++;
    //transfer ownership
    gemIndexToOwner[_tokenId] = _to;

    // When creating new gems _from is 0x0, but we can't account that address.
    if (_from != address(0)) {
      ownershipTokenCount[_from]--;
      // clear any previously approved ownership exchange
      delete gemIndexToApproved[_tokenId];
    }

    // Emit the transfer event.
    Transfer(_from, _to, _tokenId);
  }
}
function name() public pure returns (string) {
    return NAME;
  }
/// @dev Required for ERC-721 compliance.