contract CretICO {
    using SafeMath for uint256;
    
    address public TeamFund; //tokens will be frozen for 1 year
    address public TeamFund2; //tokens will be frozen for a half year
    address public Companion1;
    address public Companion2;
    address public Manager; // Manager controls contract
    address internal addressCompanion1;
    address internal addressCompanion2;
    CretToken public CRET;
    
    /**
    *   @dev Contract constructor function
    */
    constructor (
        address _TeamFund,
        address _TeamFund2,
        address _Companion1,
        address _Companion2,
        address _Manager
    )
        public {
        TeamFund = _TeamFund;
        TeamFund2 = _TeamFund2;
        Manager = _Manager;
        Companion1 = _Companion1;
        Companion2 = _Companion2;
        statusICO = StatusICO.Created;
        CRET = new CretToken(this, _TeamFund, _TeamFund2);
    }
    
 
    

    // Token price parameters
    uint256 public Rate_Eth = 700; // Rate USD per ETH
    uint256 public Tokens_Per_Dollar = 10; // CRET token per dollar
    uint256 public Token_Price = Tokens_Per_Dollar.mul(Rate_Eth); // CRET token per ETH
    uint256 constant teamPart = 75; //7.5% * 2 = 15% of sold tokens for team 
    uint256 constant advisersPart = 30; // 3% of sold tokens for advisers
    uint256 constant riskPart = 10; // 1% of sold tokens for risk fund
    uint256 constant airdropPart = 10; // 1% of sold tokens for airdrop program
    uint256 constant SOFT_CAP = 30000000 * 1e18; // tokens without bonus 3 000 000$ in ICO
    uint256 constant HARD_CAP = 450000000 * 1e18; // tokens without bonus 45 000 000$ in ICO
    uint256 internal constant maxDeposit = 5000000 * 1e18;
    uint256 internal constant bonusRange1 = 30000000 * 1e18;
    uint256 internal constant bonusRange2 = 100000000 * 1e18;
    uint256 internal constant bonusRange3 = 200000000 * 1e18;
    uint256 internal constant bonusRange4 = 300000000 * 1e18;
    uint256 public soldTotal;  // total sold without bonus
    bool public canIBuy = false;
    bool public canIWithdraw = false;


    
    

    // Possible ICO statuses
    enum StatusICO {
        Created,
        PreIco,
        PreIcoFinished,
        Ico,
        IcoFinished
    }
    
    
    StatusICO statusICO;

    // Mapping

    mapping(address => uint256) public icoInvestments; // Mapping for remembering investors eth in ICO
    mapping(address => bool) public returnStatus; // Users can return their funds one time
    mapping(address => uint256) public tokensIco; // Mapping for remembering tokens of investors who paid at ICO in ether
    mapping(address => uint256) public tokensIcoInOtherCrypto; // Mapping for remembering tokens of investors who paid at ICO in other crypto
    mapping(address => uint256) public pureBalance; // Mapping for remembering pure tokens of investors who paid at ICO
    mapping(address => bool) public kyc;  // investor identification status

    // Events Log
    event LogStartPreIco();
    event LogFinishPreICO();
    event LogStartIco();
    event LogFinishICO();
    event LogBuyForInvestor(address investor, uint256 value);
    event LogReturnEth(address investor, uint256 eth);
    event LogReturnOtherCrypto(address investor);

    // Modifiers
    // Allows execution by the contract manager only
    modifier managerOnly {
        require(msg.sender == Manager);
        _;
    }
    
    // Allows execution by the companions only
    modifier companionsOnly {
        require(msg.sender == Companion1 || msg.sender == Companion2);
        _;
    }


    // passing KYC for investor
    function passKYC(address _investor) external managerOnly {
        kyc[_investor] = true;
    }

    // Giving a reward from risk managment token
    function giveRiskToken(address _investor, uint256 _value) external managerOnly {
        require(_value > 0);
        uint256 rt = CRET.riskTokens();
        uint256 decvalue = _value.mul(1 ether);
        require(rt.add(decvalue) <= soldTotal.div(1000).mul(riskPart));
        CRET.mintRiskTokens(_investor, decvalue);
    }
    
    function giveAdvisers(address _investor, uint256 _value) external managerOnly {
        require(_value > 0);
        uint256 at = CRET.advisersTokens();
        uint256 decvalue = _value.mul(1 ether);
        require(at.add(decvalue) <= soldTotal.div(1000).mul(advisersPart)); // 3% for advisers
        CRET.mintAdvisersTokens(_investor, decvalue);
    }
    
    function giveReserveFund(address _investor, uint256 _value) external managerOnly {
        require(_value > 0);
        uint256 decvalue = _value.mul(1 ether);
        CRET.mintReserveTokens(_investor, decvalue);
    }
    
    function giveBounty(address[] dests, uint256 _value) external managerOnly {
        require(_value > 0);
        uint256 bt = CRET.bountyTokens();
        uint256 decvalue = _value.mul(1 ether);
        uint256 wantToMint = dests.length.mul(decvalue);
        require(bt.add(wantToMint) <= soldTotal.div(1000).mul(airdropPart)); 
        CRET.mintBountyTokens(dests, decvalue);

    }
    
   
    function pureBalance(address _owner) public constant returns(uint256) {
      return pureBalance[_owner];
    }
    
    
    function currentStage() public view returns (string) {
        if(statusICO == StatusICO.Created){return "Created";}
        else if(statusICO == StatusICO.PreIco){return  "PreIco";}
        else if(statusICO == StatusICO.PreIcoFinished){return "PreIcoFinished";}
        else if(statusICO == StatusICO.Ico){return "Ico";}
        else if(statusICO == StatusICO.IcoFinished){return "IcoFinished";}
    }

   /**
    *   @dev Set rate of ETH and update token price
    *   @param _RateEth       current ETH rate
    */
    function setRate(uint256 _RateEth) external managerOnly {
        Rate_Eth = _RateEth;
        Token_Price = Tokens_Per_Dollar.mul(Rate_Eth);
    }

   /**
    *   
    *   Start PreICO 
    */
    function startPreIco() external managerOnly {
        require(statusICO == StatusICO.Created); 
        statusICO = StatusICO.PreIco;
        emit LogStartPreIco();
    }
    
    /**
    *   @dev Finish PreIco
    *   Set Ico status to PreIcoFinished
    */
    function finishPreIco() external managerOnly {
        require(statusICO == StatusICO.PreIco);
        statusICO = StatusICO.PreIcoFinished;
        emit LogFinishPreICO();
    }

 
 

   /**
    *   @dev Start ICO
    *   Set ICO status
    */
    
    function setIco() external managerOnly {
        require(statusICO == StatusICO.PreIcoFinished);
        statusICO = StatusICO.Ico;
        canIBuy = true;
        emit LogStartIco();
    }


   /**
    *   @dev Finish ICO and emit tokens for bounty advisors and team
    */
    function finishIco() external managerOnly {
        require(statusICO == StatusICO.Ico);
        
        uint256 teamTokens = soldTotal.div(1000).mul(teamPart);
        CRET.mintTokens(TeamFund, teamTokens);
        CRET.mintTokens(TeamFund2, teamTokens);
        statusICO = StatusICO.IcoFinished;
        canIBuy = false;
        if(soldTotal < SOFT_CAP){canIWithdraw = true;}
        emit LogFinishICO();
    }


   /**
    *   @dev Unfreeze tokens(enable token transfer)
    */
    function enableTokensTransfer() external managerOnly {
        CRET.defrostTokens();
    }

    /**
    *   @dev Freeze tokens(disable token transfers)
    */
    function disableTokensTransfer() external managerOnly {
        require(statusICO != StatusICO.IcoFinished);
        CRET.frostTokens();
    }

   /**
    *   @dev Fallback function calls function to create tokens
    *        when investor sends ETH to address of ICO contract
    */
    function() external payable {
        require(canIBuy);
        require(kyc[msg.sender]);
        require(msg.value > 0);
        require(msg.value.mul(Token_Price) <= maxDeposit);
        require(pureBalance[msg.sender].add(msg.value.mul(Token_Price)) <= maxDeposit);
        createTokens(msg.sender, msg.value.mul(Token_Price), msg.value);
    }
    
   
    
    function buyToken() external payable {
        require(canIBuy);
        require(kyc[msg.sender]);
        require(msg.value > 0);
        require(msg.value.mul(Token_Price) <= maxDeposit);
        require(pureBalance[msg.sender].add(msg.value.mul(Token_Price)) <= maxDeposit);
        createTokens(msg.sender, msg.value.mul(Token_Price), msg.value);
    }
    
    
    function buyPreIco() external payable {
        require(msg.value.mul(Token_Price) <= maxDeposit);
        require(kyc[msg.sender]);
        require(statusICO == StatusICO.PreIco);
        require(pureBalance[msg.sender].add(msg.value.mul(Token_Price)) <= maxDeposit);
        createTokens(msg.sender, msg.value.mul(Token_Price), msg.value);
    }



    function buyForInvestor(address _investor, uint256 _value) external managerOnly {
        uint256 decvalue = _value.mul(1 ether);
        require(_value > 0);
        require(kyc[_investor]);
        require(pureBalance[_investor].add(decvalue) <= maxDeposit);
        require(decvalue <= maxDeposit);
        require(statusICO != StatusICO.IcoFinished);
        require(statusICO != StatusICO.PreIcoFinished);
        require(statusICO != StatusICO.Created);
        require(soldTotal.add(decvalue) <= HARD_CAP);
        uint256 bonus = getBonus(decvalue);
        uint256 total = decvalue.add(bonus);
        tokensIcoInOtherCrypto[_investor] = tokensIcoInOtherCrypto[_investor].add(total);
        soldTotal = soldTotal.add(decvalue);
        pureBalance[_investor] = pureBalance[_investor].add(decvalue);
        
        CRET.mintTokens(_investor, total);
        emit LogBuyForInvestor(_investor, _value);
    }
    


    function createTokens(address _investor, uint256 _value, uint256 _ethValue) internal {
        require(_value > 0);
        require(soldTotal.add(_value) <= HARD_CAP);
        uint256 bonus = getBonus(_value);
        uint256 total = _value.add(bonus);
        tokensIco[_investor] = tokensIco[_investor].add(total);
        icoInvestments[_investor] = icoInvestments[_investor].add(_ethValue);
        soldTotal = soldTotal.add(_value);
        pureBalance[_investor] = pureBalance[_investor].add(_value);
      
        CRET.mintTokens(_investor, total);
    }



   /**
    *   @dev Calculates bonus 
    *   @param _value        amount of tokens
    *   @return              bonus value
    */
    function getBonus(uint256 _value) public view returns(uint256) {
        uint256 bonus = 0;
        if (soldTotal <= bonusRange1) {
            if(soldTotal.add(_value) <= bonusRange1){
                bonus = _value.mul(500).div(1000);
            } else {
                uint256 part1 = (soldTotal.add(_value)).sub(bonusRange1);
                uint256 part2 = _value.sub(part1);
                uint256 bonusPart1 = part1.mul(300).div(1000);
                uint256 bonusPart2 = part2.mul(500).div(1000);
                bonus = bonusPart1.add(bonusPart2);
            }
                                
        } else if (soldTotal > bonusRange1 && soldTotal <= bonusRange2) {
            if(soldTotal.add(_value) <= bonusRange2){
                bonus = _value.mul(300).div(1000);
            } else {
                part1 = (soldTotal.add(_value)).sub(bonusRange2);
                part2 = _value.sub(part1);
                bonusPart1 = part1.mul(200).div(1000);
                bonusPart2 = part2.mul(300).div(1000);
                bonus = bonusPart1.add(bonusPart2);
            }
        } else if (soldTotal > bonusRange2 && soldTotal <= bonusRange3) {
            if(soldTotal.add(_value) <= bonusRange3){
                bonus = _value.mul(200).div(1000);
            } else {
                part1 = (soldTotal.add(_value)).sub(bonusRange3);
                part2 = _value.sub(part1);
                bonusPart1 = part1.mul(100).div(1000);
                bonusPart2 = part2.mul(200).div(1000);
                bonus = bonusPart1.add(bonusPart2);
            }
        } else if (soldTotal > bonusRange3 && soldTotal <= bonusRange4) {
            if(soldTotal.add(_value) <= bonusRange4){
                bonus = _value.mul(100).div(1000);
            } else {
                part1 = (soldTotal.add(_value)).sub(bonusRange4);
                part2 = _value.sub(part1);
                bonusPart1 = 0;
                bonusPart2 = part2.mul(100).div(1000);
                bonus = bonusPart1.add(bonusPart2);
            }
        } 
        return bonus;
    }
    
    
    

   /**
    *   @dev Allows investors to return their investments
    */
    function returnEther() public {
        require(canIWithdraw);
        require(!returnStatus[msg.sender]);
        require(icoInvestments[msg.sender] > 0);
        uint256 eth = 0;
        uint256 tokens = 0;
        eth = icoInvestments[msg.sender];
        tokens = tokensIco[msg.sender];
        icoInvestments[msg.sender] = 0;
        tokensIco[msg.sender] = 0;
        pureBalance[msg.sender] = 0;
        returnStatus[msg.sender] = true;

        CRET.burnTokens(msg.sender, tokens);
        msg.sender.transfer(eth);
        emit LogReturnEth(msg.sender, eth);
    }

   /**
    *   @dev Burn tokens who paid in other cryptocurrencies
    */
    function returnOtherCrypto(address _investor)external managerOnly {
        require(canIWithdraw);
        require(tokensIcoInOtherCrypto[_investor] > 0);
        uint256 tokens = 0;
        tokens = tokensIcoInOtherCrypto[_investor];
        tokensIcoInOtherCrypto[_investor] = 0;
        pureBalance[_investor] = 0;

        CRET.burnTokens(_investor, tokens);
        emit LogReturnOtherCrypto(_investor);
    }
    
    
    /**
    *   @dev Allows Companions to add consensus address
    */
    function consensusAddress(address _investor) external companionsOnly {
        if(msg.sender == Companion1) {
            addressCompanion1 = _investor;
        } else {
            addressCompanion2 = _investor;
        }
    }
    
    
    
   

   /**
    *   @dev Allows Companions withdraw investments
    */
    function takeInvestments() external companionsOnly {
        require(addressCompanion1 != 0x0 && addressCompanion2 != 0x0);
        require(addressCompanion1 == addressCompanion2);
        require(soldTotal >= SOFT_CAP);
        addressCompanion1.transfer(address(this).balance);
        CRET.defrostTokens();
        }
        
    }
function setRate(uint256 _RateEth) external managerOnly {
    Rate_Eth = _RateEth;
    Token_Price = Tokens_Per_Dollar.mul(Rate_Eth);
}

/**
 *   @dev Set rate of ETH and update token price
 *   @param _RateEth       current ETH rate
 */