library SafeMath {
  function mul(uint a, uint b) internal returns (uint) {
    uint c = a * b;
    assert(a == 0 || c / a == b);
    return c;
  }

  function div(uint a, uint b) internal returns (uint) {
    // assert(b > 0); // Solidity automatically throws when dividing by 0
    uint c = a / b;
    // assert(a == b * c + a % b); // There is no case in which this doesn't hold
    return c;
  }

  function sub(uint a, uint b) internal returns (uint) {
    assert(b <= a);
    return a - b;
  }

  function add(uint a, uint b) internal returns (uint) {
    uint c = a + b;
    assert(c >= a);
    return c;
  }

  function max64(uint64 a, uint64 b) internal constant returns (uint64) {
    return a >= b ? a : b;
  }

  function min64(uint64 a, uint64 b) internal constant returns (uint64) {
    return a < b ? a : b;
  }

  function max256(uint256 a, uint256 b) internal constant returns (uint256) {
    return a >= b ? a : b;
  }

  function min256(uint256 a, uint256 b) internal constant returns (uint256) {
    return a < b ? a : b;
  }
  
  /**
   * Based on http://www.codecodex.com/wiki/Calculate_an_integer_square_root
   */
  function sqrt(uint num) internal returns (uint) {
    if (0 == num) { // Avoid zero divide 
      return 0; 
    }   
    uint n = (num / 2) + 1;      // Initial estimate, never low  
    uint n1 = (n + (num / n)) / 2;  
    while (n1 < n) {  
      n = n1;  
      n1 = (n + (num / n)) / 2;  
    }  
    return n;  
  }

  function assert(bool assertion) internal {
    if (!assertion) {
      throw;
    }
  }
}
/**
 * Math operations with safety checks
 */
function sqrt(uint num) internal returns (uint) {
  if (0 == num) { // Avoid zero divide 
    return 0; 
  }   
  uint n = (num / 2) + 1;      // Initial estimate, never low  
  uint n1 = (n + (num / n)) / 2;  
  while (n1 < n) {  
    n = n1;  
    n1 = (n + (num / n)) / 2;  
  }  
  return n;  
}

/**
 * Based on http://www.codecodex.com/wiki/Calculate_an_integer_square_root
 */