function con = urbiConnect(name, port)
%Open a connection to the URBI server and return connection's ID 
% e.g. con = urbiConnect('101.1.1.1', 54000);
% the connection's ID is a struct with fields :
%     id          : integer identifying the TCP/IP connection
%     version     : version of the Urbi server
%     tagOperator : operator to tag messages in Urbi 


if (nargin <1)
    error(['urbiConnect(name, port)\n' ...
        '  name : IP or name of the urbi server\n' ...
        '  port : port of the urbi server (def : 54000)\n'],1);
end

if (nargin == 1)
    port= 54000;
end

id = pnet('tcpconnect', name, port);

if ( id > -1)
    % workaround to get server version as 1.0 does not implement
    % system.version
    urbiVersion = '';
    r = pnet(id, 'readline');
    r = pnet(id, 'readline');
    while ~isempty(r)
        if (~isempty(strfind(r, 'URBI Kernel version 1.0')))
            urbiVersion='"1.0"';
        end
        if (isempty(strfind(r, '*************')))
            r = pnet(id, 'readline');
        else
            r='';
        end
    end
    con = struct('id',id,'tagOperator','<<');
    if (strcmp(urbiVersion,'')) urbiVersion = urbiGetVariable(con,'system.version');
    end

else
    error('Connection failed on port %d' , port);
end

pause(.3);
urbiClearConnection(con);

if (strcmp(urbiVersion,'"1.0"'))
    tagop = ':';
else
    tagop = '<<';
end

con=struct('id',id,'version',strtrim(urbiVersion),'tagOperator',tagop);
