
package tuner;

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

// InetSocketAddress(InetAddress addr, int port) 
 

public class Server {
    
    public static int TUNER_PORT = 8189;
    public static boolean stopped;

    public static void main(String argv[]) {
	ServerSocket s = null;
	try {
	    s = new ServerSocket(TUNER_PORT);
	} catch(IOException e) {
	    System.out.println(e);
	    System.exit(1);
	}
	while (true) {
	    Socket incoming = null;
	    try {
		incoming = s.accept();
	    } catch(IOException e) {
		System.out.println(e);
		continue;
	    }

	    try {
		incoming.setSoTimeout(10000); // 10 seconds
	    } catch(SocketException e) {
		e.printStackTrace();
	    }

	    try {
		handleSocket(incoming);
	    } catch(InterruptedIOException e) {
		System.out.println("Time expired " + e);
	    } catch(IOException e) {
		System.out.println(e);
	    }

	    try {
		incoming.close();
	    } catch(IOException e) {
		// ignore
	    }
	}  
    }
    
    public static void handleSocket(Socket incoming) throws IOException {
	System.out.println("Socket connected " + incoming);
	stopped = false;

	InputStream in = null;
	OutputStream out =
	    incoming.getOutputStream();
	String cmd = "sox -t ossdsp -w -r 44100 -v 1.0 -c 1 /dev/dsp -t wav -";
	
	Process proc = null;
	try {
	    proc = Runtime.getRuntime().exec(cmd);
	    in = proc.getInputStream();
	} catch(IOException e) {
	    System.err.println("Playing " + e.toString());
	    // ignore
	    return;
	}
	
	int bytesRead = 0;
	int nread;
        byte[] bytes = new byte[1024];
        try {
            while (((nread = in.read(bytes)) != -1) &&
                   (! stopped)) {
                out.write(bytes, 0, nread);
            }
	} 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);
	    }
	}
    }
}
