contract FreezableToken is StandardToken, Ownable {
    // freezing chains
    mapping (bytes32 => uint64) internal chains;
    // freezing amounts for each chain
    mapping (bytes32 => uint) internal freezings;
    // total freezing balance per address
    mapping (address => uint) internal freezingBalance;

    // reducible freezing chains
    mapping (bytes32 => uint64) internal reducibleChains;
    // reducible freezing amounts for each chain
    mapping (bytes32 => uint) internal reducibleFreezings;
    // total reducible freezing balance per address
    mapping (address => uint) internal reducibleFreezingBalance;

    event Freezed(address indexed to, uint64 release, uint amount);
    event Released(address indexed owner, uint amount);
    event FreezeReduced(address indexed owner, uint64 release, uint amount);

    modifier hasReleasePermission() {
        require(msg.sender == owner, "Access denied");
        _;
    }

    /**
     * @dev Gets the balance of the specified address include freezing tokens.
     * @param _owner The address to query the the balance of.
     * @return An uint256 representing the amount owned by the passed address.
     */
    function balanceOf(address _owner) public view returns (uint256 balance) {
        return super.balanceOf(_owner) + freezingBalance[_owner] + reducibleFreezingBalance[_owner];
    }

    /**
     * @dev Gets the balance of the specified address without freezing tokens.
     * @param _owner The address to query the the balance of.
     * @return An uint256 representing the amount owned by the passed address.
     */
    function actualBalanceOf(address _owner) public view returns (uint256 balance) {
        return super.balanceOf(_owner);
    }

    /**
     * @dev Gets the freezed balance of the specified address.
     * @param _owner The address to query the the balance of.
     * @return An uint256 representing the amount owned by the passed address.
     */
    function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
        return freezingBalance[_owner];
    }

    /**
     * @dev Gets the reducible freezed balance of the specified address.
     * @param _owner The address to query the the balance of.
     * @return An uint256 representing the amount owned by the passed address.
     */
    function reducibleFreezingBalanceOf(address _owner) public view returns (uint256 balance) {
        return reducibleFreezingBalance[_owner];
    }

    /**
     * @dev gets freezing count
     * @param _addr Address of freeze tokens owner.
     */
    function freezingCount(address _addr) public view returns (uint count) {
        uint64 release = chains[toKey(_addr, 0)];
        while (release != 0) {
            count++;
            release = chains[toKey(_addr, release)];
        }
    }

    /**
     * @dev gets reducible freezing count
     * @param _addr Address of freeze tokens owner.
     * @param _sender Address of frozen tokens sender.
     */
    function reducibleFreezingCount(address _addr, address _sender) public view returns (uint count) {
        uint64 release = reducibleChains[toKey2(_addr, _sender, 0)];
        while (release != 0) {
            count++;
            release = reducibleChains[toKey2(_addr, _sender, release)];
        }
    }

    /**
     * @dev gets freezing end date and freezing balance for the freezing portion specified by index.
     * @param _addr Address of freeze tokens owner.
     * @param _index Freezing portion index. It ordered by release date descending.
     */
    function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
        for (uint i = 0; i < _index + 1; i++) {
            _release = chains[toKey(_addr, _release)];
            if (_release == 0) {
                return (0, 0);
            }
        }
        _balance = freezings[toKey(_addr, _release)];
    }

    /**
     * @dev gets reducible freezing end date and reducible freezing balance for the freezing portion specified by index.
     * @param _addr Address of freeze tokens owner.
     * @param _sender Address of frozen tokens sender.
     * @param _index Freezing portion index. It ordered by release date descending.
     */
    function getReducibleFreezing(address _addr, address _sender, uint _index) public view returns (uint64 _release, uint _balance) {
        for (uint i = 0; i < _index + 1; i++) {
            _release = reducibleChains[toKey2(_addr, _sender, _release)];
            if (_release == 0) {
                return (0, 0);
            }
        }
        _balance = reducibleFreezings[toKey2(_addr, _sender, _release)];
    }

    /**
     * @dev freeze your tokens to the specified address.
     *      Be careful, gas usage is not deterministic,
     *      and depends on how many freezes _to address already has.
     * @param _to Address to which token will be freeze.
     * @param _amount Amount of token to freeze.
     * @param _until Release date, must be in future.
     */
    function freezeTo(address _to, uint _amount, uint64 _until) public {
        _freezeTo(msg.sender, _to, _amount, _until);
    }

    /**
     * @dev freeze your tokens to the specified address.
     *      Be careful, gas usage is not deterministic,
     *      and depends on how many freezes _to address already has.
     * @param _to Address to which token will be freeze.
     * @param _amount Amount of token to freeze.
     * @param _until Release date, must be in future.
     */
    function _freezeTo(address _from, address _to, uint _amount, uint64 _until) internal {
        require(_to != address(0));
        require(_amount <= balances[_from]);

        balances[_from] = balances[_from].sub(_amount);

        bytes32 currentKey = toKey(_to, _until);
        freezings[currentKey] = freezings[currentKey].add(_amount);
        freezingBalance[_to] = freezingBalance[_to].add(_amount);

        freeze(_to, _until);
        emit Transfer(_from, _to, _amount);
        emit Freezed(_to, _until, _amount);
    }

    /**
     * @dev freeze your tokens to the specified address with posibility to reduce freezing.
     *      Be careful, gas usage is not deterministic,
     *      and depends on how many freezes _to address already has.
     * @param _to Address to which token will be freeze.
     * @param _amount Amount of token to freeze.
     * @param _until Release date, must be in future.
     */
    function reducibleFreezeTo(address _to, uint _amount, uint64 _until) public {
        require(_to != address(0));
        require(_amount <= balances[msg.sender]);
        require(_until > block.timestamp);

        balances[msg.sender] = balances[msg.sender].sub(_amount);

        bytes32 currentKey = toKey2(_to, msg.sender, _until);
        reducibleFreezings[currentKey] = reducibleFreezings[currentKey].add(_amount);
        reducibleFreezingBalance[_to] = reducibleFreezingBalance[_to].add(_amount);

        reducibleFreeze(_to, _until);
        emit Transfer(msg.sender, _to, _amount);
        emit Freezed(_to, _until, _amount);
    }

    /**
     * @dev reduce freeze time for _amount of tokens for reducible freezing of address _to by frozen tokens sender.
     *      Removes reducible freezing for _amount of tokens if _newUntil in the past
     *      Be careful, gas usage is not deterministic,
     *      and depends on how many freezes _to address already has.
     * @param _to Address to which token will be freeze.
     * @param _amount Amount of token to freeze.
     * @param _until Release date, must be in future.
     */
    function reduceFreezingTo(address _to, uint _amount, uint64 _until, uint64 _newUntil) public {
        require(_to != address(0));

        // Don't allow to move reducible freezing to the future
        require(_newUntil < _until, "Attempt to move the freezing into the future");

        bytes32 currentKey = toKey2(_to, msg.sender, _until);
        uint amount = reducibleFreezings[currentKey];
        require(amount > 0, "Freezing not found");

        if (_amount >= amount) {
            delete reducibleFreezings[currentKey];

            uint64 next = reducibleChains[currentKey];
            bytes32 parent = toKey2(_to, msg.sender, uint64(0));
            while (reducibleChains[parent] != _until) {
                parent = toKey2(_to, msg.sender, reducibleChains[parent]);
            }

            if (next == 0) {
                delete reducibleChains[parent];
            }
            else {
                reducibleChains[parent] = next;
            }

            if (_newUntil <= block.timestamp) {
                balances[_to] = balances[_to].add(amount);
                reducibleFreezingBalance[_to] = reducibleFreezingBalance[_to].sub(amount);

                emit Released(_to, amount);
            }
            else {
                bytes32 newKey = toKey2(_to, msg.sender, _newUntil);
                reducibleFreezings[newKey] = reducibleFreezings[newKey].add(amount);

                reducibleFreeze(_to, _newUntil);

                emit FreezeReduced(_to, _newUntil, amount);
            }
        }
        else {
            reducibleFreezings[currentKey] = reducibleFreezings[currentKey].sub(_amount);
            if (_newUntil <= block.timestamp) {
                balances[_to] = balances[_to].add(_amount);
                reducibleFreezingBalance[_to] = reducibleFreezingBalance[_to].sub(_amount);

                emit Released(_to, _amount);
            }
            else {
                bytes32 newKey = toKey2(_to, msg.sender, _newUntil);
                reducibleFreezings[newKey] = reducibleFreezings[newKey].add(_amount);

                reducibleFreeze(_to, _newUntil);

                emit FreezeReduced(_to, _newUntil, _amount);
            }
        }
    }

    /**
     * @dev release first available freezing tokens.
     */
    function releaseOnce() public {
        _releaseOnce(msg.sender);
    }

    /**
     * @dev release first available freezing tokens (support).
     * @param _addr Address of frozen tokens owner.
     */
    function releaseOnceFor(address _addr) hasReleasePermission public {
        _releaseOnce(_addr);
    }

    /**
     * @dev release first available freezing tokens.
     * @param _addr Address of frozen tokens owner.
     */
    function _releaseOnce(address _addr) internal {
        bytes32 headKey = toKey(_addr, 0);
        uint64 head = chains[headKey];
        require(head != 0, "Freezing not found");
        require(uint64(block.timestamp) > head, "Premature release attempt");
        bytes32 currentKey = toKey(_addr, head);

        uint64 next = chains[currentKey];

        uint amount = freezings[currentKey];
        delete freezings[currentKey];

        balances[_addr] = balances[_addr].add(amount);
        freezingBalance[_addr] = freezingBalance[_addr].sub(amount);

        if (next == 0) {
            delete chains[headKey];
        } else {
            chains[headKey] = next;
            delete chains[currentKey];
        }
        emit Released(_addr, amount);
    }

    /**
     * @dev release first available reducible freezing tokens.
     * @param _sender Address of frozen tokens sender.
     */
    function releaseReducibleFreezingOnce(address _sender) public {
        _releaseReducibleFreezingOnce(msg.sender, _sender);
    }

    /**
     * @dev release first available reducible freezing tokens for _addr.
     * @param _addr Address of frozen tokens owner.
     * @param _sender Address of frozen tokens sender.
     */
    function releaseReducibleFreezingOnceFor(address _addr, address _sender) hasReleasePermission public {
        _releaseReducibleFreezingOnce(_addr, _sender);
    }

    /**
     * @dev release first available reducible freezing tokens.
     * @param _addr Address of frozen tokens owner.
     * @param _sender Address of frozen tokens sender.
     */
    function _releaseReducibleFreezingOnce(address _addr, address _sender) internal {
        bytes32 headKey = toKey2(_addr, _sender, 0);
        uint64 head = reducibleChains[headKey];
        require(head != 0, "Freezing not found");
        require(uint64(block.timestamp) > head, "Premature release attempt");
        bytes32 currentKey = toKey2(_addr, _sender, head);

        uint64 next = reducibleChains[currentKey];

        uint amount = reducibleFreezings[currentKey];
        delete reducibleFreezings[currentKey];

        balances[_addr] = balances[_addr].add(amount);
        reducibleFreezingBalance[_addr] = reducibleFreezingBalance[_addr].sub(amount);

        if (next == 0) {
            delete reducibleChains[headKey];
        } else {
            reducibleChains[headKey] = next;
            delete reducibleChains[currentKey];
        }
        emit Released(_addr, amount);
    }

    /**
     * @dev release all available for release freezing tokens. Gas usage is not deterministic!
     * @return how many tokens was released
     */
    function releaseAll() public returns (uint tokens) {
        tokens = _releaseAll(msg.sender);
    }

    /**
     * @dev release all available for release freezing tokens for address _addr. Gas usage is not deterministic!
     * @param _addr Address of frozen tokens owner.
     * @return how many tokens was released
     */
    function releaseAllFor(address _addr) hasReleasePermission public returns (uint tokens) {
        tokens = _releaseAll(_addr);
    }

    /**
     * @dev release all available for release freezing tokens.
     * @param _addr Address of frozen tokens owner.
     * @return how many tokens was released
     */
    function _releaseAll(address _addr) internal returns (uint tokens) {
        uint release;
        uint balance;
        (release, balance) = getFreezing(_addr, 0);
        while (release != 0 && block.timestamp > release) {
            _releaseOnce(_addr);
            tokens += balance;
            (release, balance) = getFreezing(_addr, 0);
        }
    }

    /**
     * @dev release all available for release reducible freezing tokens sent by _sender. Gas usage is not deterministic!
     * @param _sender Address of frozen tokens sender.
     * @return how many tokens was released
     */
    function reducibleReleaseAll(address _sender) public returns (uint tokens) {
        tokens = _reducibleReleaseAll(msg.sender, _sender);
    }

    /**
     * @dev release all available for release reducible freezing tokens sent by _sender to _addr. Gas usage is not deterministic!
     * @param _addr Address of frozen tokens owner.
     * @param _sender Address of frozen tokens sender.
     * @return how many tokens was released
     */
    function reducibleReleaseAllFor(address _addr, address _sender) hasReleasePermission public returns (uint tokens) {
        tokens = _reducibleReleaseAll(_addr, _sender);
    }


    /**
     * @dev release all available for release reducible freezing tokens sent by _sender to _addr.
     * @param _addr Address of frozen tokens owner.
     * @param _sender Address of frozen tokens sender.
     * @return how many tokens was released
     */
    function _reducibleReleaseAll(address _addr, address _sender) internal returns (uint tokens) {
        uint release;
        uint balance;
        (release, balance) = getReducibleFreezing(_addr, _sender, 0);
        while (release != 0 && block.timestamp > release) {
            releaseReducibleFreezingOnce(_sender);
            tokens += balance;
            (release, balance) = getReducibleFreezing(_addr, _sender, 0);
        }
    }

    function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
        result = 0x1852251212091514201510158141318000000000000000000000000000000000;
        assembly {
            result := or(result, mul(_addr, 0x10000000000000000))
            result := or(result, _release)
        }
    }

    function toKey2(address _addr1, address _addr2, uint _release) internal pure returns (bytes32 result) {
        bytes32 key1 = 0x1852251212091514201510158141318000000000000000000000000000000000;
        bytes32 key2 = 0x9117776660000000000000000000000000000000000000000000000000000000;
        assembly {
            key1 := or(key1, mul(_addr1, 0x10000000000000000))
            key1 := or(key1, _release)
            key2 := or(key2, _addr2)
        }
        result = keccak256(abi.encodePacked(key1, key2));
    }

    function freeze(address _to, uint64 _until) internal {
        require(_until > block.timestamp);
        bytes32 key = toKey(_to, _until);
        bytes32 parentKey = toKey(_to, uint64(0));
        uint64 next = chains[parentKey];

        if (next == 0) {
            chains[parentKey] = _until;
            return;
        }

        bytes32 nextKey = toKey(_to, next);
        uint parent;

        while (next != 0 && _until > next) {
            parent = next;
            parentKey = nextKey;

            next = chains[nextKey];
            nextKey = toKey(_to, next);
        }

        if (_until == next) {
            return;
        }

        if (next != 0) {
            chains[key] = next;
        }

        chains[parentKey] = _until;
    }

    function reducibleFreeze(address _to, uint64 _until) internal {
        require(_until > block.timestamp);
        bytes32 key = toKey2(_to, msg.sender, _until);
        bytes32 parentKey = toKey2(_to, msg.sender, uint64(0));
        uint64 next = reducibleChains[parentKey];

        if (next == 0) {
            reducibleChains[parentKey] = _until;
            return;
        }

        bytes32 nextKey = toKey2(_to, msg.sender, next);
        uint parent;

        while (next != 0 && _until > next) {
            parent = next;
            parentKey = nextKey;

            next = reducibleChains[nextKey];
            nextKey = toKey2(_to, msg.sender, next);
        }

        if (_until == next) {
            return;
        }

        if (next != 0) {
            reducibleChains[key] = next;
        }

        reducibleChains[parentKey] = _until;
    }
}
function freezingCount(address _addr) public view returns (uint count) {
        uint64 release = chains[toKey(_addr, 0)];
        while (release != 0) {
            count++;
            release = chains[toKey(_addr, release)];
        }
    }
/**
 * @dev gets freezing count
 * @param _addr Address of freeze tokens owner.
 */