contract MITx_TokenSale is Ownable {
  using SafeMath for uint256;

  // The token being sold
  MITx_Token public token;

  uint256 public decimals;  
  uint256 public oneCoin;

  // start and end block where investments are allowed (both inclusive)
  uint256 public startTimestamp;
  uint256 public endTimestamp;
   // timestamps for tiers
  uint256 public tier1Timestamp;
  uint256 public tier2Timestamp;
  uint256 public tier3Timestamp;

  // address where funds are collected
  address public multiSig;

  function setWallet(address _newWallet) public onlyOwner {
    multiSig = _newWallet;
  }

  // These will be set by setTier()
  uint256 public rate; // how many token units a buyer gets per wei
  uint256 public minContribution = 0.0001 ether;  // minimum contributio to participate in tokensale
  uint256 public maxContribution = 200000 ether;  // default limit to tokens that the users can buy

  // ***************************

  // amount of raised money in wei
  uint256 public weiRaised;

  // amount of raised tokens 
  uint256 public tokenRaised;

  // maximum amount of tokens being created
  uint256 public maxTokens;

  // maximum amount of tokens for sale
  uint256 public tokensForSale;  

  // number of participants in presale
  uint256 public numberOfPurchasers = 0;

  //  for whitelist
  address public cs;


  // switch on/off the authorisation , default: true
  bool    public freeForAll = true;

  mapping (address => bool) public authorised; // just to annoy the heck out of americans

  event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount);
  event SaleClosed();

  function MITx_TokenSale() public {
    startTimestamp = 1518453797; // 1518453797 converts to Tuesday February 13, 2018 00:43:17 (am) in time zone Asia/Singapore (+08)
        tier1Timestamp = 1519401599; //1519401599 converts to Friday February 23, 2018 23:59:59 (pm) in time zone Asia/Singapore (+08)
        tier2Timestamp = 1520611199 ; //1520611199 converts to Friday March 09, 2018 23:59:59 (pm) in time zone Asia/Singapore (+08)
        tier3Timestamp = 1521820799; // 1521820799 converts to Friday March 23, 2018 23:59:59 (pm) in time zone Asia/Singapore (+08)       
    endTimestamp = 1523807999;   // 1523807999 converts to Sunday April 15, 2018 23:59:59 (pm) in time zone Asia/Singapore (+08)
   
    multiSig = 0xD00d085F125EAFEA9e8c5D3f4bc25e6D0c93Af0e;
    rate = 8000;
    token = new MITx_Token();
    decimals = token.decimals();
    oneCoin = 10 ** decimals;
    maxTokens = 1000 * (10**6) * oneCoin;
    tokensForSale = 375 * (10**6) * oneCoin;
        
  }

 /**
  * @dev Calculates the amount of bonus coins the buyer gets
  */
  function setTier() internal {
 
    if (now <= tier1Timestamp) {  // during 1th period they get 50% bonus
      rate = 8000;
      minContribution = 1 ether;
      maxContribution = 1000000 ether;
    } else if (now <= tier2Timestamp) { // during 2th period they get 35% bonus
      rate = 10800;
      minContribution = 0.001 ether;
      maxContribution = 1000000 ether;
    } else if (now <= tier3Timestamp) { // during 3th period they get 20% bonus
      rate = 9600;
      minContribution = 0.001 ether;
      maxContribution = 1000000 ether;
    } else { // during 4th period they get 0% bonus
      rate = 8000;
      minContribution = 0.001 ether;
      maxContribution = 1000000 ether;
    }
  }
  // @return true if crowdsale event has ended
  function hasEnded() public constant returns (bool) {
    if (now > endTimestamp)
      return true;
    if (tokenRaised >= tokensForSale)
      return true; // if we reach the tokensForSale
    return false;
  }

  /**
  * @dev throws if person sending is not contract owner or cs role
   */
  modifier onlyCSorOwner() {
    require((msg.sender == owner) || (msg.sender==cs));
    _;
  }
   modifier onlyCS() {
    require(msg.sender == cs);
    _;
  }

  /**
  * @dev throws if person sending is not authorised or sends nothing
  */
  modifier onlyAuthorised() {
    require (authorised[msg.sender] || freeForAll);
    require (now >= startTimestamp);
    require (!(hasEnded()));
    require (multiSig != 0x0);
    require(tokensForSale > tokenRaised); // check we are not over the number of tokensForSale
    _;
  }

  /**
  * @dev authorise an account to participate
  */
  function authoriseAccount(address whom) onlyCSorOwner public {
    authorised[whom] = true;
  }

  /**
  * @dev authorise a lot of accounts in one go
  */
  function authoriseManyAccounts(address[] many) onlyCSorOwner public {
    for (uint256 i = 0; i < many.length; i++) {
      authorised[many[i]] = true;
    }
  }

  /**
  * @dev ban an account from participation (default)
  */
  function blockAccount(address whom) onlyCSorOwner public {
    authorised[whom] = false;
   }  
    
  /**
  * @dev set a new CS representative
  */
  function setCS(address newCS) onlyOwner public {
    cs = newCS;
  }

   /**
  * @dev set a freeForAll to true ( in case you leave to anybody to send ethers)
  */
  function switchONfreeForAll() onlyCSorOwner public {
    freeForAll = true;
  }
   /**
  * @dev set a freeForAll to false ( in case you need to authorise the acconts)
  */
  function switchOFFfreeForAll() onlyCSorOwner public {
    freeForAll = false;
  }

  function placeTokens(address beneficiary, uint256 _tokens) onlyCS public {
    //check minimum and maximum amount
    require(_tokens != 0);
    require(!hasEnded());
    require(tokenRaised <= maxTokens);
    require(now <= endTimestamp);
    uint256 amount = 0;
    if (token.balanceOf(beneficiary) == 0) {
      numberOfPurchasers++;
    }
    tokenRaised = tokenRaised.add(_tokens); // so we can go slightly over
    token.mint(beneficiary, _tokens);
    TokenPurchase(beneficiary, amount, _tokens);
  }

  // low level token purchase function
  function buyTokens(address beneficiary, uint256 amount) onlyAuthorised internal {

    setTier();   
   
    // calculate token amount to be created
    uint256 tokens = amount.mul(rate);

    // update state
    weiRaised = weiRaised.add(amount);
    if (token.balanceOf(beneficiary) == 0) {
      numberOfPurchasers++;
    }
    tokenRaised = tokenRaised.add(tokens); // so we can go slightly over
    token.mint(beneficiary, tokens);
    TokenPurchase(beneficiary, amount, tokens);
    multiSig.transfer(this.balance); // better in case any other ether ends up here
  }

  // transfer ownership of the token to the owner of the presale contract
  function finishSale() public onlyOwner {
    require(hasEnded());

    // assign the rest of the 60M tokens to the reserve
    uint unassigned;
    if(maxTokens > tokenRaised) {
      unassigned  = maxTokens.sub(tokenRaised);
      token.mint(multiSig,unassigned);
    }
    token.finishMinting();
    token.transferOwnership(owner);
    SaleClosed();
  }

  // fallback function can be used to buy tokens
  function () public payable {
    buyTokens(msg.sender, msg.value);
  }

  function emergencyERC20Drain( ERC20 oddToken, uint amount ) public {
    oddToken.transfer(owner, amount);
  }
}
function hasEnded() public constant returns (bool) {
  if (now > endTimestamp)
    return true;
  if (tokenRaised >= tokensForSale)
    return true; // if we reach the tokensForSale
  return false;
}

// @return true if crowdsale event has ended