function ipaddress = prologix_discovery(localhost)
%% PROLOGIX_DISCOVERY Find your prologix GPIB device.
%   ipaddress = PROLOGIX_DISCOVERY() finds prologix on your 
%   local network. When your prologix device is detected
%   string with ip address is returned. 
%   
%   Function uses persistent ipaddress: when ipaddress is 
%   changed use CLEAR ALL to find the current ipaddress.
%   See also CLEAR

%% setup correct variables.
% if location of prologix is known: just return stored ip address
if nargin < 1
    localhostcellarray = getLocalIP();
else
    localhostcellarray{1} = localhost;
end
persistent stored_ipaddress;
if ~isempty(stored_ipaddress)
    ipaddress = stored_ipaddress;
    return
end
local_port = randi([49152 65535]);
remote_port = 3040;

%% setup dsp to send and recieve udp packets.
for ipIndex = 1:length(localhostcellarray)
    udpconnection = udp('10.255.255.255',3040);
    %hudpr = dsp.UDPReceiver('LocalIPPort',local_port);
    % hudps = dsp.UDPSender('RemoteIPAddress','255.255.255.255','RemoteIPPort',remote_port,'LocalIPPortSource','Property','LocalIPPort',local_port);
    % start recieving udp packets
    % setup(hudpr);
    fopen(udpconnection);


    %% Discover prologix.
    % magic string to request ipaddress from prologix: ['5a' '00' '5b' 'db' 'ff' 'ff' 'ff' 'ff' 'ff' 'ff' '00' '00']
    magic_msg = uint8([90 0 91 219 255 255 255 255 255 255 00 00]);
    % Sending packet.
    % hudps(magic_msg);
    fwrite(udpconnection,magic_msg);
    % Recieving packet or resend.
    for i = 1:100
        pause(0.1);
        msg = fread(udpconnection);
        if numel(msg)>0
            break;
        elseif mod(i,10) == 0
            %waiting dot and resending of string
            fprintf('.')
            fwrite(udpconnection,magic_msg);
    %         step(hudps,magic_msg);
        end
    end
    fclose(udpconnection);
    if ~isempty(msg)
        break;
    end
end
if isempty(msg)
    error('No prologix found on network');
end
%ipaddress string is extracted from recieved UDP message. array position 21
%till 24.
ipaddress = num2str(msg(21:24)','%d.%d.%d.%d');
stored_ipaddress = ipaddress;