contract MtnCrowdsale is Ownable, Crowdsale {
    /*** CONSTANTS ***/
    uint256 public constant TOTAL_TOKEN_CAP = 500e6 * 1e18;   // 500 million * 1e18 - smallest unit of MTN token
    uint256 public constant CROWDSALE_TOKENS = 175e6 * 1e18;  // 175 million * 1e18 - presale and crowdsale tokens
    uint256 public constant TOTAL_TEAM_TOKENS = 170e6 * 1e18; // 170 million * 1e18 - team tokens
    uint256 public constant TEAM_TOKENS0 = 50e6 * 1e18;       // 50 million * 1e18 - team tokens, already vested
    uint256 public constant TEAM_TOKENS1 = 60e6 * 1e18;       // 60 million * 1e18 - team tokens, vesting over 2 years
    uint256 public constant TEAM_TOKENS2 = 60e6 * 1e18;       // 60 million * 1e18 - team tokens, vesting over 4 years
    uint256 public constant COMMUNITY_TOKENS = 155e6 * 1e18;  // 155 million * 1e18 - community tokens, vesting over 4 years

    uint256 public constant MAX_CONTRIBUTION_USD = 5000;      //  USD
    uint256 public constant USD_CENT_PER_TOKEN = 25;          // in cents - smallest unit of USD E.g. 100 = 1 USD

    uint256 public constant VESTING_DURATION_4Y = 4 years;
    uint256 public constant VESTING_DURATION_2Y = 2 years;

    // true if address is allowed to invest
    mapping(address => bool) public isWhitelisted;

    // allow managers to whitelist and confirm contributions by manager accounts
    // managers can be set and altered by owner, multiple manager accounts are possible
    mapping(address => bool) public isManager;

    uint256 public maxContributionInWei;
    uint256 public tokensMinted;                            // already minted tokens (maximally = TOKEN_CAP)
    bool public capReached;                                 // set to true when cap has been reached when minting tokens
    mapping(address => uint256) public totalInvestedPerAddress;

    address public beneficiaryWallet;

    // for convenience we store vesting wallets
    address public teamVesting2Years;
    address public teamVesting4Years;
    address public communityVesting4Years;

    /*** Tracking Crowdsale Stages ***/
    bool public isCrowdsaleOver;

    /*** EVENTS  ***/
    event ChangedManager(address manager, bool active);
    event PresaleMinted(address indexed beneficiary, uint256 tokenAmount);
    event ChangedInvestorWhitelisting(address indexed investor, bool whitelisted);

    /*** MODIFIERS ***/
    modifier onlyManager() {
        require(isManager[msg.sender]);
        _;
    }

    // trying to accompish using already existing variables to determine stage - prevents manual updating of the enum stage states
    modifier onlyPresalePhase() {
        require(now < startTime);
        _;
    }

    modifier onlyCrowdsalePhase() {
        require(now >= startTime && now < endTime && !isCrowdsaleOver);
        _;
    }

    modifier respectCrowdsaleCap(uint256 _amount) {
        require(tokensMinted.add(_amount) <= CROWDSALE_TOKENS);
        _;
    }

    modifier onlyCrowdSaleOver() {
        require(isCrowdsaleOver || now > endTime || capReached);
        _;
    }

    modifier onlyValidAddress(address _address) {
        require(_address != address(0));
        _;
    }

    /**
     * @dev Deploy MTN Token Crowdsale
     * @param _startTime uint256 Start time of the crowdsale
     * @param _endTime uint256 End time of the crowdsale
     * @param _usdPerEth uint256 issueing rate tokens per wei
     * @param _wallet address Wallet address of the crowdsale
     * @param _beneficiaryWallet address wallet holding team and community tokens
     */
    function MtnCrowdsale(
        uint256 _startTime,
        uint256 _endTime,
        uint256 _usdPerEth,
        address _wallet,
        address _beneficiaryWallet
        )
        Crowdsale(_startTime, _endTime, (_usdPerEth.mul(1e2)).div(USD_CENT_PER_TOKEN), _wallet)
        public
        onlyValidAddress(_beneficiaryWallet)
    {
        require(TOTAL_TOKEN_CAP == CROWDSALE_TOKENS.add(TOTAL_TEAM_TOKENS).add(COMMUNITY_TOKENS));
        require(TOTAL_TEAM_TOKENS == TEAM_TOKENS0.add(TEAM_TOKENS1).add(TEAM_TOKENS2));
        setManager(msg.sender, true);

        beneficiaryWallet = _beneficiaryWallet;

        maxContributionInWei = (MAX_CONTRIBUTION_USD.mul(1e18)).div(_usdPerEth);

        mintTeamTokens();
        mintCommunityTokens();
    }

    /**
     * @dev Create new instance of mtn token contract
     */
    function createTokenContract() internal returns (MintableToken) {
        return new MtnToken();
    }

    /**
     * @dev Set / alter manager / whitelister "account". This can be done from owner only
     * @param _manager address address of the manager to create/alter
     * @param _active bool flag that shows if the manager account is active
     */
    function setManager(address _manager, bool _active) public onlyOwner onlyValidAddress(_manager) {
        isManager[_manager] = _active;
        ChangedManager(_manager, _active);
    }

    /**
     * @dev whitelist investors to allow the direct investment of this crowdsale
     * @param _investor address address of the investor to be whitelisted
     */
    function whiteListInvestor(address _investor) public onlyManager onlyValidAddress(_investor) {
        isWhitelisted[_investor] = true;
        ChangedInvestorWhitelisting(_investor, true);
    }

    /**
     * @dev whitelist several investors via a batch method
     * @param _investors address[] array of addresses of the beneficiaries to receive tokens after they have been confirmed
     */
    function batchWhiteListInvestors(address[] _investors) public onlyManager {
        for (uint256 c; c < _investors.length; c = c.add(1)) {
            whiteListInvestor(_investors[c]);
        }
    }

    /**
     * @dev unwhitelist investor from participating in the crowdsale
     * @param _investor address address of the investor to disallowed participation
     */
    function unWhiteListInvestor(address _investor) public onlyManager onlyValidAddress(_investor) {
        isWhitelisted[_investor] = false;
        ChangedInvestorWhitelisting(_investor, false);
    }

   /**
    * @dev onlyOwner allowed to mint tokens, respecting the cap, and only before the crowdsale starts
    * @param _beneficiary address
    * @param _amount uint256
    */
    function mintTokenPreSale(address _beneficiary, uint256 _amount) public onlyOwner onlyPresalePhase onlyValidAddress(_beneficiary) respectCrowdsaleCap(_amount) {
        require(_amount > 0);

        tokensMinted = tokensMinted.add(_amount);
        token.mint(_beneficiary, _amount);
        PresaleMinted(_beneficiary, _amount);
    }

   /**
    * @dev onlyOwner allowed to handle batch presale minting
    * @param _beneficiaries address[]
    * @param _amounts uint256[]
    */
    function batchMintTokenPresale(address[] _beneficiaries, uint256[] _amounts) public onlyOwner onlyPresalePhase {
        require(_beneficiaries.length == _amounts.length);

        for (uint256 i; i < _beneficiaries.length; i = i.add(1)) {
            mintTokenPreSale(_beneficiaries[i], _amounts[i]);
        }
    }

   /**
    * @dev override core functionality by whitelist check
    * @param _beneficiary address
    */
    function buyTokens(address _beneficiary) public payable onlyCrowdsalePhase onlyValidAddress(_beneficiary) {
        require(isWhitelisted[msg.sender]);
        require(validPurchase());

        uint256 overflowTokens;
        uint256 refundWeiAmount;
        bool overMaxInvestmentAllowed;

        uint256 investedWeiAmount = msg.value;

        // Is this specific investment over the MAX_CONTRIBUTION_USD limit?
        // if so, calcuate wei refunded and tokens to mint for the allowed investment amount
        uint256 totalInvestedWeiAmount = investedWeiAmount.add(totalInvestedPerAddress[msg.sender]);
        if (totalInvestedWeiAmount > maxContributionInWei) {
            overMaxInvestmentAllowed = true;
            refundWeiAmount = totalInvestedWeiAmount.sub(maxContributionInWei);
            investedWeiAmount = investedWeiAmount.sub(refundWeiAmount);
        }

        uint256 tokenAmount = investedWeiAmount.mul(rate);
        uint256 tempMintedTokens = tokensMinted.add(tokenAmount); // gas optimization, do not inline twice

        // check to see if this purchase sets it over the crowdsale token cap
        // if so, calculate tokens to mint, then refund the remaining ether investment
        if (tempMintedTokens >= CROWDSALE_TOKENS) {
            capReached = true;
            overflowTokens = tempMintedTokens.sub(CROWDSALE_TOKENS);
            tokenAmount = tokenAmount.sub(overflowTokens);
            refundWeiAmount = overflowTokens.div(rate);
            investedWeiAmount = investedWeiAmount.sub(refundWeiAmount);
        }

        weiRaised = weiRaised.add(investedWeiAmount);

        tokensMinted = tokensMinted.add(tokenAmount);
        TokenPurchase(msg.sender, _beneficiary, investedWeiAmount, tokenAmount);
        totalInvestedPerAddress[msg.sender] = totalInvestedPerAddress[msg.sender].add(investedWeiAmount);
        token.mint(_beneficiary, tokenAmount);

        // if investor breached cap and has remaining ether not invested
        // refund remaining ether to investor
        if (capReached || overMaxInvestmentAllowed) {
            msg.sender.transfer(refundWeiAmount);
            wallet.transfer(investedWeiAmount);
        } else {
            forwardFunds();
        }
    }

   /**
    * @dev onlyOwner to close Crowdsale manually if before endTime
    */
    function closeCrowdsale() public onlyOwner onlyCrowdsalePhase {
        isCrowdsaleOver = true;
    }

   /**
    * @dev onlyOwner allows tokens to be tradeable
    */
    function finalize() public onlyOwner onlyCrowdSaleOver {
        // do not allow new owner to mint further tokens & unpause token to allow trading
        MintableToken(token).finishMinting();
        PausableToken(token).unpause();
    }

    /*** INTERNAL/PRIVATE FUNCTIONS ***/

    /**
     * @dev allows contract owner to mint all team tokens per TEAM_TOKENS and have 50m immediately available, 60m 2 years vested, and 60m over 4 years vesting
     */
    function mintTeamTokens() private {
        token.mint(beneficiaryWallet, TEAM_TOKENS0);

        TokenVesting newVault1 = new TokenVesting(beneficiaryWallet, now, 0, VESTING_DURATION_2Y, false);
        teamVesting2Years = address(newVault1); // for convenience we keep them in storage so that they are easily accessible via MEW or etherscan
        token.mint(address(newVault1), TEAM_TOKENS1);

        TokenVesting newVault2 = new TokenVesting(beneficiaryWallet, now, 0, VESTING_DURATION_4Y, false);
        teamVesting4Years = address(newVault2); // for convenience we keep them in storage so that they are easily accessible via MEW or etherscan
        token.mint(address(newVault2), TEAM_TOKENS2);
    }

    /**
     * @dev allows contract owner to mint all community tokens per COMMUNITY_TOKENS and have the vested to the beneficiaryWallet
     */
    function mintCommunityTokens() private {
        TokenVesting newVault = new TokenVesting(beneficiaryWallet, now, 0, VESTING_DURATION_4Y, false);
        communityVesting4Years = address(newVault); // for convenience we keep them in storage so that they are easily accessible via MEW or etherscan
        token.mint(address(newVault), COMMUNITY_TOKENS);
    }

    /**
     * @dev extend base functionality with min investment amount
     */
    function validPurchase() internal view respectCrowdsaleCap(0) returns (bool) {
        require(!capReached);
        require(totalInvestedPerAddress[msg.sender] < maxContributionInWei);

        return super.validPurchase();
    }
}
function batchWhiteListInvestors(address[] _investors) public onlyManager {
    for (uint256 c; c < _investors.length; c = c.add(1)) {
        whiteListInvestor(_investors[c]);
    }
}

/**
 * @dev whitelist several investors via a batch method
 * @param _investors address[] array of addresses of the beneficiaries to receive tokens after they have been confirmed
 */