package net.tinyos.matlab;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class MatClient {
	Socket sock = null;

	ObjectOutputStream os = null;

	ObjectInputStream is = null;

	public void startJob() throws Exception {
		try {
			sock = new Socket("localhost", 4444);
			os = new ObjectOutputStream(sock.getOutputStream());
			is = new ObjectInputStream(sock.getInputStream());
		} catch (UnknownHostException e) {
			System.err.println("no localhost");
			System.exit(1);
		}
		// catch (Exception e) { e.printStackTrace(); System.exit(1); }
	}

	public void finishJob() {
		try {
			System.out.println("closing output stream...");
			os.close();
			System.out.println("closing input stream...");
			is.close();
			System.out.println("closing socket");
			sock.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Object sendCommand(String command, Object[] args) throws Exception {
		// ein "" als command kann verwendet werden, um die Matlab-Verbindung zu
		// überprüfen. Es wird kein Kommando ausgeführt, sondern lediglich
		// startJob
		// und finishJob gerufen. Kann keine Verbindung hergestellt werden, wird
		// eine Exception geworfen.

		startJob();
		Object ret = null;
		try {
			if (command != null && !"".equals(command)) {
				Object t[] = { command, args };
				os.writeObject(t);
				if (!"bye".equals(command)) {
					ret = is.readObject();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		finishJob();

		return ret;
	}

	public void shutdownServer() throws Exception {
		sendCommand("bye", null);
	}
	
}

