contract Crowdsale {
  using SafeMath for uint256;

  // The token being sold
  ERC20 public token;

  // Address where funds are collected
  address public wallet;

  // How many token units a buyer gets per wei
  uint256 public rate;

  // Amount of wei raised
  uint256 public weiRaised;

  // total cap
  uint256 public cap;

  //sales between openingTime and closingTime
  uint256 public openingTime;
  uint256 public closingTime;

  mapping (address => uint256) public contributorList;

  /**
   * @dev Reverts if not in crowdsale time range. 
   */
  modifier onlyWhileOpen {
    require(now >= openingTime && now <= closingTime);
    _;
  }

  /**
   * 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);

  /**
   * @param _rate Number of token units a buyer gets per wei
   * @param _wallet Address where collected funds will be forwarded to
   * @param _token Address of the token being sold
   * @param _cap Amount of weis to be sold
   */
  function Crowdsale(uint256 _rate, address _wallet, ERC20 _token, uint256 _cap, uint256 _openingTime, uint256 _closingTime) public {
    require(_rate > 0);
    require(_wallet != address(0));
    require(_token != address(0));
    require(_cap > 0);
    require(_openingTime >= now);
    require(_closingTime >= _openingTime);
    
    rate = _rate;
    wallet = _wallet;
    token = _token;
    cap = _cap;
    openingTime = _openingTime;
    closingTime = _closingTime;  
    
    }

  /**
   * @dev Checks whether the cap has been reached. 
   * @return Whether the cap was reached
   */
  function capReached() public view returns (bool) {
    return weiRaised >= cap;
  }

  // -----------------------------------------
  // Crowdsale external interface
  // -----------------------------------------

  /**
   * @dev fallback function ***DO NOT OVERRIDE***
   */
  function () external payable {
    buyTokens(msg.sender);
  }

  /**
   * @dev low level token purchase ***DO NOT OVERRIDE***
   * @param _beneficiary Address performing the token purchase
   */
  function buyTokens(address _beneficiary) public payable {

    //uint256 weiAmountTmp = msg.value;
    uint256 weiAmount;

    weiAmount = (weiRaised.add(msg.value) <= cap) ? (msg.value) : (cap.sub(weiRaised));

    _preValidatePurchase(_beneficiary, weiAmount);

    _setContributor(_beneficiary, weiAmount);

    //update state
    weiRaised = weiRaised.add(weiAmount);

    /**
    * return overflowed ETH to sender
    */
    if(weiAmount < msg.value){
        _beneficiary.transfer(msg.value.sub(weiAmount));
    }
    _forwardFundsWei(weiAmount);

  }

  /**
   * @dev Checks whether the period in which the crowdsale is open has already elapsed.
   * @return Whether crowdsale period has elapsed
   */
  function hasClosed() public view returns (bool) {
    return now > closingTime;
  }

  // -----------------------------------------
  // Internal interface (extensible)
  // -----------------------------------------

  /**
   * @dev Validation of an incoming purchase. Use require statemens to revert state when conditions are not met. Use super to concatenate validations.
   * @param _beneficiary Address performing the token purchase
   * @param _weiAmount Value in wei involved in the purchase
   */
  function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen {
    require(_beneficiary != address(0));
    require(_weiAmount != 0);
    require(weiRaised.add(_weiAmount) <= cap);

  }

  function _setContributor(address _beneficiary, uint256 _tokenAmount) internal onlyWhileOpen {

    // rounding at 2 point
    uint pibToken = _tokenAmount.mul(rate).div(10 ** 16).mul(10 ** 16);
//      uint pibToken = _tokenAmount.mul(rate);
  
     contributorList[_beneficiary] += pibToken;

  }

  /**
   * @dev Determines how ETH is stored/forwarded on purchases.
   */
  function _forwardFundsWei(uint256 txAmount) internal {

    wallet.transfer(txAmount);

  }  
  
}
/**
 * @title Crowdsale
 * @dev Crowdsale is a base contract for managing a token crowdsale,
 * allowing investors to purchase tokens with ether. This contract implements
 * such functionality in its most fundamental form and can be extended to provide additional
 * functionality and/or custom behavior.
 * The external interface represents the basic interface for purchasing tokens, and conform
 * the base architecture for crowdsales. They are *not* intended to be modified / overriden.
 * The internal interface conforms the extensible and modifiable surface of crowdsales. Override 
 * the methods to add functionality. Consider using 'super' where appropiate to concatenate
 * behavior.
 */
function () external payable {
    buyTokens(msg.sender);
  }
/**
 * @dev fallback function ***DO NOT OVERRIDE***
 */