import processing.core.*; 
import processing.xml.*; 

import processing.net.*; 
import ddf.minim.*; 

import java.applet.*; 
import java.awt.*; 
import java.awt.image.*; 
import java.awt.event.*; 
import java.io.*; 
import java.net.*; 
import java.text.*; 
import java.util.*; 
import java.util.zip.*; 
import java.util.regex.*; 

public class SoundServer4 extends PApplet {





// audio stuff
Minim minim;
AudioInput in;

// server
Server s; 
// data output
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
DataOutputStream dataOut = new DataOutputStream(byteOut);

Boolean okToSend = false;

public void setup(){
  size(100,100, P2D);

  s = new Server(this, 4444);

  minim = new Minim(this);
  minim.debugOn();

  // get a line in from Minim, default bit depth is 16
  in = minim.getLineIn(Minim.STEREO, 512);
}

public void draw(){
  // get a client if they are sending something
  Client client=s.available();

  if(client!=null) {
 
    try{
      
      ByteArrayInputStream bytesIn = new ByteArrayInputStream (client.readBytes());

      DataInputStream dataIn = new DataInputStream (bytesIn);

      String message=dataIn.readUTF();
      println(message);

      okToSend = true;

    } catch(IOException e) {

      s.disconnect(client);
      okToSend  = false;
      println("error: "+e);
    }
  }

  if(okToSend)  {

    try{
      // left channel
      for(int i = 0; i < 512; i++){
        dataOut.writeFloat((float)((in.left.get(i))));
      }

      // right channel
      for(int i = 0; i < 512; i++){
        dataOut.writeFloat((float)((in.right.get(i))));
      }

      s.write(byteOut.toByteArray());

      // empty output
      byteOut.reset();
      dataOut.flush();

    }catch (IOException e){

      println("error: "+e);
    }
  }
}


public void stop(){
  // always close Minim audio classes when you are done with them
  in.close();
  minim.stop();
  super.stop();
}



  static public void main(String args[]) {
    PApplet.main(new String[] { "--bgcolor=#ffffff", "SoundServer4" });
  }
}
