
package tuner;

import java.io.*;
import java.net.*;

public class Client{

    public static final int TUNER_PORT = 8189;
    
    public static void main(String[] args){
	boolean stopped = false;
	String cmd = "play -t wav -";

	if (args.length != 1) {
	    System.err.println("Usage: Client address");
	    // System.exit(1);
	    return;
	}

	InetAddress address = null;
	try {
	    address = InetAddress.getByName(args[0]);
	} catch(UnknownHostException e) {
	    e.printStackTrace();
	    // System.exit(2);
            return;
	}

	Socket sock = null;
	try {
	    sock = new Socket(address, TUNER_PORT);
	} catch(IOException e) {
	    e.printStackTrace();
	    // System.exit(3);
            return;
	}

	InputStream in = null;
	OutputStream out = null;

	try {
	    in = sock.getInputStream();
	} catch(IOException e) {
	    e.printStackTrace();
	    // System.exit(5);
            return;
	}

	Process proc = null;
	try {
	    proc = Runtime.getRuntime().exec(cmd);
	    out = proc.getOutputStream();
	} catch(IOException e) {
	    System.err.println("Playing " + e.toString());
	    // ignore
	    return;
	}
	
	int ch;
	int bytesRead = 0;
	int nread;
        byte[] bytes = new byte[8096];
        try {
            while (((nread = in.read(bytes)) != -1) &&
                   (! stopped)) {
                out.write(bytes, 0, nread);
                        if (((bytesRead += nread) % 10000) == 0) {
                    System.out.println("Bytes read " + bytesRead);
                }
            }
	} catch(IOException e) {
	    // ignore
	    System.err.println("Exception writing " + e.toString());
	    return;
	} finally {
	    if (stopped) {
		System.out.println("Record stop called");
	    } else {
		System.out.println("Record finished naturally");
		stopped = true;
	    }
	    try {
		if (proc != null) {
		    proc.destroy();
		}
		in.close();
		out.close();
	    } catch(IOException e) {
		// ignore
		System.out.println("Finally " + e);
	    }
	}
    }
} // Client
