@Override
	public void receiveAgent(final IAgent agent) {
		System.out.printf("Received agent %s.%n", agent);
		final Client thisClient = this;

		Runnable run = new Runnable() {
			public void run() {
				boolean failed = false;
				try {
					InetAddress nextNodeLocation = nameServer.lookupNode(nextNodeHash);
					String nextNodeAddress;
					if (nextNodeLocation == null) {
						nextNodeAddress = thisClient.getAddress().getHostAddress();
					}
					else {
						nextNodeAddress = nextNodeLocation.getHostAddress();
					}

					boolean sendAgent = agent.setCurrentClient(thisClient);
					Thread agentThread = new Thread(agent);
					agentThread.start();
					agentThread.join();

					// As long as there are no other nodes in the network, don't send the agent
					while (thisClient.getAddress().getHostAddress().equals(nextNodeAddress)) {
						Thread.sleep(10000);
						nextNodeAddress = nameServer.lookupNode(nextNodeHash).getHostAddress();
					}

					Thread.sleep(5000);
					if (sendAgent) {
						try {
							agent.prepareToSend();
							Registry registry = LocateRegistry.getRegistry(nextNodeAddress, Client.rmiPort);
							IClient nextClient = (IClient) registry.lookup(Client.bindLocation);
							nextClient.receiveAgent(agent);
						} catch (ConnectException e) {
							// assuming next client has failed
							removeFailedNode(getNextNodeHash());
						}
					}
				} catch (InterruptedException e) {
					System.err.println("Interrupted while waiting for agent thread");
					e.printStackTrace();
					failed = true;
				} catch (RemoteException e) {
					System.err.println("Error while locating registry or client");
					e.printStackTrace();
					failed = true;
				} catch (NotBoundException e) {
					System.err.println("Error while looking up remote client");
					e.printStackTrace();
					failed = true;
				} finally { 
					//TODO is dit goed?
					if (failed && agent instanceof FileAgent) {
						thisClient.receiveAgent(new FileAgent()); 
					}
				 }

			}
		};

		Thread wrapperThread = new Thread(run);
		wrapperThread.start();

	}