/*
 * Mind.java
 *
 * Created on 1 of February 2006, 2:06
 */

/**
 *
 * @author Paulo Roque Silva
 */

/**
 * 
	TouchSensor(SensorPort.S1);
	SoundSensor(SensorPort.S2);
	LightSensor(SensorPort.S3);
	UltrasonicSensor(SensorPort.S4);

	Motor.A  Left leg
	Motor.B  Right leg
 */

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.BrokenBarrierException;
import javax.swing.*;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.sound.sampled.Port;
import javax.sound.sampled.TargetDataLine;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioFormat.Encoding;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Clip;
import javax.sound.sampled.AudioInputStream;
import java.io.*;

public class Mind extends Thread {
	static final int TimeSlize = 0;
					// Tempo (ms) intervalo entre passos
    final int       StartLocal  = 61;
    				// Local de come�o do C. Elegans
	static final int PROFOUNDITY = 6; // Profundidade Sleep
    Brain           brain; // Todo o c�rebro e c�rtex
// CONSTANTES DO CORPO
    static final int Power = 100; // Amplitude
    static final int BANDS = 7; // Bandas de som
    final int		SAMPLE_RATE = 16000; // Amostragem som
    static final int TimeWait  = 64; // Tempo (ms) espera
 // VARI�VEIS DO CORPO
    public static Signal []Action; // A��o do rob�
    public static int Tact[], // Sentido Tacto do rob�
    				NStep; // N�mero passo do rob�
	public static boolean speak;
	int				bottom, // NXT
					ligth, // NXT
					ultraSonic, // NXT
					sound; // NXT
	boolean			feelPain; // Se o rob� sente Dor
    int 			senteTaste[];
    int             senteVision[];
    int             senteTact[];
    int 			senteSound[];
    int 			senteSmell[];
    int             senteProSelf[]; // Propriocetivo
    int				tasteBefore[]; // Sensa��o anterior
    int				smellBefore[];
    int				visionBefore[];
    int             tactBefore[];
    int				pleasurePS[], // N�vel de prazer
    				pleasureTa[],
    				pleasureTc[],
    				pleasureSm[],
    				pleasureSo[],
    				pleasureVi[];
    int				quantity[]; // N�vel de prazer
	int				m; // indexe
	int				profoundity; // indexe
    public static int Bom; // Para agir
    public static float	veloc; // Velocidade, 1- Normal
    
    CyclicBarrier   stepBarrierAct; // Barreiras
    CyclicBarrier   stepBarrierDecision;
    CyclicBarrier   stepBarrierDecision2;
    CyclicBarrier   stepBarrierPast;
    CyclicBarrier   stepBarrierCerebellum;
    CyclicBarrier   stepBarrierSleep;

// VARI�VEIS DA SIMULA��O
    int				i; // �ndexe
    boolean         pause; // Se para parar
	public static boolean OpenData; // Se dados antigos
    
    static int      local; // Actual local
	int				orient, // Orienta��o do C. Elegans
					wallOrLocal, // Local ou Parede
					tact, // Parede ou n�o
					nutrition, // Comida, �gua ou Terra
					vision, // Vis�o
					nStep; // Passo movimentado pelo rob�
    World           habitat; // Mundo do C. Elegans
    TargetDataLine  line; // Microfone
    AudioFormat		format; // Formato �udio
    int				numBytesRead;
    int				numBytesReadTotal;
    byte[]          data;
    DataLine.Info   info,
                    info2,
    				info3,
    				info4,
    				info5,
    				info6;
    AudioInputStream stream,
    				stream2,
    				stream3,
    				stream4,
					stream5;
    public static Clip clip,
    				clip2,
    				clip3,
    				clip4, // Rir
    				clip5; // Chorar
    /** Creates a new instance of Mind */
    public Mind(boolean od, JTextField txt) {
        
        System.out.println(
        	"VitaLiberu...by Paulo Roque Silva 2004-2025");
        brain        = new Brain(txt);
        Action      = new Signal[Brain.MOVES];
        for (int i=0; i < Action.length; i++)
            Action[i] = new Signal(i, 0, 0);
        senteTaste  = new int[Brain.NanalogTaste];
        pleasureTa  = new int[Brain.NanalogTaste];
        tasteBefore = new int[Brain.NanalogTaste];
        senteVision = new int[Brain.NanalogVision];
        pleasureVi  = new int[Brain.NanalogVision];
        senteTact   = new int[Brain.NanalogTact];
        pleasureTc  = new int[Brain.NanalogTact];
        senteSound  = new int[Brain.NanalogSound];
        pleasureSo  = new int[Brain.NanalogSound];
        senteSmell  = new int[Brain.NanalogSmell];
        pleasureSm  = new int[Brain.NanalogSmell];
        Tact		= new int[Brain.NanalogTact];
        tactBefore	= new int[Brain.NanalogTact];
        visionBefore= new int[Brain.NanalogVision];
        smellBefore= new int[Brain.NanalogSmell];
        senteProSelf= new int[Brain.NanalogProSelf];
        pleasurePS  = new int[Brain.NanalogProSelf];
        quantity    = new int[1];
        quantity[0] = 0;
        NStep       = 0;
        speak = false;
        pause 		= true;
        tasteBefore[0] = 0;
    	for (i=0; i<visionBefore.length; i++)
    		visionBefore[i] = 0;
    	for (i=0; i<smellBefore.length; i++)
    		smellBefore[i] = 0;
        OpenData    = od;
        veloc 		= 1;
        habitat     = new World();
        local = StartLocal;
        orient = World.NORTH;
        tact        = Brain.NO_TACT;
        nutrition   = habitat.element(local);
        vision      = habitat.vision(local, orient);
        display(true, false);
    }
    
    public void step(boolean p) {
        
    	pause = p;
    }
    
    public static int getBom() {
        
        return Math.abs(Bom);
    }
    
    public static void setBom(int b) {
        
        Bom = b;
    }
    
    public void display(boolean ex, boolean w) {
    	
        Liberu.InterFace.displayRobot(brain, ex, w);
        Liberu.InterFace.saveValue(0, local);
        Liberu.InterFace.saveValue(1, tact);
        Liberu.InterFace.saveValue(2, nutrition);
        Liberu.InterFace.saveValue(3, senteTact[1]);
        Liberu.InterFace.saveValue(4, orient);
        Liberu.InterFace.saveValue(5, vision);

        for (i=0; i<Brain.ACTS; i++)
            if (Action[i].active)
            	Liberu.InterFace.saveValue(8+i, 1);
            else
            	Liberu.InterFace.saveValue(8+i, 0);
        Liberu.InterFace.repaint();
    }
        
    private void ouve() {
    	int n, m, // �ndexes
    		derivada, // Diferen�a no som
    		readBefore, 
    		bandBefore,
    		totalHits;
    	
    	numBytesReadTotal = 0;
    	line.flush();
    	readBefore = 0;
    	System.out.println("Ouvindo...");
    	while (numBytesReadTotal < SAMPLE_RATE * 2) {
    		// Tempo ouvindo
    		numBytesRead = line.read(data, 0, data.length);
    		numBytesReadTotal += numBytesRead;
    		for (n=0; n < numBytesRead; n++) {
    			derivada = Math.abs(data[n] - readBefore);
    			bandBefore = 0;
    			for (m=0; m < BANDS; m++) {
    				if (derivada >= bandBefore &&
    						derivada < (int)(32000 /
    								Math.pow(2, BANDS-1-m)/
    								Brain.MaxInSense)) {
    					senteSound[m] += 1;
    					bandBefore = (int)(32000 /
    							Math.pow(2, BANDS-1-m)/
    							Brain.MaxInSense);
    				}
    			}
    			readBefore = data[n];
    		}
    	}
		System.out.println("Surdo...");
		totalHits = 0;
		for (m=0; m < BANDS; m++)
			totalHits += senteSound[m];
		if (totalHits == 0) totalHits = 1;
		for (m=0; m < BANDS; m++)
			senteSound[m] = (int)(senteSound[m] *
					Brain.MaxInSense / totalHits);
		for (m=0; m < BANDS; m++)
	        Liberu.InterFace.saveValue(36+m,
	        		senteSound[m]);
    }
    
    private void updateSenses() { // Comandos C.Elegants
    	int m, temp;
    	
    	for (m=0; m < senteVision.length; m++)
    		senteVision[m] = 0;
    	for (m=0; m < senteTact.length; m++)
    		senteTact[m] = 0;
    	for (m=0; m < senteSmell.length; m++)
    		senteSmell[m] = 0;
    	for (m=0; m < senteTaste.length; m++)
    		senteTaste[m] = 0;
    	for (m=0; m < senteSound.length; m++)
    		senteSound[m] = 0;
    	for (m=0; m < senteProSelf.length; m++)
    		senteProSelf[m] = 0;
    	// OUVE  	
    	for (i=0; i<pleasureSo.length; i++)
    		pleasureSo[i] = 0;
		System.out.println("Lisen..................:)");
		// REMOVER
    	ouve();
		for (m=0; m < BANDS; m++) {
			if (m != 0)
				pleasureSo[m] = senteSound[m] -
				senteSound[m-1];
			else
				pleasureSo[0] = 0;
		}

    	if (Action[Brain.TURN_RIGHT].active &&
    			Action[Brain.TURN_LEFT].active)
    	 	   ;
    	 	else {
    	    	if (Action[Brain.TURN_LEFT].active)
    	            orient = habitat.orientate(orient,
    	            		Brain.TURN_LEFT);
    	        if (Action[Brain.TURN_RIGHT].active)
    	            orient = habitat.orientate(orient,
    	            		Brain.TURN_RIGHT);
    	 	}
        
        // TACT
    	for (i=0; i<pleasureTc.length; i++)
    		pleasureTc[i] = 0;
    	Tact[0] = Brain.NO_TACT;
		feelPain = false;
        tact = Brain.NO_TACT;
        if (Action[Brain.WALK].active) {
            wallOrLocal = habitat.move(local, orient);
            if (wallOrLocal != World.WALL) {
                local = wallOrLocal; // Novo local
	         	senteTact[0] = (int)Power/2;
	         	// N�o sente tato
            }
            else {
                tact = Brain.TACT; // Sente obst�culo
             	senteTact[0] = Power; // Sente tato
        		if (brain.past.time[0][0].step >
        		Emotions.ActRandom) {
        			feelPain = true;
        	        Tact[0] = Brain.TACT;
        			pleasureTc[0] = -Power;
        	     	senteTact[0] = Power; // Sente tato
        			if (brain.past.time[0][0].step >
        			Emotions.ActRandom)
        				brain.decision.emotionPAIN();
        		}
            }
        }
		if (Brain.Energy)
			pleasureTc[0] += Power;

		nutrition = habitat.element(local);
        vision = habitat.vision(local, orient);

        if (vision == World.WALL)
        	senteTact[1] = (int)Power/2;
        else
        	senteTact[1] = Power;
        
        if (NStep > 1)
        	for (m=0; m < senteTact.length; m++)
                pleasureTc[m] = senteTact[m] -
                tactBefore[m]; // Melhor se distante
        else
        	pleasureTc[0] = 0;
        
        temp = orient;
        
        // TASTE
    	for (i=0; i<pleasureTa.length; i++)
    		pleasureTa[i] = 0;

    	senteTaste[nutrition-1] = Power;

        if (Action[Brain.EAT].active &&
        		nutrition != World.FOOD) {
			feelPain = true;
			if (brain.past.time[0][0].step >
			Emotions.ActRandom)
				brain.decision.emotionPAIN();
        }

        if (Action[Brain.DRINK].active &&
        		nutrition != World.WATER) {
			feelPain = true;
			if (brain.past.time[0][0].step >
			Emotions.ActRandom)
				brain.decision.emotionPAIN();
        }

    	for (m=0; m < senteTaste.length; m++)
            if (NStep > 1) {
                if (Brain.BackHome)
                    pleasureTa[m] = (senteTaste[m] -
                    		tasteBefore[m]) * 5;
                else
                    pleasureTa[m] = (tasteBefore[m] -
                    		senteTaste[m] * 5);
            }
            else
            	pleasureTa[m] = 0;
    	
		// SMELL
    	for (i=0; i<pleasureSm.length; i++)
    		pleasureSm[i] = 0;
     	senteSmell[local-1] = Power;
        pleasureSm[0] = local * 5;

        // VISION
    	for (i=0; i<pleasureVi.length; i++)
    		pleasureVi[i] = 0;
        temp = habitat.orientate(orient, Brain.TURN_LEFT);
        senteVision[0] = habitat.vision(local, temp);
        temp = habitat.orientate(orient, Brain.TURN_RIGHT);
        senteVision[2] = habitat.vision(local, temp);
     	senteVision[1] = vision;
		for (m=0; m < senteVision.length; m++)
			Interface.Vision[m] = senteVision[m];
        if (NStep > 1)
        	for (m=0; m < senteVision.length; m++)
                pleasureVi[m] = (visionBefore[m] -
                		senteVision[m]) * 5;
        else
        	pleasureVi[0] = 0;
        
        // PROPRIOCETIVO
		if (Action[Brain.DRINK].active)
			senteProSelf[Brain.DRINK] = Power;
		if (Action[Brain.EAT].active)
			senteProSelf[Brain.EAT] = Power;
		if (Action[Brain.WALK].active)
			senteProSelf[Brain.WALK] = Power;
		if (Action[Brain.TURN_LEFT].active)
			senteProSelf[Brain.TURN_LEFT] = Power;
		if (Action[Brain.TURN_RIGHT].active)
			senteProSelf[Brain.TURN_RIGHT] = Power;
		if (Action[Brain.Motive].active)
			senteProSelf[Brain.Motive] = Power;
		
    	speak = false;
		if (Action[Brain.Vogal1].active) {
			clip.setMicrosecondPosition(0);
			clip.start();
	        speak = true;
	        Cortex.nSpeaks += 1;
			senteProSelf[Brain.Vogal1] = Power;
    	}
		if (Action[Brain.Vogal2].active) {
			clip2.setMicrosecondPosition(0);
			clip2.start();
	        speak = true;
	        Cortex.nSpeaks += 1;
			senteProSelf[Brain.Vogal2] = Power;
		}
		if (Action[Brain.Vogal3].active) {
			clip3.setMicrosecondPosition(0);
			clip3.start();
	        speak = true;
	        Cortex.nSpeaks += 1;
			senteProSelf[Brain.Vogal3] = Power;
		}
    }
    
    private void senseProSelf() {
    	
		// PROPRIOCETIVO
    	for (i=0; i<pleasurePS.length; i++)
    		pleasurePS[i] = 0;
        pleasurePS[0] = brain.proSelf(senteProSelf,
        		senteTaste, Power);
        // Atualiza propriocetivo
        brain.motivationNXT(senteProSelf, Power);
        // Motiva��o
        if (feelPain)
        	pleasurePS[0] += -Power;
        brain.feelProSelf(senteProSelf, pleasurePS);
    }
    
    public void Sono() {
    	
        // Sleep in action ********************************
		Brain.Ansiedade = false;
		Brain.Saudade = false;
        brain.clearBusSleepPreviews();
        brain.clearBusSleepPreviews2();
		setBom(Math.abs(Emotions.Good));
		Brain.Best = brain.past.time[getBom()]
				[Brain.ProSelf].finalQuality;
		Brain.BusSleepPreviews.add(new Signal(Bom,Bom,
				brain.past.time[getBom()][Brain.ProSelf].
				finalQuality));
    	for (i=0; i<brain.past.time[getBom()][0].
    			learn.size(); i++)
    		Brain.BusSleepPreviews2.add(new Signal(
    				brain.past.time[getBom()][0].
    				getLearn(i).emitter,
    				brain.past.time[getBom()][0].
    				getLearn(i).emitter,
    				brain.past.time[getBom()]
    						[Brain.ProSelf].finalQuality));
		profoundity = 0;
		while (profoundity < PROFOUNDITY) {
			brain.pollSleepOut();
			brain.pollSleepOut2();
	        try {
	            stepBarrierSleep.await(); // In�cio Sleep 
	            while (stepBarrierSleep.
	            		getNumberWaiting() <
	            		stepBarrierSleep.getParties() - 1)
	                sleep(TimeWait);
	        }
	        catch (InterruptedException ex) { 
	        }
	        catch (BrokenBarrierException ex) { 
            }
			profoundity += 1;

	        brain.decide(profoundity);

			brain.transferOutIn();
			
			
			System.out.println("SONO acting...");
			// REMOVER
			brain.decide2(profoundity);

			brain.transferOutIn2();
		}
		if (Brain.Ansiedade || Brain.Saudade)
			brain.past.time[brain.past.time[0][0].pointer]
					[Brain.ProSelf].setFinalQuality(
							Brain.Best);

		Cortex.exec = Bom;
    	System.out.print("Bom= "); //REMOVER
    	System.out.println(Bom); //REMOVER
   }

    private void runStepBrain() {
    	int i;
    	
        // COME�A O CICLO
        NStep = brain.addStep();
        System.out.print("Passo = "); // REMOVER
        System.out.println(NStep); // REMOVER
    	if (brain.past.time[0][0].step == 0)
    		brain.past.time[0][0].standby2 = true;
        
    	// Come�a o passo de vida do rob�
        brain.clearBusesIn(true);
		brain.feelSound(senteSound, pleasureSo); // Sente
        brain.feelTaste(senteTaste, pleasureTa); 
		brain.feelSmell(senteSmell, pleasureSm);
        brain.feelVision(senteVision, pleasureVi);
        brain.feelTact(senteTact, pleasureTc);
        senseProSelf();

    	for (m=0; m < senteVision.length; m++)
    		visionBefore[m] = senteVision[m];
    	for (m=0; m < senteSmell.length; m++)
    		smellBefore[m] = senteSmell[m];
    	for (m=0; m < senteTaste.length; m++)
    		tasteBefore[m] = senteTaste[m];
    	for (m=0; m < senteTact.length; m++)
    		tactBefore[m] = senteTact[m];

        display(true, false); // Mostra ecr�

        // Fim do tempo real

        for (i=0; i<Action.length; i++)	{ // reset actions
            Action[i].setActive(false);
            Action[i].setActPower(0);
            Action[i].setPleasure(0);
        }

        Remember.Lovely = 0;
        Interface.Lovely = 0;
    	Remember.RecentMost = 0;
		Remember.threshold = 0;
        for (i=0; i<Brain.SENSES; i++)
        	Remember.NewSense[i] = true;
    	// Remember em a��o *******************************
        try {
            stepBarrierPast.await(); // Sincroniza
            while (stepBarrierPast.getNumberWaiting() <
            		stepBarrierPast.getParties() - 1)
                sleep(TimeWait);
        }
        catch (InterruptedException ex) { 
            return;
        }
        catch (BrokenBarrierException ex) { 
            return;
            }
		System.out.println("Past Remember..."); // REMOVER
		Emotions.Good = Remember.RecentMost;
    	brain.clearBusSleepPreviews();
    	brain.clearBusSleepPreviews2();
        // Emotions em a��o *******************************
        try {
            stepBarrierDecision.await(); // Sincroniza 
            while (stepBarrierDecision2.
            		getNumberWaiting() <
            		stepBarrierDecision2.getParties() - 1)
                sleep(TimeWait);
        }
        catch (InterruptedException ex) { 
            return;
        }
        catch (BrokenBarrierException ex) { 
            return;
            }
		System.out.println("Emotions acted..."); // REMOVER
    	System.out.print("recent= "); //REMOVER
    	System.out.println(Remember.RecentMost); //REMOVER
        display(true, false); // shows in screen
		if (!Emotions.ActualPain && Emotions.IdAct1 ==
				Cerebellum.ESCape) {
			brain.past.time[Math.abs(Cortex.
					lastExec)][0].standby2 =
					true;
	    	System.out.println(Cortex.lastExec);
	    	//REMOVER
    		Cortex.lastExec = Cortex.exec;
		}
		if (Emotions.Good >= 0 && Emotions.IdAct1 ==
				Cerebellum.ESCape)
	        // Sleep em ação ******************************
			Sono();
    	System.out.print("exec= "); //REMOVER
    	System.out.println(Cortex.exec); //REMOVER
		// Cerebellum em a��o *****************************
        try {
            stepBarrierCerebellum.await(); // Sincroniza
            while (stepBarrierCerebellum.
            		getNumberWaiting() <
            		stepBarrierCerebellum.getParties() - 1)
                sleep(TimeWait);
        }
        catch (InterruptedException ex) { 
            return;
        }
        catch (BrokenBarrierException ex) { 
            return;
            }
		System.out.println("Cerebellum acted...");
		// REMOVER
        // Act em a��o ************************************
        try {
            stepBarrierAct.await(); // Sincroniza 
            while (stepBarrierAct.getNumberWaiting() <
            		stepBarrierAct.getParties() - 1)
                sleep(TimeWait);
        }
        catch (InterruptedException ex) { 
            return;
        }
        catch (BrokenBarrierException ex) { 
            return;
            }
		System.out.println("Acting Nodes..."); // REMOVER
        // Emotions parte 2 em a��o ***********************
        try {
            stepBarrierDecision2.await(); // Sincroniza
            while (stepBarrierDecision.getNumberWaiting() <
            		stepBarrierDecision.getParties() - 1)
                sleep(TimeWait);
        }
        catch (InterruptedException ex) { 
            return;
        }
        catch (BrokenBarrierException ex) { 
            return;
            }
		System.out.println("Decision 2 acted...");
		// REMOVER
        
        // Come�o do tempo real
		brain.act(Action); // Rob� age
        display(true, Cortex.Warn); // Mostra ecr�
        updateSenses();
        veloc = 1;
        // Fim do passo de vida do rob�
		Emotions.WARNING = false;
    }

    public void continueRun() {
        
        System.out.println("Continue...");
        pause = false;
    }
    
    public void pause() {
        
        System.out.println("Pause...");
        pause = true;
    }
    
    public void setToEnd() {
        
    	stepBarrierAct.reset();
    	stepBarrierDecision.reset();
    	stepBarrierDecision2.reset();
    	stepBarrierPast.reset();
    	stepBarrierCerebellum.reset();
    	stepBarrierSleep.reset();
    }
    
    public void run() {
        
    	if (!OpenData)
    		brain.past.bornTime();
    	
		bottom = Brain.NO_TACT;
		ligth = 0;
		ultraSonic = vision;
		sound = 0;

		format = new AudioFormat(Encoding.PCM_SIGNED,
				SAMPLE_RATE, 8, 1, 1, SAMPLE_RATE, true);
    	info = new DataLine.Info(TargetDataLine.class,
    			format);
    	if (AudioSystem.isLineSupported(
    			Port.Info.MICROPHONE)) {
    		try {
    			line = (TargetDataLine)AudioSystem.
    					getLine(info);
    	    	line.open(format);
    	    	data = new byte[line.getBufferSize()/5];
    	    	line.start();
    			System.out.print("microfone...");
    			System.out.println(line.getBufferSize());
    		}
    		catch (LineUnavailableException ex) {
    			System.out.println("Sem microfone...");
    		}
    	}
    	else
			System.out.println("Sem microfone......");
    	if (AudioSystem.isLineSupported(
    			Port.Info.SPEAKER)) {
        	try {
            	stream = AudioSystem.getAudioInputStream(
            			new File("audiofile1nxt.wav"));
            	stream2 = AudioSystem.getAudioInputStream(
            			new File("audiofile2nxt.wav"));
            	stream3 = AudioSystem.getAudioInputStream(
            			new File("audiofile3nxt.wav"));
            	stream4 = AudioSystem.getAudioInputStream(
            			new File("Rir.wav"));
            	stream5 = AudioSystem.getAudioInputStream(
            			new File("Choro.wav"));
        	}
        	catch (IOException e) {
                e.printStackTrace();
            }
           	catch (UnsupportedAudioFileException e) {
                e.printStackTrace();
            }
            AudioFormat format = stream.getFormat();
            info2 = new DataLine.Info(Clip.class,
            		stream.getFormat(),
                    ((int) stream.getFrameLength() *
                    		format.getFrameSize()));
            info3 = new DataLine.Info(Clip.class,
            		stream2.getFormat(),
                    ((int) stream2.getFrameLength() *
                    		format.getFrameSize()));
            info4 = new DataLine.Info(Clip.class,
            		stream3.getFormat(),
                    ((int) stream3.getFrameLength() *
                    		format.getFrameSize()));
            info5 = new DataLine.Info(Clip.class,
            		stream4.getFormat(),
                    ((int) stream4.getFrameLength() *
                    		format.getFrameSize()));
            info6 = new DataLine.Info(Clip.class,
            		stream5.getFormat(),
                    ((int) stream5.getFrameLength() *
                    		format.getFrameSize()));
    		try {
                clip = (Clip) AudioSystem.getLine(info2);
                clip.open(stream);
                clip2 = (Clip) AudioSystem.getLine(info3);
                clip2.open(stream2);
                clip3 = (Clip) AudioSystem.getLine(info4);
                clip3.open(stream3);
                clip4 = (Clip) AudioSystem.getLine(info5);
                clip4.open(stream4);
                clip5 = (Clip) AudioSystem.getLine(info6);
                clip5.open(stream5);
    		}
    		catch (LineUnavailableException ex) {
    		}
        	catch (IOException e) {
            }

            clip.start();
    	}
    	else
			System.out.println("Sem Som......");

    	stepBarrierPast  = brain.initiatePastTime();
        stepBarrierDecision   = brain.initiateDecision();
        stepBarrierDecision2  = brain.initiateDecision2();
        stepBarrierCerebellum = brain.initiateCerebellum();
        stepBarrierSleep 	 = brain.initiateSleep();
		stepBarrierAct   = brain.initiateAct();
		try {
            while(!interrupted() && !Neuron.end)
                if (pause)
                    sleep(200); // Espera pelo Mentor (ms)
                else {
                	brain.past.startTime();
                    runStepBrain();
                    sleep(TimeSlize); // Espera ciclo
                    brain.past.addTime();
                }
        }
        catch(InterruptedException e) {
        }
        line.close();																// NXT
        System.out.println("End of Mind Thread...");
    }
}