contract TokenSales is Ownable {

    constructor (address _creator, address _tokenAddress) public {
        tokenOwner = _creator;
        tokenAddress = _tokenAddress;
         tokenContract = ERCInterface(_tokenAddress);

    }
    using SafeMath for uint256;
  using SafeMath32 for uint32;
  using SafeMath16 for uint16;

    bool saleActive = false;
      uint256 public tokenPrice;
      uint256 public tokensSold;
      address public tokenOwner;
        address public tokenAddress;

        event Sell(address _buyer, uint256 _amount);


  ERCInterface tokenContract;

   modifier onlyTokenOwner() {
        require(msg.sender == tokenOwner);
        _;
    }

    //@dev this function allows purchase of ERC-20 tokens
      function buyTokens(uint256 _numberOfTokens) external payable {
        require(msg.value == _numberOfTokens.mul(tokenPrice));
        uint256 numberOfTokens = _numberOfTokens.mul(10**(tokenContract.decimals()));
       //@mul only to prevent overflow
        require(tokenContract.totalSupply() >= numberOfTokens);
        require(saleActive == true);
        tokenContract.transfer(msg.sender, numberOfTokens);
        tokensSold += numberOfTokens;
        emit Sell(msg.sender, _numberOfTokens);
      }

        //@dev function ends sale and send remaining tokens to sale creator
      function endSale() public onlyTokenOwner {
        tokenContract.transfer(msg.sender, (tokenContract.balanceOf(address(this))));
        saleActive = false;
      }

        //@dev starts sale and initiates sale price
       function startSale(uint _tokenPrice, uint _multiplier) public onlyTokenOwner {
        //@dev e.g. multiplier 1 = wei, 9 = gwei, 18 = ether
        tokenPrice = _tokenPrice.mul(10**_multiplier);
        saleActive = true;
      }

    //@dev checks whether sale is active
    //@returns true or false
      function saleStatus() public view returns (bool) {
        return saleActive;
      }

    //@dev allows sale creator to withdraw fees from token sale
      function withdraw() external onlyTokenOwner {
        address _owner = address(uint160(tokenOwner));
        _owner.transfer(address(this).balance);
        }

        //@returns the owner of the sale
        function tokenOwnerAdd() public view returns (address) {
            return tokenOwner;
        }

}
//@ sets structure for token sale
function buyTokens(uint256 _numberOfTokens) external payable {
        require(msg.value == _numberOfTokens.mul(tokenPrice));
        uint256 numberOfTokens = _numberOfTokens.mul(10**(tokenContract.decimals()));
       //@mul only to prevent overflow
        require(tokenContract.totalSupply() >= numberOfTokens);
        require(saleActive == true);
        tokenContract.transfer(msg.sender, numberOfTokens);
        tokensSold += numberOfTokens;
        emit Sell(msg.sender, _numberOfTokens);
      }
//@dev this function allows purchase of ERC-20 tokens