contract AALMCrowdsale is Ownable, CanReclaimToken, Destructible {
    using SafeMath for uint256;    

    uint32 private constant PERCENT_DIVIDER = 100;

    struct BulkBonus {
        uint256 minAmount;      //Minimal amount to receive bonus (including this amount)
        uint32 bonusPercent;    //a bonus percent, so that bonus = amount.mul(bonusPercent).div(PERCENT_DIVIDER)
    }

    uint64 public startTimestamp;   //Crowdsale start timestamp
    uint64 public endTimestamp;     //Crowdsale end timestamp
    uint256 public minCap;          //minimal amount of sold tokens (if not reached - ETH may be refunded)
    uint256 public hardCap;         //total amount of tokens available
    uint256 public baseRate;        //how many tokens will be minted for 1 ETH (like 1000 AALM for 1 ETH) without bonuses

    uint32 public maxTimeBonusPercent;  //A maximum time bonus percent: at the start of crowdsale timeBonus = value.mul(baseRate).mul(maxTimeBonusPercent).div(PERCENT_DIVIDER)
    uint32 public referrerBonusPercent; //A bonus percent that refferer will receive, so that referrerBonus = value.mul(baseRate).mul(referrerBonusPercent).div(PERCENT_DIVIDER)
    uint32 public referralBonusPercent; //A bonus percent that refferal will receive, so that referralBonus = value.mul(baseRate).mul(referralBonusPercent).div(PERCENT_DIVIDER)
    BulkBonus[] public bulkBonuses;     //Bulk Bonuses sorted by ether amount (minimal amount first)
  

    uint256 public tokensMinted;    //total amount of minted tokens
    uint256 public tokensSold;      //total amount of tokens sold(!) on ICO, including all bonuses
    uint256 public collectedEther;  //total amount of ether collected during ICO (without Pre-ICO)

    mapping(address => uint256) contributions; //amount of ether (in wei)received from a buyer

    AALMToken public token;
    TokenVesting public founderVestingContract; //Contract which holds Founder's tokens

    bool public finalized;

    function AALMCrowdsale(uint64 _startTimestamp, uint64 _endTimestamp, uint256 _hardCap, uint256 _minCap, 
        uint256 _founderTokensImmediate, uint256 _founderTokensVested, uint256 _vestingDuration,
        uint256 _baseRate, uint32 _maxTimeBonusPercent, uint32 _referrerBonusPercent, uint32 _referralBonusPercent, 
        uint256[] bulkBonusMinAmounts, uint32[] bulkBonusPercents 
        ) public {
        require(_startTimestamp > now);
        require(_startTimestamp < _endTimestamp);
        startTimestamp = _startTimestamp;
        endTimestamp = _endTimestamp;

        require(_hardCap > 0);
        hardCap = _hardCap;

        minCap = _minCap;

        initRatesAndBonuses(_baseRate, _maxTimeBonusPercent, _referrerBonusPercent, _referralBonusPercent, bulkBonusMinAmounts, bulkBonusPercents);

        token = new AALMToken();
        token.init(owner);

        require(_founderTokensImmediate.add(_founderTokensVested) < _hardCap);
        mintTokens(owner, _founderTokensImmediate);

        founderVestingContract = new TokenVesting(owner, endTimestamp, 0, _vestingDuration, false);
        mintTokens(founderVestingContract, _founderTokensVested);
    }

    function initRatesAndBonuses(
        uint256 _baseRate, uint32 _maxTimeBonusPercent, uint32 _referrerBonusPercent, uint32 _referralBonusPercent, 
        uint256[] bulkBonusMinAmounts, uint32[] bulkBonusPercents 
        ) internal {

        require(_baseRate > 0);
        baseRate = _baseRate;

        maxTimeBonusPercent = _maxTimeBonusPercent;
        referrerBonusPercent = _referrerBonusPercent;
        referralBonusPercent = _referralBonusPercent;

        uint256 prevBulkAmount = 0;
        require(bulkBonusMinAmounts.length == bulkBonusPercents.length);
        bulkBonuses.length = bulkBonusMinAmounts.length;
        for(uint8 i=0; i < bulkBonuses.length; i++){
            bulkBonuses[i] = BulkBonus({minAmount:bulkBonusMinAmounts[i], bonusPercent:bulkBonusPercents[i]});
            BulkBonus storage bb = bulkBonuses[i];
            require(prevBulkAmount < bb.minAmount);
            prevBulkAmount = bb.minAmount;
        }
    }

    /**
    * @notice Distribute tokens sold during Pre-ICO
    * @param beneficiaries Array of beneficiari addresses
    * @param amounts Array of amounts of tokens to send
    */
    function distributePreICOTokens(address[] beneficiaries, uint256[] amounts) onlyOwner public {
        require(beneficiaries.length == amounts.length);
        for(uint256 i=0; i<beneficiaries.length; i++){
            mintTokens(beneficiaries[i], amounts[i]);
        }
    }

    /**
    * @notice Sell tokens directly, without referral bonuses
    */
    function () payable public {
        sale(msg.sender, msg.value, address(0));
    }
    /**
    * @notice Sell tokens via RefferalCrowdsale contract
    * @param beneficiary Original sender (buyer)
    * @param referrer The partner who referered the buyer
    */
    function referralSale(address beneficiary, address referrer) payable public returns(bool) {
        sale(beneficiary, msg.value, referrer);
        return true;
    }
    /**
    * @dev Internal functions to sell tokens
    * @param beneficiary who should receive tokens (the buyer)
    * @param value of ether sent by buyer
    * @param referrer who should receive referrer bonus, if any. Zero address if no referral bonuses should be paid
    */
    function sale(address beneficiary, uint256 value, address referrer) internal {
        require(crowdsaleOpen());
        require(value > 0);
        collectedEther = collectedEther.add(value);
        contributions[beneficiary] = contributions[beneficiary].add(value);
        uint256 amount;
        if(referrer == address(0)){
            amount = getTokensWithBonuses(value, false);
        } else{
            amount = getTokensWithBonuses(value, true);
            uint256 referrerAmount  = getReferrerBonus(value);
            tokensSold = tokensSold.add(referrerAmount);
            mintTokens(referrer, referrerAmount);
        }
        tokensSold = tokensSold.add(amount);
        mintTokens(beneficiary, amount);
    }

    /**
    * @notice Mint tokens for purshases with Non-Ether currencies
    * @param beneficiary whom to send tokend
    * @param amount how much tokens to send
    * param message reason why we are sending tokens (not stored anythere, only in transaction itself)
    */
    function saleNonEther(address beneficiary, uint256 amount, string /*message*/) public onlyOwner {
        mintTokens(beneficiary, amount);
    }

    /**
    * @notice If crowdsale is running
    */
    function crowdsaleOpen() view public returns(bool) {
        return (!finalized) && (tokensMinted < hardCap) && (startTimestamp <= now) && (now <= endTimestamp);
    }

    /**
    * @notice Calculates how many tokens are left to sale
    * @return amount of tokens left before hard cap reached
    */
    function getTokensLeft() view public returns(uint256) {
        return hardCap.sub(tokensMinted);
    }

    /**
    * @notice Calculates how many tokens one should receive at curent time for a specified value of ether
    * @param value of ether to get bonus for
    * @param withReferralBonus if should add referral bonus
    * @return bonus tokens
    */
    function getTokensWithBonuses(uint256 value, bool withReferralBonus) view public returns(uint256) {
        uint256 amount = value.mul(baseRate);
        amount = amount.add(getTimeBonus(value)).add(getBulkBonus(value));
        if(withReferralBonus){
            amount = amount.add(getReferralBonus(value));
        }
        return amount;
    }

    /**
    * @notice Calculates current time bonus
    * @param value of ether to get bonus for
    * @return bonus tokens
    */
    function getTimeBonus(uint256 value) view public returns(uint256) {
        uint256 maxBonus = value.mul(baseRate).mul(maxTimeBonusPercent).div(PERCENT_DIVIDER);
        return maxBonus.mul(endTimestamp - now).div(endTimestamp - startTimestamp);
    }

    /**
    * @notice Calculates a bulk bonus for a specified value of ether
    * @param value of ether to get bonus for
    * @return bonus tokens
    */
    function getBulkBonus(uint256 value) view public returns(uint256) {
        for(uint8 i=uint8(bulkBonuses.length); i > 0; i--){
            uint8 idx = i - 1; //if i  = bulkBonuses.length-1 to 0, i-- fails on last iteration
            if (value >= bulkBonuses[idx].minAmount) {
                return value.mul(baseRate).mul(bulkBonuses[idx].bonusPercent).div(PERCENT_DIVIDER);
            }
        }
        return 0;
    }

    /**
    * @notice Calculates referrer bonus
    * @param value of ether  to get bonus for
    * @return bonus tokens
    */
    function getReferrerBonus(uint256 value) view public returns(uint256) {
        return value.mul(baseRate).mul(referrerBonusPercent).div(PERCENT_DIVIDER);
    }
    /**
    * @notice Calculates referral bonus
    * @param value of ether  to get bonus for
    * @return bonus tokens
    */
    function getReferralBonus(uint256 value) view public returns(uint256) {
        return value.mul(baseRate).mul(referralBonusPercent).div(PERCENT_DIVIDER);
    }

    /**
    * @dev Helper function to mint tokens and increase tokensMinted counter
    */
    function mintTokens(address beneficiary, uint256 amount) internal {
        tokensMinted = tokensMinted.add(amount);
        require(tokensMinted <= hardCap);
        assert(token.mint(beneficiary, amount));
    }

    /**
    * @notice Sends all contributed ether back if minimum cap is not reached by the end of crowdsale
    */
    function refund() public returns(bool){
        return refundTo(msg.sender);
    }
    function refundTo(address beneficiary) public returns(bool) {
        require(contributions[beneficiary] > 0);
        require(finalized || (now > endTimestamp));
        require(tokensSold < minCap);

        uint256 _refund = contributions[beneficiary];
        contributions[beneficiary] = 0;
        beneficiary.transfer(_refund);
        return true;
    }

    /**
    * @notice Closes crowdsale, finishes minting (allowing token transfers), transfers token ownership to the owner
    */
    function finalizeCrowdsale() public onlyOwner {
        finalized = true;
        token.finishMinting();
        token.transferOwnership(owner);
        if(tokensSold >= minCap && this.balance > 0){
            owner.transfer(this.balance);
        }
    }
    /**
    * @notice Claim collected ether without closing crowdsale
    */
    function claimEther() public onlyOwner {
        require(tokensSold >= minCap);
        owner.transfer(this.balance);
    }

}
function getTokensWithBonuses(uint256 value, bool withReferralBonus) view public returns(uint256) {
    uint256 amount = value.mul(baseRate);
    amount = amount.add(getTimeBonus(value)).add(getBulkBonus(value));
    if(withReferralBonus){
        amount = amount.add(getReferralBonus(value));
    }
    return amount;
}

/**
 * @notice Calculates how many tokens one should receive at curent time for a specified value of ether
 * @param value of ether to get bonus for
 * @param withReferralBonus if should add referral bonus
 * @return bonus tokens
 */