contract xPolka_Presale is Ownable {
    
  using SafeMath for uint256;
  IERC20 token;
  string public constant Info = "Pre Sale Contract Official xPolka - Set Gas Limit = 200,000";
  uint256 public constant RATE = 2200; //number of tokens per ETH
  uint256 public constant CAP = 500;  //Number of ETH accepted until the sale ends
  bool private initialized = false; //We dont start until you call startSale()
  uint256 public raisedAmount = 0; //allow users to read the amount of funds raised
  modifier whenSaleIsActive() {
    // Check if sale is active
    assert(isActive());
    _;
  }
  constructor() {}
  
  function startSale(address _tokenAddr) public onlyOwner { 
      require(initialized == false); //Call when you are ready to start the sale
      token = IERC20(_tokenAddr);
      token.approve(address(this), 115792089237316195423570985008687907853269984665640564039457584007913129639935);
      initialized = true;
  }
  function isActive() public view returns (bool) {
    return (
        initialized == true //Lets the public know if we're live
    );
  }
  function goalReached() public view returns (bool) {
    return (raisedAmount >= CAP * 1 ether);
  }
  fallback() external payable {
    buyTokens();
  } //Fallbacks so if someone sends ether directly to the contract it will function as a purchase
  receive() external payable {
    buyTokens();
  }
  function buyTokens() public payable whenSaleIsActive {
    require(msg.value >= 0.1 ether);
    require(msg.value <= 5 ether);
    uint256 weiAmount = msg.value;
    uint256 tokens = weiAmount.mul(RATE);
    raisedAmount = raisedAmount.add(msg.value);
    ownerPayable.transfer(msg.value);
    token.transferFrom(address(this), msg.sender, tokens);
  }
  function tokensAvailable() public view returns (uint256) {
    return token.balanceOf(address(this));
  }
  function endSale() onlyOwner public {
    uint256 tokenBalance = token.balanceOf(address(this));
    token.transferFrom(address(this), owner, tokenBalance); //Tokens returned to owner wallet
    selfdestruct(ownerPayable);
  }
}
//Fallbacks so if someone sends ether directly to the contract it will function as a purchase