function [ t,version ] = prologix_connect(ipAddress)
%PROLOGIX_CONNECT opens TCP/IP connection with Prologix device
%   [t,version] = PROLOGIX_CONNECT() will automaticly find IP 
%   address and starts connection.
%   [t,version] = PROLOGIX_CONNECT(ipAddress) starts connection
%   with given IP address.
%   IP address is autodiscovered. But can be used for a
%   device on a different subnet.
%   If you don't know the IP address leave it empty.
    
%% define variables
    port = 1234;
    % if no IP address is given start autodiscovery;
    if nargin < 1
        ipAddress = prologix_discovery();
    elseif isempty(regexp(ipAddress,'([1-2]?[0-9]{1,2}\.){3}[1-2]?[0-9]{1,2}','match'))
        error('Given IP address is not valid, leave empty to use autodiscovery of device');
    end
        
    
%% open connection.
    echotcpip('on', port);      % start listening for tcp packets on port
    t = tcpip(ipAddress,port);  % define tcpip connection
    fopen(t);                   % open connection

%% configure prologix.
    fprintf(t, '++mode 1');     %set device in controller mode
    fprintf(t, '++auto 0');     %disable automatic datapull. this avoids errors on equipment.
    fprintf(t, '++ver');        %ask firmware version of the prologix.
    version = ['Firmware Version: ', fscanf(t)]; %pull firmware function from prologix.
end

