// Contract: EqvcTokens
// Target function: function allocateTokens(address to, uint256 tokens) public onlyOwner returns (bool)
 <= balances[msg.sender]);

    uint256 tokensToBurn = findTwoAnfHalfPercent(value);
    uint256 tokensToTransfer = value.sub(tokensToBurn);

     balances[msg.sender] = balances[msg.sender].sub(value);
     balances[to] = balances[to].add(tokensToTransfer);

    totalSupply = totalSupply.sub(tokensToBurn);

    emit Transfer(msg.sender, to, tokensToTransfer);
    emit Transfer(msg.sender, address(0), tokensToBurn);
    return true;
  }
  
  /**
  * @dev transfer token for a specified address
  * @param _to The address to transfer to.
  * @param _value The amount to be transferred.
  */
//   function transfer(address _to, uint256 _value) public returns (bool) {
//     require(_to != address(0));
//     require(_value <= balances[msg.sender]);

//     // SafeMath.sub will throw if there is not enough balance.
//     balances[msg.sender] = balances[msg.sender].sub(_value);
//     balances[_to] = balances[_to].add(_value);
//     emit Transfer(msg.sender, _to, _value);
//     return true;
//   }
  

  /**
  * @dev Gets the balance of the specified address.
  * @param _owner The address to query the the balance of.
  * @return An uint256 representing the amount owned by the passed address.
  */
  function balanceOf(address _owner) public view returns (uint256 balance) {
    return balances[_owner];
  }

}

/**
 * @title Burnable Token
 * @dev Token that can be irreversibly burned (destroyed).
 */
contract BurnableToken is BasicToken {

    event Burn(address indexed burner, uint256 value);

    /**
     * @dev Burns a specific amount of tokens.
     * @param _value The amount of token to be burned.
     */
    function burn(uint256 _value) public {
        require(_value <= balances[msg.sender]);
        // no need to require value <= totalSupply, since that would imply the
        // sender's balance is greater than the totalSupply, which *should* be an assertion failure

        address burner = msg.sender;
        balances[burner] = balances[burner].sub(_value);
        totalSupply = totalSupply.sub(_value);
        emit Burn(burner, _value);
    }
}


/**
 * @title Standard ERC20 token
 *
 * @dev Implementation of the basic standard token.
 * @dev https://github.com/ethereum/EIPs/issues/20
 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
 */
contract StandardToken is ERC20, BasicToken {

  mapping (address => mapping (address => uint256)) internal allowed;


  /**
   * @dev Transfer tokens from one address to another
   * @param _from address The address which you want to send tokens from
   * @param _to address The address which you want to transfer to
   * @param _value uint256 the amount of tokens to be transferred
   */
  function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
    require(_to != address(0));
    require(_value <= balances[_from]);
    require(_value <= allowed[_from][msg.sender]);

    balances[_from] = balances[_from].sub(_value);
    balances[_to] = balances[_to].add(_value);
    allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
    emit Transfer(_from, _to, _value);
    return true;
  }

  /**
   * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
   *
   * Beware that changing an allowance with this method brings the risk that someone may use both the old
   * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
   * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
   * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
   * @param _spender The address which will spend the funds.
   * @param _value The amount of tokens to be spent.
   */
  function approve(address _spender, uint256 _value) public returns (bool) {
    allowed[msg.sender][_spender] = _value;
    emit Approval(msg.sender, _spender, _value);
    return true;
  }

  /**
   * @dev Function to check the amount of tokens that an owner allowed to a spender.
   * @param _owner address The address which owns the funds.
   * @param _spender address The address which will spend the funds.
   * @return A uint256 specifying the amount of tokens still available for the spender.
   */
  function allowance(address _owner, address _spender) public view returns (uint256) {
    return allowed[_owner][_spender];
  }

  /**
   * @dev Increase the amount of tokens that an owner allowed to a spender.
   *
   * approve should be called when allowed[_spender] == 0. To increment
   * allowed value is better to use this function to avoid 2 calls (and wait until
   * the first transaction is mined)
   * From MonolithDAO Token.sol
   * @param _spender The address which will spend the funds.
   * @param _addedValue The amount of tokens to increase the allowance by.
   */
  function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
    allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
    emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
    return true;
  }

  /**
   * @dev Decrease the amount of tokens that an owner allowed to a spender.
   *
   * approve should be called when allowed[_spender] == 0. To decrement
   * allowed value is better to use this function to avoid 2 calls (and wait until
   * the first transaction is mined)
   * From MonolithDAO Token.sol
   * @param _spender The address which will spend the funds.
   * @param _subtractedValue The amount of tokens to decrease the allowance by.
   */
  function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
    uint oldValue = allowed[msg.sender][_spender];
    if (_subtractedValue > oldValue) {
      allowed[msg.sender][_spender] = 0;
    } else {
      allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
    }
    emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
    return true;
  }

}


/*
 * EqvcToken is a standard ERC20 token with some additional functionalities:
 * - Transfers are only enabled after contract owner enables it (after the ICO)
 *
 * Note: Token Offering == Initial Coin Offering(ICO)
 */

contract EqvcTokens is StandardToken, Ownable {
    string public constant symbol = "EQVC";
    string public constant name = "EqvcToken";
    uint8 public constant decimals = 0;
    uint256 public constant INITIAL_SUPPLY = 2000000;
    uint256 public constant TOKEN_OFFERING_ALLOWANCE = 2000000;
    uint256 public constant ADMIN_ALLOWANCE = INITIAL_SUPPLY - TOKEN_OFFERING_ALLOWANCE;
    
    // Address of token admin
    address public adminAddr;

    // Address of token offering
	  address public tokenOfferingAddr;

    // Enable transfers after conclusion of token offering
    bool public transferEnabled = false;
    
    /**
     * Check if transfer is allowed
     *
     * Permissions:
     *                                                       Owner    Admin    OffeirngContract    Others
     * transfer (before transferEnabled is true)               x        x            x               x
     * transferFrom (before transferEnabled is true)           x        v            v               x
     * transfer/transferFrom after transferEnabled is true     v        x            x               v
     */
    modifier onlyWhenTransferAllowed() {
        require(transferEnabled || msg.sender == adminAddr || msg.sender == tokenOfferingAddr);
        _;
    }

    /**
     * Check if token offering address is set or not
     */
    modifier onlyTokenOfferingAddrNotSet() {
        require(tokenOfferingAddr == address(0x0));
        _;
    }

    /**
     * Check if address is a valid destination to transfer tokens to
     * - must not be zero address
     * - must not be the token address
     * - must not be the owner's address
     * - must not be the admin's address
     * - must not be the token offering contract address
     */
    modifier validDestination(address to) {
        require(to != address(0x0));
        require(to != address(this));
        require(to != owner);
        require(to != address(adminAddr));
        require(to != address(tokenOfferingAddr));
        _;
    }
    
    /**
     * Token contract constructor
     *
     * @param admin Address of admin account
     */
    function EqvcToken(address admin) public {
        totalSupply = INITIAL_SUPPLY;
        
        // Mint tokens
        balances[msg.sender] = totalSupply;
        emit Transfer(address(0x0), msg.sender, totalSupply);

        // Approve allowance for admin account
        adminAddr = admin;
        approve(adminAddr, ADMIN_ALLOWANCE);
    }
    
    
 

    /**
     * Set token offering to approve allowance for offering contract to distribute tokens
     *
     * @param offeringAddr Address of token offering contract
     * @param amountForSale Amount of tokens for sale, set 0 to max out
     */
    function setTokenOffering(address offeringAddr, uint256 amountForSale) external onlyOwner onlyTokenOfferingAddrNotSet {
        require(!transferEnabled);

        uint256 amount = (amountForSale == 0) ? TOKEN_OFFERING_ALLOWANCE : amountForSale;
        require(amount <= TOKEN_OFFERING_ALLOWANCE);

        approve(offeringAddr, amount);
        tokenOfferingAddr = offeringAddr;
    }
    
    /**
     * Enable transfers
     */
    function enableTransfer() external onlyOwner {
        transferEnabled = true;

        // End the offering
        approve(tokenOfferingAddr, 0);
    }

    /**
     * Transfer from sender to another account
     *
     * @param to Destination address
     * @param value Amount of Eqvcs to send
     */
    function transfer(address to, uint256 value) public onlyWhenTransferAllowed validDestination(to) returns (bool) {
        return super.transfer(to, value);
    }
    
    /**
     * Transfer from `from` account to `to` account using allowance in `from` account to the sender
     *
     * @param from Origin address
     * @param to Destination address
     * @param value Amount of Eqvcs to send
     */
    function transferFrom(address from, address to, uint256 value) public onlyWhenTransferAllowed validDestination(to) returns (bool) {
        return super.transferFrom(from, to, value);
    }
    
}

contract EqvcsCrowdsale is Pausable {
    using SafeMath for uint256;

     // Token to be sold
    EqvcTokens public token;

    // Start and end timestamps where contributions are allowed (both inclusive)
    uint256 public startTime;
    uint256 public endTime;

    // Address where funds are collected
    address payable  beneficiary;

    // Price of the tokens as in tokens per ether
    uint256 public rate;

    // Amount of raised in Wei 
    uint256 public EthRaised;

    // Timelines for contribution limit policy
    uint256 public capReleaseTimestamp;

    uint256 public extraTime;

    // Whitelists of participant address
    // mapping(address => bool) public whitelists;

    // Contributions in Wei for each participant
    mapping(address => uint256) public contributions;

    // Funding cap in ETH. 
     uint256 public constant FUNDING_ETH_HARD_CAP = 1300;

    // Min contribution is 0.1 ether
    uint256 public minContribution = 1 ;

    // Max contribution is 10 ether
    uint256 public maxContribution = 15;

    //remainCap
     uint256 public remainCap;

    // The current stage of the offering
    Stages public stage;

    enum Stages { 
        Setup,
        OfferingStarted,
        OfferingEnded
    }

    event OfferingOpens(uint256 startTime, uint256 endTime);
    event OfferingCloses(uint256 endTime, uint256 totalEthRaised);
    /**
     * Event for token purchase logging
     *
     * @param purchaser Who paid for the tokens
     * @param value Weis paid for purchase
     * @return amount Amount of tokens purchased
     */
    event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount);

    /**
     * Modifier that requires certain stage before executing the main function body
     *
     * @param expectedStage Value that the current stage is required to match
     */
    modifier atStage(Stages expectedStage) {
        require(stage == expectedStage);
        _;
    }

    
    /**
     * The constructor of the contract.
     * @param eqvcToEtherRate Number of Eqvcs per ether
     * @param beneficiaryAddr Address where funds are collected
     */
    function EqvcCrowdsale(
        uint256 eqvcToEtherRate, 
        address payable beneficiaryAddr, 
        address tokenAddress
    ) public {
        require(eqvcToEtherRate > 0);
        require(beneficiaryAddr != address(0));
        require(tokenAddress != address(0));

        token = EqvcTokens(tokenAddress);
        rate = eqvcToEtherRate;
        beneficiary = beneficiaryAddr;
        stage = Stages.Setup;
    }

    /**
     * Fallback function can be used to buy tokens
     */
    function ()  payable external {
        buy();
    }

    // /**
    //  * Withdraw available ethers into beneficiary account, serves as a safety, should never be needed
    //  */
    function ownerSafeWithdrawal() external onlyOwner {
        beneficiary.transfer(address(this).balance);
    }

    function updateRate(uint256 eqvcToEtherRate) public onlyOwner atStage(Stages.Setup) {
        rate = eqvcToEtherRate;
    }

    /**
     * Whitelist participant address 
     * 
     * 
     * @param users Array of addresses to be whitelisted
     */
    // function whitelist(address[] memory users) public onlyOwner {
    //     for (uint32 i = 0; i < users.length; i++) {
    //         whitelists[users[i]] = true;
    //     }
    // }
    // function whitelistRemove(address user) public onlyOwner{
    //   require(whitelists[user]);
    //   whitelists[user] = false;
    // }
    /**
     * Start the offering
     *
     * @param durationInSeconds Extra duration of the offering on top of the minimum 4 hours
     */
    function startOffering(uint256 durationInSeconds) public onlyOwner atStage(Stages.Setup) {
        stage = Stages.OfferingStarted;
        startTime = now;
        capReleaseTimestamp = startTime + 1 days;
        extraTime = capReleaseTimestamp + 365 days;
        endTime = extraTime.add(durationInSeconds);
        emit OfferingOpens(startTime, endTime);
    }

    /**
     * End the offering
     */
    function endOffering() public onlyOwner atStage(Stages.OfferingStarted) {
        endOfferingImpl();
    }
    
  
    /**
     * Function to invest ether to buy tokens, can be called directly or called by the fallback function
     * Only whitelisted users can buy tokens.
     *
     * @return bool Return true if purchase succeeds, false otherwise
     */
    function buy() public payable whenNotPaused atStage(Stages.OfferingStarted) returns (bool) {
        // if (whitelists[msg.sender]) {
              buyTokens();
              return true;
        // }
        revert();
    }

    /**
     * Function that returns whether offering has ended
     * 
     * @return bool Return true if token offering has ended
     */
    function hasEnded() public view returns (bool) {
        return now > endTime || stage == Stages.OfferingEnded;
    }

    /**
     * Modifier that validates a purchase at a tier
     * All the following has to be met:
     * - current time within the offering period
     * - valid sender address and ether value greater than 0.1
     * - total Wei raised not greater than FUNDING_ETH_HARD_CAP
     * - contribution per perticipant within contribution limit
     *
     * 
     */
    modifier validPurchase() {
        require(now >= startTime && now <= endTime && stage == Stages.OfferingStarted);
        if(now > capReleaseTimestamp) {
          maxContribution = 2000;
        }
        uint256 contributionInETH = uint256(msg.value).div(10**18);
        address participant = msg.sender; 


        require(contributionInETH <= maxContribution.sub(contributions[participant]));
        require(participant != address(0) && contributionInETH >= minContribution && contributionInETH <= maxContribution);
        require(EthRaised.add(contributionInETH) <= FUNDING_ETH_HARD_CAP);
        
        _;
    }


    function buyTokens() internal validPurchase {
      
        // contributionInETH amount in eth
        uint256 contributionInETH = uint256(msg.value).div(10**18);
        address participant = msg.sender;

        // Calculate token amount to be distributed
        uint256 tokens = contributionInETH.mul(rate);
        
        if (!token.transferFrom(token.owner(), participant, tokens)) {
            revert();
        }

        EthRaised = EthRaised.add(contributionInETH);
        contributions[participant] = contributions[participant].add(contributionInETH);

        remainCap = FUNDING_ETH_HARD_CAP.sub(EthRaised);

        
       // Check if the funding cap has been reached, end the offering if so
        if (EthRaised >= FUNDING_ETH_HARD_CAP) {
            endOfferingImpl();
        }
        
        // // Transfer funds to beneficiary
        // transfer(beneficiary,contributionInETH);
        beneficiary.transfer(contributionInETH.mul(10**18));
        emit TokenPurchase(msg.sender, contributionInETH, tokens);          
    }


    /**
     * End token offering by set the stage and endTime
     */
    function endOfferingImpl() internal{
        endTime = now;
        stage = Stages.OfferingEnded;
        emit OfferingCloses(endTime, EthRaised);
    }