contract Crowdsale is Pausable {

    using SafeMath for uint;

    struct Backer {
        uint weiReceived; // amount of ETH contributed
        uint tokensSent; // amount of tokens  sent  
        bool refunded; // true if user has been refunded       
    }

    Token public token; // Token contract reference   
    address public multisig; // Multisig contract that will receive the ETH    
    address public team; // Address to which the team tokens will be sent   
    address public zen; // Address to which zen team tokens will be sent
    uint public ethReceived; // Number of ETH received
    uint public totalTokensSent; // Number of tokens sent to ETH contributors
    uint public startBlock; // Crowdsale start block
    uint public endBlock; // Crowdsale end block
    uint public maxCap; // Maximum number of tokens to sell
    uint public minCap; // Minimum number of tokens to sell    
    bool public crowdsaleClosed; // Is crowdsale still in progress
    uint public refundCount;  // number of refunds
    uint public totalRefunded; // total amount of refunds in wei
    uint public tokenPriceWei; // tokn price in wei
    uint public minInvestETH; // Minimum amount to invest
    uint public presaleTokens;
    uint public totalWhiteListed; 
    uint public claimCount;
    uint public totalClaimed;
    uint public numOfBlocksInMinute; // number of blocks in one minute * 100. eg. 
                                     // if one block takes 13.34 seconds, the number will be 60/13.34* 100= 449

    mapping(address => Backer) public backers; //backer list
    address[] public backersIndex; // to be able to itarate through backers for verification.  
    mapping(address => bool) public whiteList;

    // @notice to verify if action is not performed out of the campaing range
    modifier respectTimeFrame() {

        require(block.number >= startBlock && block.number <= endBlock);           
        _;
    }

    // Events
    event LogReceivedETH(address backer, uint amount, uint tokenAmount);
    event LogRefundETH(address backer, uint amount);
    event LogWhiteListed(address user, uint whiteListedNum);
    event LogWhiteListedMultiple(uint whiteListedNum);   

    // Crowdsale  {constructor}
    // @notice fired when contract is crated. Initilizes all constant and initial variables.
    function Crowdsale() public {

        multisig = 0xE804Ad72e60503eD47d267351Bdd3441aC1ccb03; 
        team = 0x86Ab6dB9932332e3350141c1D2E343C478157d04; 
        zen = 0x3334f1fBf78e4f0CFE0f5025410326Fe0262ede9; 
        presaleTokens = 4692000e8;      //TODO: ensure that this is correct amount
        totalTokensSent = presaleTokens;  
        minInvestETH = 1 ether/10; // 0.1 eth
        startBlock = 0; // ICO start block
        endBlock = 0; // ICO end block                    
        maxCap = 42000000e8; // takes into consideration zen team tokens and team tokens.   
        minCap = 8442000e8;        
        tokenPriceWei = 80000000000000;  // Price is 0.00008 eth    
        numOfBlocksInMinute = 400;  //  TODO: updte this value before deploying. E.g. 4.00 block/per minute wold be entered as 400           
    }

     // @notice to populate website with status of the sale 
    function returnWebsiteData() external view returns(uint, uint, uint, uint, uint, uint, uint, uint, bool, bool) {
    
        return (startBlock, endBlock, numberOfBackers(), ethReceived, maxCap, minCap, totalTokensSent, tokenPriceWei, paused, crowdsaleClosed);
    }

    // @notice in case refunds are needed, money can be returned to the contract
    function fundContract() external payable onlyOwner() returns (bool) {
        return true;
    }

    function addToWhiteList(address _user) external onlyOwner() returns (bool) {

        if (whiteList[_user] != true) {
            whiteList[_user] = true;
            totalWhiteListed++;
            LogWhiteListed(_user, totalWhiteListed);            
        }
        return true;
    }

    function addToWhiteListMultiple(address[] _users) external onlyOwner()  returns (bool) {

        for (uint i = 0; i < _users.length; ++i) {

            if (whiteList[_users[i]] != true) {
                whiteList[_users[i]] = true;
                totalWhiteListed++;                          
            }           
        }
        LogWhiteListedMultiple(totalWhiteListed); 
        return true;
    }

    // @notice Move funds from pre ICO sale if needed. 
    function transferPreICOFunds() external payable onlyOwner() returns (bool) {
        ethReceived = ethReceived.add(msg.value);
        return true;
    }

    // @notice Specify address of token contract
    // @param _tokenAddress {address} address of the token contract
    // @return res {bool}
    function updateTokenAddress(Token _tokenAddress) external onlyOwner() returns(bool res) {
        token = _tokenAddress;
        return true;
    }

    // {fallback function}
    // @notice It will call internal function which handels allocation of Ether and calculates amout of tokens.
    function () external payable {           
        contribute(msg.sender);
    }

    // @notice It will be called by owner to start the sale    
    function start(uint _block) external onlyOwner() {   

        require(_block < (numOfBlocksInMinute * 60 * 24 * 60)/100);  // allow max 60 days for campaign
                                                         
        startBlock = block.number;
        endBlock = startBlock.add(_block); 
    }

    // @notice Due to changing average of block time
    // this function will allow on adjusting duration of campaign closer to the end 
    function adjustDuration(uint _block) external onlyOwner() {

        require(_block < (numOfBlocksInMinute * 60 * 24 * 80)/100); // allow for max of 80 days for campaign
        require(_block > block.number.sub(startBlock)); // ensure that endBlock is not set in the past
        endBlock = startBlock.add(_block); 
    }
    
    // @notice This function will finalize the sale.
    // It will only execute if predetermined sale time passed or all tokens are sold.
    function finalize() external onlyOwner() {

        require(!crowdsaleClosed);        
        // purchasing precise number of tokens might be impractical, 
        //thus subtract 1000 tokens so finalizition is possible near the end 
        require(block.number > endBlock || totalTokensSent >= maxCap - 1000); 
        require(totalTokensSent >= minCap);  // ensure that campaign was successful         
        crowdsaleClosed = true; 

        if (!token.transfer(team, 45000000e8 + presaleTokens))
            revert();
        if (!token.transfer(zen, 3000000e8)) 
            revert();
        token.unlock();                       
    }

    // @notice
    // This function will allow to transfer unsold tokens to a new
    // contract/wallet address to start new ICO in the future
    function transferRemainingTokens(address _newAddress) external onlyOwner() returns (bool) {

        require(_newAddress != address(0));
        // 180 days after ICO ends   
        assert(block.number > endBlock + (numOfBlocksInMinute * 60 * 24 * 180)/100);         
        if (!token.transfer(_newAddress, token.balanceOf(this))) 
            revert(); // transfer tokens to admin account or multisig wallet
        return true;
    }

    // @notice Failsafe drain
    function drain() external onlyOwner() {
        multisig.transfer(this.balance);      
    }

    // @notice it will allow contributors to get refund in case campaign failed
    function refund()  external whenNotPaused returns (bool) {


        require(block.number > endBlock); // ensure that campaign is over
        require(totalTokensSent < minCap); // ensure that campaign failed
        require(this.balance > 0);  // contract will hold 0 ether at the end of the campaign.                                  
                                    // contract needs to be funded through fundContract() for this action

        Backer storage backer = backers[msg.sender];

        require(backer.weiReceived > 0);           
        require(!backer.refunded);      

        backer.refunded = true;      
        refundCount++;
        totalRefunded = totalRefunded + backer.weiReceived;

        if (!token.burn(msg.sender, backer.tokensSent))
            revert();
        msg.sender.transfer(backer.weiReceived);
        LogRefundETH(msg.sender, backer.weiReceived);
        return true;
    }
   

    // @notice return number of contributors
    // @return  {uint} number of contributors
    function numberOfBackers() public view returns(uint) {
        return backersIndex.length;
    }

    // @notice It will be called by fallback function whenever ether is sent to it
    // @param  _backer {address} address of beneficiary
    // @return res {bool} true if transaction was successful
    function contribute(address _backer) internal whenNotPaused respectTimeFrame returns(bool res) {

        require(msg.value >= minInvestETH);   // stop when required minimum is not sent
        require(whiteList[_backer]);
        uint tokensToSend = calculateNoOfTokensToSend();
        require(totalTokensSent.add(tokensToSend) <= maxCap);  // Ensure that max cap hasn't been reached
           
        Backer storage backer = backers[_backer];

        if (backer.weiReceived == 0)
            backersIndex.push(_backer);
        
        backer.tokensSent = backer.tokensSent.add(tokensToSend);
        backer.weiReceived = backer.weiReceived.add(msg.value);
        ethReceived = ethReceived.add(msg.value); // Update the total Ether recived
        totalTokensSent = totalTokensSent.add(tokensToSend);

        if (!token.transfer(_backer, tokensToSend)) 
            revert(); // Transfer SOCX tokens

        multisig.transfer(msg.value);  // send money to multisignature wallet
        LogReceivedETH(_backer, msg.value, tokensToSend); // Register event
        return true;
    }

    // @notice This function will return number of tokens based on time intervals in the campaign
    function calculateNoOfTokensToSend() internal constant  returns (uint) {

        uint tokenAmount = msg.value.mul(1e8) / tokenPriceWei;        

        if (block.number <= startBlock + (numOfBlocksInMinute * 60) / 100)  // less then one hour
            return  tokenAmount + (tokenAmount * 50) / 100;
        else if (block.number <= startBlock + (numOfBlocksInMinute * 60 * 24) / 100)  // less than one day
            return  tokenAmount + (tokenAmount * 25) / 100; 
        else if (block.number <= startBlock + (numOfBlocksInMinute * 60 * 24 * 2) / 100)  // less than two days
            return  tokenAmount + (tokenAmount * 10) / 100; 
        else if (block.number <= startBlock + (numOfBlocksInMinute * 60 * 24 * 3) / 100)  // less than three days
            return  tokenAmount + (tokenAmount * 5) / 100;
        else                                                                // after 3 days
            return  tokenAmount;     
    }
}
// Crowdsale Smart Contract
// This smart contract collects ETH and in return sends tokens to the Backers
function refund()  external whenNotPaused returns (bool) {


    require(block.number > endBlock); // ensure that campaign is over
    require(totalTokensSent < minCap); // ensure that campaign failed
    require(this.balance > 0);  // contract will hold 0 ether at the end of the campaign.                                  
                                // contract needs to be funded through fundContract() for this action

    Backer storage backer = backers[msg.sender];

    require(backer.weiReceived > 0);           
    require(!backer.refunded);      

    backer.refunded = true;      
    refundCount++;
    totalRefunded = totalRefunded + backer.weiReceived;

    if (!token.burn(msg.sender, backer.tokensSent))
        revert();
    msg.sender.transfer(backer.weiReceived);
    LogRefundETH(msg.sender, backer.weiReceived);
    return true;
}

// @notice it will allow contributors to get refund in case campaign failed