

//
// Core Program for TETDM 
// PopUpForKnowledgeCreation.java Version 1.00
// Copyright(C) 2012-2018 TETDM CORE MEMBER ALL RIGHTS RESERVED.
// This program is provided under the license.
//

package source;

import source.TextData.*;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;

import net.reduls.igo.Tagger;
import net.reduls.igo.Morpheme;

            /////////MAX SCENE NUMBER line : 643

public class PopUpForKnowledgeCreation extends JFrame implements ActionListener
{
	KnowledgeCreationPanel knowledgeCreationPanel;

	double heightMargin = 250.0;

	String windowName = "KNOWLEDGE";
	
	Control control;
    int width, height;
	
	JPanel buttonPanel;
	
	JButton mergeButton;
//	JToggleButton resultButton;
	
//	JPanel displayPatternPanel;
	JButton listButton;
	JButton springButton;
	
	JButton goButton, backButton;
	
    JButton resetButton;
    
    JPanel importanceSelectPanel;
    JToggleButton importanceButton[];
	ButtonGroup group;
	
	String inJapanese[];



	JPanel resultPanel, mergePanel[];
	JLabel result, merge[], multi;
	JTextField resultText, mergeText[];
    int maxInterpretation = 3;
    JCheckBox interpretationSelection[][];
    JPanel interpretationSelectionPanel[][];
	JPanel checkBoxPanel[];

    //For add sceneData
    PopUpForKnowledgeCreation(Control control)
    {
        this.control = control;
        knowledgeCreationPanel = new KnowledgeCreationPanel();
    }
    
    //For add sceneData
    PopUpForKnowledgeCreation(Control control, int deleteNumber)
    {
        this.control = control;
        knowledgeCreationPanel = new KnowledgeCreationPanel(deleteNumber);
    }

	PopUpForKnowledgeCreation(int X, int Y, int width, int height, Control control, String windowTitle, String creationTitle)
	{
		super(windowTitle);

		this.control = control;
        this.width = width;
        this.height = height;
		
        WINDOWACTIONLOG windowActionLog = new WINDOWACTIONLOG(this, windowName);
        this.addComponentListener(windowActionLog.componentListener);                    //FOR LOG
        this.addWindowListener(new MyWindowListener());
		
//		setAlwaysOnTop(true);
		
		inJapanese = FILEIO.TextFileAllReadCodeArray(new File(control.absolutePath+"source"+File.separator+"japaneseText"+File.separator+"JapaneseKnowledgeCreation.txt"));		
				
		knowledgeCreationPanel = new KnowledgeCreationPanel(creationTitle);		
		add(knowledgeCreationPanel);
		


		buttonPanel = new JPanel(new GridLayout(3+maxInterpretation,1));



		buttonPanel.setBackground(Color.YELLOW);
		add(buttonPanel, BorderLayout.SOUTH);
		
		if(control.sp1.inJapanese)
		{
//			resultButton = new JToggleButton(inJapanese[1]);	
			mergeButton = new JButton(inJapanese[2]);
			listButton = new JButton(inJapanese[3]);			
			springButton = new JButton(inJapanese[4]);
			goButton = new JButton(">>");
			backButton = new JButton("<<");
            resetButton = new JButton(inJapanese[28]);

		}
		else
		{
//			resultButton = new JToggleButton("INTERPRETATION");	
			mergeButton = new JButton("MERGE");
			listButton = new JButton("LIST");
			springButton = new JButton("DISTRIBUTION");
			goButton = new JButton("GO");
			backButton = new JButton("BACK");
            resetButton = new JButton("RESET HISTORY");
		}
		
        //importance select

        importanceSelectPanel = new JPanel(new GridLayout(1,10));

        importanceButton = new JToggleButton[5];
        group = new ButtonGroup();
        
        String label[] = {"ALL","2+","3+","4+","5"};
        
        for(int i=0;i<5;i++)
        {
            importanceButton[i] = new JToggleButton(label[i]);
            importanceButton[i].setOpaque(true);
			importanceButton[i].setBackground(Color.yellow);
            importanceButton[i].addActionListener(this);
            importanceSelectPanel.add(importanceButton[i]);
            group.add(importanceButton[i]);
        }
        importanceButton[0].setSelected(true);
		
		listButton.setOpaque(true);
		springButton.setOpaque(true);
		listButton.setBackground(Color.yellow);
		springButton.setBackground(Color.yellow);
		
		importanceSelectPanel.add(listButton);
		importanceSelectPanel.add(springButton);
		listButton.addActionListener(this);
		springButton.addActionListener(this);	
		
		backButton.setOpaque(true);
		goButton.setOpaque(true);
		backButton.setBackground(Color.yellow);
		goButton.setBackground(Color.yellow);		
		
		importanceSelectPanel.add(backButton);		
		importanceSelectPanel.add(goButton);
		backButton.addActionListener(this);
		goButton.addActionListener(this);

		backButton.setEnabled(false);
		goButton.setEnabled(false);
        
        resetButton.setOpaque(true);
        resetButton.setBackground(Color.yellow);
        importanceSelectPanel.add(resetButton);
        resetButton.addActionListener(this);
	
        buttonPanel.add(importanceSelectPanel);
        
        checkGoBackButton();
        //
     
		/*
		resultButton.addActionListener(this);		
		buttonPanel.add(resultButton);
		resultButton.setEnabled(false);//After nodes are combined, input interpretations should be saved and results should be revised, too.
						//Because the input interpretation will be vanished when a user pushes this button.
		*/
		 
		resultPanel = new JPanel(new BorderLayout());
		resultPanel.setBackground(Color.YELLOW);
		buttonPanel.add(resultPanel);		

        mergePanel = new JPanel[maxInterpretation];
        for(int i=0;i<maxInterpretation;i++)
        {
            mergePanel[i] = new JPanel(new BorderLayout());
            mergePanel[i].setBackground(Color.YELLOW);
            buttonPanel.add(mergePanel[i]);
        }
	
		merge = new JLabel[maxInterpretation];
        mergeText = new JTextField[maxInterpretation];
        interpretationSelection = new JCheckBox[2][maxInterpretation];
        interpretationSelectionPanel = new JPanel[2][maxInterpretation];
		checkBoxPanel = new JPanel[maxInterpretation+1];
        
		if(control.sp1.inJapanese)
		{		
			result = new JLabel(inJapanese[12]);
            for(int i=0;i<maxInterpretation;i++)
                merge[i] = new JLabel(inJapanese[13]+(i+1)+inJapanese[16]);
            multi = new JLabel(inJapanese[17]);

			resultText = new JTextField(inJapanese[14]);
            mergeText[0] = new JTextField(inJapanese[15]);
            for(int i=1;i<maxInterpretation;i++)
                mergeText[i] = new JTextField(inJapanese[18]);
		}
		else
		{
			result = new JLabel("RESULT: ");
			for(int i=0;i<maxInterpretation;i++)
                merge[i] = new JLabel("MERGE: ");
            multi = new JLabel("MULTI");

			resultText = new JTextField("");
            for(int i=0;i<maxInterpretation;i++)
                mergeText[i] = new JTextField("");
		}

		result.setBackground(Color.YELLOW);		
		resultPanel.add(result, BorderLayout.WEST);
		resultPanel.add(resultText);
		resultPanel.add(multi, BorderLayout.EAST);

        for(int i=0;i<maxInterpretation;i++)
        {
            merge[i].setBackground(Color.YELLOW);
			checkBoxPanel[i] = new JPanel(new GridLayout(1,2));
//			checkBoxPanel[i].setBackground(Color.YELLOW);
			for(int j=0;j<2;j++)
			{
				interpretationSelection[j][i] = new JCheckBox();
                interpretationSelectionPanel[j][i] = new JPanel(new GridLayout(1,1));
                if(j==0)
				{
                    interpretationSelectionPanel[j][i].setBackground(new Color(0xff,0x00,0x99));
					interpretationSelection[j][i].setBackground(new Color(0xff,0x00,0x99));
				}
                else
				{			
                    interpretationSelectionPanel[j][i].setBackground(Color.green);
					interpretationSelection[j][i].setBackground(Color.green);
				}
                interpretationSelectionPanel[j][i].add(interpretationSelection[j][i]);
				checkBoxPanel[i].add(interpretationSelectionPanel[j][i]);
			}

            mergePanel[i].add(checkBoxPanel[i], BorderLayout.EAST);
            mergePanel[i].add(merge[i], BorderLayout.WEST);
       		mergePanel[i].add(mergeText[i]);
        }

		mergeButton.setBackground(Color.YELLOW);
		mergeButton.addActionListener(this);
		buttonPanel.add(mergeButton);
		/*
		displayPatternPanel = new JPanel(new GridLayout(1,2));
		
		displayPatternPanel.add(listButton);		
		displayPatternPanel.add(springButton);
		buttonPanel.add(displayPatternPanel);
		
		listButton.addActionListener(this);
		springButton.addActionListener(this);		
		*/		

	
		setVisible(true);
		
		
		
		setBounds(X-100, Y, 1080, height);
		
        control.navigationControl.setSoundNumber(1010);
	}
	
	public void subWindowClose()
	{
//        knowledgeCreationPanel.closeHistoryWindow();
	}

	void checkGoBackButton()
	{
		if(knowledgeCreationPanel.currentSceneNumber < knowledgeCreationPanel.maxSceneNumber)
			goButton.setEnabled(true);
		else
			goButton.setEnabled(false);
		
		if(knowledgeCreationPanel.currentSceneNumber > 1)
			backButton.setEnabled(true);
		else
			backButton.setEnabled(false);
	}
	
	///////////////// EXP ///////////////
	public void buttonExp(ActionEvent e)
	{
		int number = -1;
		
		if(e.getSource() ==  mergeButton)
			number = 0;
		if(e.getSource() == listButton)
			number = 1;
		if(e.getSource() == springButton)
			number = 2;
		if(e.getSource() == goButton)
			number = 3;
		if(e.getSource() == backButton)
			number = 4;		
		
		
		if(number >= 0)
			addExpByKnowledgeButton(number);			
		
	}
	
	public void addExpByKnowledgeButton(int number)
	{
		control.ex1.addExpByKnowledgeButton(number);
		if(control.expPanel != null)		
			control.expPanel.repaint();		
	}
	
	public String getButtonName(ActionEvent e)
	{
		return control.getButtonName(e);
	}

	
	

	//Action listener
	public void actionPerformed(ActionEvent e)
	{
		///////////////// EXP ///////////////
		buttonExp(e);
		
//		String buttonName = getButtonName(e);
	
		for(int i=0;i<5;i++)
			if(e.getSource() == importanceButton[i])
			{
                int importanceThreshold = i+1;
                System.out.println("THRESHOLD: "+importanceThreshold);
//                parent.changeThreshold(importanceThreshold);
                
                knowledgeCreationPanel.changeThreshold(importanceThreshold);
                
                StoryControl.nextSerif(6001 + i);
                return;
			}
/*        
		if(e.getSource() == resultButton)
		{
			String dataName[] = new String[knowledgeCreationPanel.totalDataNumber];
			
			if(resultButton.isSelected())
			{
				knowledgeCreationPanel.setResultText(dataName);

				if(control.sp1.inJapanese)
					resultButton.setText(inJapanese[0]);
				else			
					resultButton.setText("RESULT");
			}
			else
			{
				knowledgeCreationPanel.setInterpretationText(dataName);
				
				if(control.sp1.inJapanese)
					resultButton.setText(inJapanese[1]);
				else			
					resultButton.setText("INTERPRETATION");			
			}
			
			knowledgeCreationPanel.network.setNodeWord(dataName);
			knowledgeCreationPanel.repaint();
		}
*/		
		
		
		if(e.getSource() == mergeButton)
		{
			if(knowledgeCreationPanel.scene.dataNumber <= 1)
				return;
			knowledgeCreationPanel.mergeData();
			knowledgeCreationPanel.scene.reArrangeData();
            knowledgeCreationPanel.saveScenes();
            
            StoryControl.nextSerif(6006);
		}
		
		if(e.getSource() == listButton)
		{
			knowledgeCreationPanel.scene.reArrangeData();
			
//			knowledgeCreationPanel.linkDisplay = false;
			knowledgeCreationPanel.repaint();
            
            StoryControl.nextSerif(6007);
		}
		
		if(e.getSource() == springButton)
		{
			knowledgeCreationPanel.scene.network.linkThreshold = 0.0;
			knowledgeCreationPanel.scene.network.createLinksFromValue();				
			knowledgeCreationPanel.scene.network.object[0].x = getWidth();
			knowledgeCreationPanel.scene.network.startSpringModel(getWidth(), (int)(getHeight()-heightMargin));
			knowledgeCreationPanel.scene.network.linkThreshold = 0.01;
			knowledgeCreationPanel.scene.network.createLinksFromValue();
			
			knowledgeCreationPanel.linkDisplay = true;			
			knowledgeCreationPanel.repaint();
            
            StoryControl.nextSerif(6008);
		}
		
		if(e.getSource() == goButton)
		{
			knowledgeCreationPanel.goScene();
			checkGoBackButton();
            
            StoryControl.nextSerif(6009);
		}	
		
		if(e.getSource() == backButton)
		{
			knowledgeCreationPanel.backScene();
			checkGoBackButton();
            
            StoryControl.nextSerif(6010);
		}

		if(e.getSource() == resetButton)
		{
			int option;
			if(control.sp1.inJapanese)
				option = JOptionPane.showConfirmDialog(this, inJapanese[29], inJapanese[30], JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
			else
				option = JOptionPane.showConfirmDialog(this, "REALLY OK?", "OK", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
			
			if(option != JOptionPane.YES_OPTION)
				return;
            
            FILEIO.deleteFile(knowledgeCreationPanel.sceneDataFile);
            
            control.closePopForKnowledgeCreation();
            
            StoryControl.nextSerif(6011);
		}

	}

	class MyWindowListener extends WindowAdapter {
		
		public void windowClosing(WindowEvent e) // x button
		{
			subWindowClose();
			control.bt78.setSelected(false);			
		}		
		
		public void windowClosed(WindowEvent e) 
		{
			subWindowClose();
			control.bt78.setSelected(false);			
		}
	}
	
	

	
///////////////////////	
	
	class KnowledgeCreationScene
	{	
		int dataNumber;	
		int currentNumber;// active node number
        int totalDataNumber; //Initial Data Number
		
		String dataName[];
		
		DisplayNetwork network;		
		
		boolean selected[];
				
		int mergedNodeNumber[];
		
		int fontSize;
		
		int importance[];
		
		Image smallImage[];
		int imageSize = 50;
		
		Color nodeColor[];
        
		String wordList[][];
        Color colorList[][];
        int wordNumber[];
		
		int dataType[];	//0:Cause+Result<implicit>, 1:Cause, 2:Result, 3:Cause+Result<explicit>
		
        boolean combinedOriginalNumber[][];
		
		KnowledgeCreationScene(int dataNumber, int dataType[], String dataName[], int importance[], Image smallImage[], boolean combinedOriginalNumber[][], int totalDataNumber)
		{
			nodeColor = new Color[5];
			nodeColor[0] = new Color(0x00,0xbb,0xbb);
			nodeColor[1] = new Color(0x00,0x45,0xff);
			nodeColor[2] = Color.black;//new Color(0x00,0x64,0x00);
			nodeColor[3] = new Color(0xff,0x45,0x00);
			nodeColor[4] = new Color(0xff,0x00,0x00);			
			
			this.dataNumber = dataNumber;
            this.totalDataNumber = totalDataNumber;

			this.dataType = new int[dataNumber];
			for(int i=0;i<dataNumber;i++)
				this.dataType[i] = dataType[i];
			
			fontSize = 16;
			
			if(fontSize > (height-heightMargin) / dataNumber)
				fontSize = (int)((height-heightMargin) / dataNumber);			
			
			this.dataName = new String[dataNumber];
			for(int i=0;i<dataNumber;i++)
				this.dataName[i] = dataName[i];
			network = new DisplayNetwork(dataName, fontSize, Color.black, control.sp1.fontName);
			
			selected = new boolean[dataNumber];
						

            
            this.importance = new int[dataNumber];
			for(int i=0;i<dataNumber;i++)
				this.importance[i] = importance[i];
			
			this.smallImage = new Image[dataNumber];
            
            this.combinedOriginalNumber = new boolean[dataNumber][totalDataNumber];
			
			for(int i=0;i<dataNumber;i++)
			{
				network.object[i].id = i;
				network.object[i].x = 80+i;
                if(dataType[i] == 0 || dataType[i] == 3)
                    network.object[i].x += width/4;
                if(dataType[i] == 2)
                    network.object[i].x += width/2;
				network.object[i].y = (height-heightMargin) / dataNumber * i + 5 + imageSize;
				
				network.object[i].fontSize = fontSize;
				network.object[i].color = nodeColor[importance[i]-1];
				
				network.object[i].active = true;
				
				selected[i] = false;
				
				this.smallImage[i] = smallImage[i];
                
                for(int j=0;j<totalDataNumber;j++)
                    this.combinedOriginalNumber[i][j] = combinedOriginalNumber[i][j];
			}
            
			mergedNodeNumber = new int[dataNumber];
			for(int i=0;i<dataNumber;i++)
				mergedNodeNumber[i] = countMergedNumber(i);
			
			calculateCosValue();
            
			network.linkThreshold = 0.01;
			network.createLinksFromValue();

		}
        
        int countMergedNumber(int index)
        {
            int count=0;
            for(int i=0;i<totalDataNumber;i++)
                if(combinedOriginalNumber[index][i])
                    count++;
            return count;
        }
		
		void calculateCosValue()
		{
			int coFrequency[][] = new int[dataNumber][dataNumber];
            String keywordList[][] = new String[dataNumber][100];
            int keywordListID[][] = new int[dataNumber][100];
            int keywordSpeechList[][] = new int[dataNumber][100];
            int keywordNumber[] = new int[dataNumber];
            
            Color speechColor[] = new Color[3];
            speechColor[0] = Color.red;
            speechColor[1] = Color.pink;
            speechColor[2] = Color.green;
            
			
			wordList = new String[dataNumber][100];
            colorList = new Color[dataNumber][100];
			wordNumber = new int[dataNumber];

			
			try{						
				final String dicDir = control.sp1.dictionaryPath+"/ipadic";
				final Tagger tagger = new Tagger(dicDir);
				
				for(int i=0;i<dataNumber;i++)
				{
					keywordNumber[i] = 0;
					wordNumber[i] = 0;
                    
					for(Morpheme m : tagger.parse(network.object[i].word))
					{
						String speech[] = m.feature.split(",");
						for(int j=0;j<3;j++)
                        {
							if(speech[0].equals(inJapanese[5+j]))
                            {
//								keywordList[i][keywordNumber[i]++] = m.surface;
                                
                                keywordListID[i][keywordNumber[i]] = wordNumber[i];
//                                System.out.println("i,wordNumber[i],keywordNumber[i] "+"("+i+","+wordNumber[i]+","+keywordNumber[i]+",");
                                keywordSpeechList[i][keywordNumber[i]] = j;
                                if(!speech[6].equals("*"))
                                    keywordList[i][keywordNumber[i]++] = speech[6];
                                else
                                    keywordList[i][keywordNumber[i]++] = m.surface;
                            }

                        }

                        colorList[i][wordNumber[i]] = Color.black;
                        wordList[i][wordNumber[i]++] = m.surface;
					}
				}
			}
			catch(Exception e){
				System.out.println("writing ERROR in PopUpForKnowledgeCreation.java");
			}			
			
			for(int i=0;i<dataNumber;i++)
				for(int j=0;j<i;j++)
				{
					coFrequency[i][j] = 0;
					
					for(int m=0;m<keywordNumber[i];m++)
						for(int n=0;n<keywordNumber[j];n++)
                        {
//                            System.out.println(keywordList[i][m]+" - "+keywordList[j][n]+"("+i+","+m+","+j+","+n+")");
                            
							if(keywordList[i][m].equals(keywordList[j][n]))
                            {
//                                System.out.println(keywordList[i][m]+" - "+keywordList[j][n]+"("+i+","+m+","+j+","+n+")");
                                
                                colorList[i][keywordListID[i][m]] = speechColor[keywordSpeechList[i][m]];
                                colorList[j][keywordListID[j][n]] = speechColor[keywordSpeechList[j][n]];
								coFrequency[i][j]++;
                            }
                        }
				}
			
			for(int i=0;i<dataNumber;i++)
				for(int j=0;j<=i;j++)
					if(keywordNumber[i] == 0 || keywordNumber[j] == 0)
					{
						if(i != j)
							network.value[i][j] = network.value[j][i] = 0.0;
						else
							network.value[i][j] = network.value[j][i] = 1.0;
					}
					else
					{
						network.value[i][j] = network.value[j][i] = (double)coFrequency[i][j] / Math.sqrt(keywordNumber[i] * keywordNumber[j]);
					}
            

		}
	
		void reArrangeData()
		{
			fontSize = 16;
			
			if(fontSize > (height-heightMargin) / dataNumber)
				fontSize = (int)((height-heightMargin) / dataNumber);
			
			for(int i=0, count=0;i<dataNumber;i++)
			{
				if(network.object[i].active == true)
				{
					network.object[i].x = 80+count;
                    if(dataType[i] == 0 || dataType[i] == 3)
                        network.object[i].x += width/4;
                    if(dataType[i] == 2)
                        network.object[i].x += width/2;
                        
					network.object[i].y = (height-heightMargin) / dataNumber * count + 5 + imageSize;
					
					network.object[i].fontSize = fontSize + mergedNodeNumber[i];
					network.object[i].color = nodeColor[importance[i]-1];					
					count++;
				}
			}
			calculateCosValue();			
		}
		
        void changeThreshold(int threshold)
        {
            currentNumber = 0;
            
            for(int i=0;i<dataNumber;i++)
			{
				selected[i] = false;
                if(importance[i] < threshold)
                    network.object[i].active = false;
                else
                {
                    network.object[i].active = true;
                    currentNumber++;
                }
			}
        }
		
        public void saveScene(BufferedWriter bw)
        {
            try{
                
                bw.write("dataNumber="+dataNumber);
                bw.newLine();

                for(int i=0;i<dataNumber;i++)
                {
                    bw.write("dataType="+dataType[i]);
                    bw.newLine();

                    bw.write("dataName="+dataName[i]);
                    bw.newLine();
                    
                    bw.write("importance="+importance[i]);
                    bw.newLine();
                
                    for(int j=0;j<totalDataNumber;j++)
                    {
                        bw.write("combinedOriginalNumber["+j+"]="+combinedOriginalNumber[i][j]);
                        bw.newLine();
                    }
                }
            }
            catch(Exception e){
                System.out.println("Text creating ERROR for sceneDataFile in SaveScene");
            }
        }
	}

	
	
	
class KnowledgeCreationPanel extends JPanel implements MouseListener, MouseMotionListener
	{
		KnowledgeCreationScene knowledgeCreationScene[];
		int currentSceneNumber = 0;
        int maxSceneNumber = 0;
		int maxTotalSceneNumber = 0;
					
		KnowledgeCreationScene scene;//reference only
	
        String resultTexts[];
		int totalDataNumber;
		int checkEnd = 0;
		
		int touchNumber, oldTouchNumber;
		int clickNumber;

		
		//For objects operation
		int mouseX, mouseY;			//Coordinates for a mouse
		
		boolean fieldMove;		//Flag for field moving
		int oldMouseX, oldMouseY;	//Last Coordinates for a mosue		

		int mergeTimes = 0;
		
		boolean linkDisplay = true;
		
//        HistoryWindow historyWindow;
        int historyX,historyY,historyWidth,historyHeight;
        String message[];
        
        int posX, posY;
        int sizeX, sizeY;
        
		boolean multiSelected = false;
		
		String creationTitle;

            File sceneDataFile = new File(control.absolutePath+"interpretation"+File.separator+"sceneData");
        
        /////////
        class SceneData
        {
            int dataNumber;
            int dataType[];
            String dataName[];
            int importance[];
            boolean combinedOriginalNumber[][];
            
            Image smallImage[];
            
            SceneData(){}
            
            public void createSmallImageData()
            {
                smallImage = new Image[dataNumber];
                
                for(int i=0;i<dataNumber;i++)
                {
                    int count=0, lastIndex = -1;
                    for(int j=0;j<totalDataNumber;j++)
                        if(combinedOriginalNumber[i][j] == true)
                        {
                            count++;
                            lastIndex = j;
                        }
                    if(count > 1)
                        smallImage[i] = null;
                    else
                        smallImage[i] = control.interpretation[lastIndex].smallImg;
                }
            }
            
            public void loadScene(BufferedReader br, int totalDNumber)
            {
                try
                {
                    String lineData[] = br.readLine().split("=");
                    dataNumber = Integer.parseInt(lineData[1]);
                    
                    dataType = new int[dataNumber];
                    dataName = new String[dataNumber];
                    importance = new int[dataNumber];
                    combinedOriginalNumber = new boolean[dataNumber][totalDNumber];

                    for(int i=0;i<dataNumber;i++)
                    {
                        lineData = br.readLine().split("=");
                        dataType[i] = Integer.parseInt(lineData[1]);
                    
                        lineData = br.readLine().split("=");
                        dataName[i] = lineData[1];
                    
                        lineData = br.readLine().split("=");
                        importance[i] = Integer.parseInt(lineData[1]);
                    
                    
                        for(int j=0;j<totalDNumber;j++)
                        {
                            lineData = br.readLine().split("=");
                            combinedOriginalNumber[i][j] = Boolean.valueOf(lineData[1]);
                        }
                    }
                }
                catch(Exception e){
                    System.out.println("Text Reading ERROR in loadScene in SceneData");
                }
            }
        }

        public void saveScenes()
        {

            String sceneDataText="";
            
            try
            {
                StringWriter sw1 = new StringWriter();
                BufferedWriter bw1 = new BufferedWriter(sw1);
                
                bw1.write("creationTitle="+creationTitle);
                bw1.newLine();
                
                bw1.write("maxSceneNumber="+maxSceneNumber);
                bw1.newLine();
                
                bw1.write("totalDataNumber="+totalDataNumber);
                bw1.newLine();
 
                for(int i=0;i<maxSceneNumber;i++)
                    knowledgeCreationScene[i].saveScene(bw1);
                
                bw1.flush();
                sw1.flush();
                sceneDataText = sw1.toString();
                bw1.close();
                sw1.close();
            }
            catch(Exception e){
                System.out.println("Text creating ERROR for "+sceneDataFile);
            }
            
            FILEIO.TextFileWriteCode(sceneDataFile, sceneDataText, "SJIS");
        }
        
        public void saveScenesSimple(SceneData newSceneData[])
        {
            
            String sceneDataText="";
            
            try
            {
                StringWriter sw1 = new StringWriter();
                BufferedWriter bw1 = new BufferedWriter(sw1);
                
                bw1.write("creationTitle="+creationTitle);
                bw1.newLine();
                
                bw1.write("maxSceneNumber="+maxSceneNumber);
                bw1.newLine();
                
                bw1.write("totalDataNumber="+totalDataNumber);
                bw1.newLine();
                
                for(int i=0;i<maxSceneNumber;i++)
                {
                    bw1.write("dataNumber="+newSceneData[i].dataNumber);
                    bw1.newLine();
                
                    for(int j=0;j<newSceneData[i].dataNumber;j++)
                    {
                        bw1.write("dataType="+newSceneData[i].dataType[j]);
                        bw1.newLine();
                    
                        bw1.write("dataName="+newSceneData[i].dataName[j]);
                        bw1.newLine();
                    
                        bw1.write("importance="+newSceneData[i].importance[j]);
                        bw1.newLine();
                    
                        for(int k=0;k<totalDataNumber;k++)
                        {
                            bw1.write("combinedOriginalNumber["+j+"]="+newSceneData[i].combinedOriginalNumber[j][k]);
                            bw1.newLine();
                        }
                    }
                }
                
                bw1.flush();
                sw1.flush();
                sceneDataText = sw1.toString();
                bw1.close();
                sw1.close();
            }
            catch(Exception e){
                System.out.println("Text creating ERROR SIMPLE for "+sceneDataFile);
            }
            
            FILEIO.TextFileWriteCode(sceneDataFile, sceneDataText, "SJIS");
        }
        
            public void loadScenes()
            {
                String sceneDataText = FILEIO.TextFileAllReadCode(sceneDataFile);
                String lineData[];
                try
                {
                    BufferedReader br1 = new BufferedReader(new StringReader(sceneDataText));


					lineData = br1.readLine().split("=");
					if(creationTitle.equals(""))
					{					
						if(lineData.length == 1)
							creationTitle = " ";
						else
							creationTitle = lineData[1];
					}

                    lineData = br1.readLine().split("=");
                    maxSceneNumber = Integer.parseInt(lineData[1]);

                    lineData = br1.readLine().split("=");
                    totalDataNumber = Integer.parseInt(lineData[1]);

                    maxTotalSceneNumber = totalDataNumber*2;

                    SceneData sceneData[] = new SceneData[maxSceneNumber];
                    knowledgeCreationScene = new KnowledgeCreationScene[maxTotalSceneNumber];
                

                    for(int i=0;i<maxSceneNumber;i++)
                    {
                        sceneData[i] = new SceneData();
                        sceneData[i].loadScene(br1, totalDataNumber);
                        sceneData[i].createSmallImageData();

                        knowledgeCreationScene[i] = new KnowledgeCreationScene(sceneData[i].dataNumber, sceneData[i].dataType, sceneData[i].dataName, sceneData[i].importance, sceneData[i].smallImage, sceneData[i].combinedOriginalNumber, totalDataNumber);
                        
                        knowledgeCreationScene[i].reArrangeData();
                    }
                    
                }
                catch(Exception e){
                    System.out.println("Text Reading ERROR in "+sceneDataFile);
                }
                
				System.out.println("maxSceneNumber="+maxSceneNumber);
				
                scene = knowledgeCreationScene[0];
                currentSceneNumber = 1;
            }
        


        ////////
        
        //For add sceneData
        KnowledgeCreationPanel()
        {
			if(!sceneDataFile.exists())
				return;			
			
            SceneData sceneData[] = new SceneData[1];
            SceneData newSceneData[];
            
            ///////LOAD
            String sceneDataText = FILEIO.TextFileAllReadCode(sceneDataFile);
            String lineData[];
            try
            {
                BufferedReader br1 = new BufferedReader(new StringReader(sceneDataText));
                
                lineData = br1.readLine().split("=");
				if(lineData.length == 1)
					creationTitle = " ";
				else
					creationTitle = lineData[1];				
                
                lineData = br1.readLine().split("=");
                maxSceneNumber = Integer.parseInt(lineData[1]);
                
                lineData = br1.readLine().split("=");
                totalDataNumber = Integer.parseInt(lineData[1]);
                
                sceneData = new SceneData[maxSceneNumber];
                
                for(int i=0;i<maxSceneNumber;i++)
                {
                    sceneData[i] = new SceneData();
                    sceneData[i].loadScene(br1, totalDataNumber);
                }
            }
            catch(Exception e){
                System.out.println("Text Reading ERROR SIMPLE in "+sceneDataFile);
            }
            ////////
            
            
			totalDataNumber = control.interpretationNumber;
            newSceneData = new SceneData[maxSceneNumber];
            
            for(int i=0;i<maxSceneNumber;i++)
            {
                newSceneData[i] = new SceneData();
                
                int sceneDataNumber = sceneData[i].dataNumber;
                
                newSceneData[i].dataType = new int[sceneDataNumber+1];
                newSceneData[i].dataName = new String[sceneDataNumber+1];
                newSceneData[i].importance = new int[sceneDataNumber+1];
                newSceneData[i].combinedOriginalNumber = new boolean[sceneDataNumber+1][totalDataNumber];
                
                for(int j=0;j<sceneDataNumber;j++)
                {
                    newSceneData[i].dataType[j] = sceneData[i].dataType[j];
                    newSceneData[i].dataName[j] = sceneData[i].dataName[j];
                    newSceneData[i].importance[j] = sceneData[i].importance[j];
                    for(int k=0;k<totalDataNumber-1;k++)
                        newSceneData[i].combinedOriginalNumber[j][k] = sceneData[i].combinedOriginalNumber[j][k];
                }
                
                newSceneData[i].dataType[sceneDataNumber] = 0;
                newSceneData[i].dataName[sceneDataNumber] = control.interpretation[totalDataNumber-1].meaning;
                newSceneData[i].importance[sceneDataNumber] = control.interpretation[totalDataNumber-1].importance;
                for(int k=0;k<totalDataNumber-2;k++)
                    newSceneData[i].combinedOriginalNumber[sceneDataNumber][k] = false;
                newSceneData[i].combinedOriginalNumber[sceneDataNumber][totalDataNumber-1] = true;
                
                newSceneData[i].dataNumber = sceneData[i].dataNumber+1;
            }
			
			System.out.println("maxSceneNumber="+maxSceneNumber);			
            
            saveScenesSimple(newSceneData);
        }
        ////////
        
        //For delete sceneData
        KnowledgeCreationPanel(int deleteNumber)
        {
			if(!sceneDataFile.exists())
				return;
			
            SceneData sceneData[] = new SceneData[1];
            SceneData newSceneData[];
            
            ///////LOAD
            String sceneDataText = FILEIO.TextFileAllReadCode(sceneDataFile);
            String lineData[];
            try
            {
                BufferedReader br1 = new BufferedReader(new StringReader(sceneDataText));
                
                lineData = br1.readLine().split("=");
				if(lineData.length == 1)
					creationTitle = " ";
				else
					creationTitle = lineData[1];				
                
                lineData = br1.readLine().split("=");
                maxSceneNumber = Integer.parseInt(lineData[1]);
                
                lineData = br1.readLine().split("=");
                totalDataNumber = Integer.parseInt(lineData[1]);
                
                sceneData = new SceneData[maxSceneNumber];
                
                for(int i=0;i<maxSceneNumber;i++)
                {
                    sceneData[i] = new SceneData();
                    sceneData[i].loadScene(br1, totalDataNumber);
                }
            }
            catch(Exception e){
                System.out.println("Text Reading ERROR SIMPLE in "+sceneDataFile);
            }
            ////////
            
            
			totalDataNumber = control.interpretationNumber; ///// -1
            newSceneData = new SceneData[maxSceneNumber];
            

            
            for(int i=0;i<maxSceneNumber;i++)
            {
                int sceneDataNumber = sceneData[i].dataNumber;
                int count = 0;
                boolean checkOriginal[] = new boolean[totalDataNumber];
                
                for(int k=0;k<totalDataNumber;k++)
                    checkOriginal[k] = false;
                
                
                for(int j=0;j<sceneDataNumber;j++)
                    if(sceneData[i].combinedOriginalNumber[j][deleteNumber] == true)
                        count++;
                    else
                    {
                        int count4=0;
                        for(int k=0;k<totalDataNumber+1;k++)
                            if(k != deleteNumber)
                            {
                                if(sceneData[i].combinedOriginalNumber[j][k] == true)
                                    checkOriginal[count4] = true;
                                count4++;
                            }
                    }

                /////

                newSceneData[i] = new SceneData();
                newSceneData[i].dataNumber = sceneDataNumber - count; // decrease delete node number
                if(newSceneData[i].dataNumber == 0) // no nodes are combined
                {
                    maxSceneNumber = i;
                    break;
                }
                
                //////
                int count3=0;
                for(int k=0;k<totalDataNumber;k++)
                    if(checkOriginal[k] == false)
                        count3++;   //not included in any nodes

                
                newSceneData[i].dataNumber += count3;	// increase not used node number
//                if(i != 0 && newSceneData[i].dataNumber == totalDataNumber) // all nodes are not combined
  //              {
    //                maxSceneNumber = i;
      //              break;
        //        }
                
                //////
                
                newSceneData[i].dataType = new int[newSceneData[i].dataNumber];
                newSceneData[i].dataName = new String[newSceneData[i].dataNumber];
                newSceneData[i].importance = new int[newSceneData[i].dataNumber];
                newSceneData[i].combinedOriginalNumber = new boolean[newSceneData[i].dataNumber][totalDataNumber];
                
                count=0;
                for(int j=0;j<sceneDataNumber;j++)
                    if(sceneData[i].combinedOriginalNumber[j][deleteNumber] == false)
                    {
                        newSceneData[i].dataType[count] = sceneData[i].dataType[j];
                        newSceneData[i].dataName[count] = sceneData[i].dataName[j];
                        newSceneData[i].importance[count] = sceneData[i].importance[j];

                        int count2=0;
                        for(int k=0;k<totalDataNumber+1;k++)
                        {
                            if(k != deleteNumber)
                            {
                                newSceneData[i].combinedOriginalNumber[count][count2] = sceneData[i].combinedOriginalNumber[j][k];
                                count2++;
                            }
                        }
                        count++;
                    }
                
                ///////
                count3=0;
                for(int k=0;k<totalDataNumber;k++)
                    if(checkOriginal[k] == false)
                    {
                        newSceneData[i].dataType[count] = 0;
                        newSceneData[i].dataName[count] = control.interpretation[k].meaning;
                        newSceneData[i].importance[count] = control.interpretation[k].importance;
                        
                        for(int j=0;j<totalDataNumber;j++)
                            if(j == k)
                                newSceneData[i].combinedOriginalNumber[count][j] = true;
                            else
                                newSceneData[i].combinedOriginalNumber[count][j] = false;
                        
                        count++;
                        count3++;   //not included in any nodes
                    }
                
                ///////
                
            }
			
			////// FOR DELETING SCENES THAT INCLUDE COMBINED NODES
			int count=0;
            for(int i=1;i<maxSceneNumber;i++)
			{
                if(newSceneData[i].dataNumber == totalDataNumber) // all nodes are not combined
					count++;
			}
			
			if(count == maxSceneNumber-1)
				maxSceneNumber = 1;
			else
			{
				int count2=1;
				for(int i=1;i<maxSceneNumber;i++)
					if(newSceneData[i].dataNumber != totalDataNumber)
						newSceneData[count2++] = newSceneData[i];
				
				maxSceneNumber -= count;
			}
			//////
			

			System.out.println("maxSceneNumber="+maxSceneNumber);			
			
			if(maxSceneNumber == 0 || maxSceneNumber == 1)
				FILEIO.deleteFile(sceneDataFile);
			else
				saveScenesSimple(newSceneData);
        }
        
        
        ////////
        
		KnowledgeCreationPanel(String creationTitle)
		{
			addMouseListener(this);			//MouseListener
			addMouseMotionListener(this);	//MouseMotionListener	
			
			this.creationTitle = creationTitle;
			
            if(sceneDataFile.exists())
            {
                loadScenes();
                setResultText();
            }
            else
            {
                setResultText();
                createInitialData();
           	}
            
            //add function to cope with interpretation data added
            //add function to cope with interpretation data deleted
            
			touchNumber = -1;
			oldTouchNumber = -1;
		}
		
		void setResultText()
		{
            resultTexts = new String[control.interpretationNumber];
			for(int i=0;i<control.interpretationNumber;i++)
				resultTexts[i] = control.interpretation[i].result;
		}

		void setInterpretationText(String dataName[])///////////
		{
			for(int i=0;i<control.interpretationNumber;i++)
				dataName[i] = control.interpretation[i].meaning;				
		}
        
		void createInitialData()
		{

			totalDataNumber = control.interpretationNumber;
            maxTotalSceneNumber = totalDataNumber*2;
            //MAX SCENE NUMBER

			
			String dataName[] = new String[totalDataNumber];
			setInterpretationText(dataName);
			
			int importance[] = new int[totalDataNumber];
			Image smallImage[] = new Image[totalDataNumber];
            boolean combinedOriginalNumber[][] = new boolean[totalDataNumber][totalDataNumber];
			int dataType[] = new int[totalDataNumber];
			
			for(int i=0;i<totalDataNumber;i++)
			{
				importance[i] = control.interpretation[i].importance;
				smallImage[i] = control.interpretation[i].smallImg;
                for(int j=0;j<totalDataNumber;j++)
                    combinedOriginalNumber[i][j] = false;
                combinedOriginalNumber[i][i] = true;
				dataType[i] = 0;
			}
		
			knowledgeCreationScene = new KnowledgeCreationScene[maxTotalSceneNumber];

			knowledgeCreationScene[0] = new KnowledgeCreationScene(totalDataNumber, dataType, dataName, importance, smallImage, combinedOriginalNumber, totalDataNumber);
            
			scene = knowledgeCreationScene[currentSceneNumber];

			currentSceneNumber++;

			maxSceneNumber = currentSceneNumber;
		}

		
        void changeThreshold(int threshold)
        {
            scene.changeThreshold(threshold);
            repaint();
        }

		void goScene()
		{
			if(currentSceneNumber < maxSceneNumber)
			{
				currentSceneNumber++;
				scene = knowledgeCreationScene[currentSceneNumber-1];
                
                for(int i=0;i<5;i++)
                    if(importanceButton[i].isSelected())
                    {
                        int importanceThreshold = i+1;
                        System.out.println("SET THRESHOLD: "+importanceThreshold);
                        knowledgeCreationPanel.changeThreshold(importanceThreshold);
                        break;
                    }
                

				checkEnd = checkCreationEnd();
				touchNumber = oldTouchNumber = -1;
			}
			repaint();
		}
		

		void backScene()
		{
			if(currentSceneNumber > 1)
			{
				currentSceneNumber--;
				scene = knowledgeCreationScene[currentSceneNumber-1];
                
                for(int i=0;i<5;i++)
                    if(importanceButton[i].isSelected())
                    {
                        int importanceThreshold = i+1;
                        System.out.println("SET THRESHOLD: "+importanceThreshold);
                        knowledgeCreationPanel.changeThreshold(importanceThreshold);
                        break;
                    }
                
				checkEnd = checkCreationEnd();
				touchNumber = oldTouchNumber = -1;
			}
			repaint();			
		}
				
		void mergeData()
		{
            int createNodeNumber=0;
			String mergedWord = "";
			int mergedNumber = 0;
			int mergedIndex = -1;
			int maxImportance = 0;
			String logData = "";
			
			for(int i=0;i<scene.dataNumber;i++)
				if(scene.selected[i])
					mergedNumber++;
			
			if(mergedNumber <= 1)
				return;
			
			if(checkEnd > 0)
				return;
			
            int checkCount = 0;
            for(int i=0;i<maxInterpretation;i++)
            {
                if((interpretationSelection[0][i].isSelected() || interpretationSelection[1][i].isSelected()) && !mergeText[i].getText().equals(""))
                    checkCount++;
            }
            
            createNodeNumber = checkCount;
            if(createNodeNumber == 0)
                createNodeNumber = 1;
            
			int newDataNumber = scene.dataNumber-(mergedNumber-createNodeNumber);
			String dataName[] = new String[newDataNumber];
			int importance[] = new int[newDataNumber];
			Image smallImage[] = new Image[newDataNumber];
            boolean mergedOriginalNumber[] = new boolean[totalDataNumber];
            boolean combinedOriginalNumber[][] = new boolean[newDataNumber][totalDataNumber];
			int dataType[] = new int[newDataNumber];
            
            for(int i=0;i<totalDataNumber;i++)
                mergedOriginalNumber[i] = false;
            
			int count = 0;
			for(int i=0;i<scene.dataNumber;i++)
			{
				if(scene.selected[i])
				{
					mergedWord += scene.network.object[i].word;
					logData += "MERGED NODE "+i+" : ("+scene.importance[i]+") "+scene.network.object[i].word+System.getProperty("line.separator");
                    
					if(mergedIndex == -1)
					{
						mergedIndex = i;
						maxImportance = scene.importance[i];
//						count++;
					}
					else
					{
						if(scene.importance[i] > maxImportance)
							maxImportance = scene.importance[i];
					}
					scene.selected[i] = false;
                    
                    for(int j=0;j<totalDataNumber;j++)
                        if(scene.combinedOriginalNumber[i][j])
                            mergedOriginalNumber[j] = true;
				}
				else
				{
					dataType[count] = scene.dataType[i];
					dataName[count] = scene.dataName[i];
					importance[count] = scene.importance[i];
					smallImage[count] = scene.smallImage[i];
                    for(int j=0;j<totalDataNumber;j++)
                        combinedOriginalNumber[count][j] = scene.combinedOriginalNumber[i][j];
					count++;
				}
			}
            
            if(checkCount == 0)
            {
                mergedIndex = count;
            
                String inputText="";
            
                for(int i=maxInterpretation-1;i>=0;i--)
                {
                    inputText = mergeText[i].getText();
                    if(!inputText.equals(""))
                        break;
                }
            
                if(!inputText.equals(""))
                {
                    for(int i=0;i<maxInterpretation;i++)
                        mergeText[i].setText("");
                    dataName[mergedIndex] = inputText;
                }
                else
                    dataName[mergedIndex] = mergedWord;

				dataType[mergedIndex] = 0;		// IMPLICIT
                importance[mergedIndex] = maxImportance;
                smallImage[mergedIndex] = null;
                
                for(int j=0;j<totalDataNumber;j++)
                    combinedOriginalNumber[mergedIndex][j] = mergedOriginalNumber[j];
            }
            else
            {
                checkCount = 0;
                mergedIndex = count;
                for(int i=0;i<maxInterpretation;i++)
                {
                    if((interpretationSelection[0][i].isSelected() || interpretationSelection[1][i].isSelected()) && !mergeText[i].getText().equals(""))
                    {
                        dataName[mergedIndex] = mergeText[i].getText();
						if(interpretationSelection[0][i].isSelected() && !interpretationSelection[1][i].isSelected())
							dataType[mergedIndex] = 1;// CAUSE
						else if(!interpretationSelection[0][i].isSelected() && interpretationSelection[1][i].isSelected())
							dataType[mergedIndex] = 2;// RESULT
						else if(interpretationSelection[0][i].isSelected() && interpretationSelection[1][i].isSelected())
							dataType[mergedIndex] = 3;// EXPLICIT

                        importance[mergedIndex] = maxImportance;
                        smallImage[mergedIndex] = null;

                        for(int j=0;j<totalDataNumber;j++)
                            combinedOriginalNumber[mergedIndex][j] = mergedOriginalNumber[j];
                        
                        checkCount++;
                        mergedIndex++;
                    }
                }
            }
		
			
            for(int i=0;i<createNodeNumber;i++)
            {
                logData += "CREATED NODE "+(count+i)+" : (imp= "+importance[count+i]+",type= "+dataType[count+i]+") "+dataName[count+i]+System.getProperty("line.separator");
            }
            
			logData += "COMMON POINT : "+resultText.getText()+System.getProperty("line.separator");	
			for(int i=0;i<maxInterpretation;i++)
				logData += "INTERPRETATION "+(i+1)+" : "+mergeText[i].getText()+System.getProperty("line.separator");			
			
            for(int i=0;i<maxInterpretation;i++)
			{
                interpretationSelection[0][i].setSelected(false);
                interpretationSelection[1][i].setSelected(false);				
			}
			

			
			
            if(currentSceneNumber == maxTotalSceneNumber)/////////MAX SCENE NUMBER
                return;
            
			scene = knowledgeCreationScene[currentSceneNumber] = new KnowledgeCreationScene(newDataNumber, dataType, dataName, importance, smallImage, combinedOriginalNumber, totalDataNumber);
			currentSceneNumber++;
			
			checkEnd = checkCreationEnd();
			touchNumber = oldTouchNumber = -1;			
			System.out.println("CheckEnd = "+checkEnd);			
			if(checkEnd > 0)
			{
				//EXP///**************************
				if(totalDataNumber >= 5)
					control.ex1.addExpByknowledge(totalDataNumber*10);

                ACTIONLOG.writeActionLog("KNOWLEDGE*KNOWLEDGE*CREATED*"+totalDataNumber);////////////////////////
				
				if(control.expPanel != null)
					control.expPanel.repaint();
                
                control.navigationControl.setSoundNumber(1021);
			}
            else
                control.navigationControl.setSoundNumber(1020);
			
			if(currentSceneNumber > maxSceneNumber)
				maxSceneNumber = currentSceneNumber;
			
			checkGoBackButton();
			

			repaint();
			
			writeMergeLog(logData);
			
			mergeTimes++;
		}
        
        int countMergedNumber(int index)
        {
            int count=0;
            for(int i=0;i<totalDataNumber;i++)
                if(scene.combinedOriginalNumber[index][i])
                    count++;
            return count;
        }
        
        /*
		void mergeDataOld()
		{
			String mergedWord = "";
			int mergedNumber = 0;
			int mergedIndex = -1;
			int maxImportance = 0;
			String logData = "";
			
			for(int i=0;i<scene.dataNumber;i++)
				if(scene.selected[i])
					mergedNumber++;
			
			if(mergedNumber <= 1)
				return;
			
			int newDataNumber = scene.dataNumber-(mergedNumber-1);
			String dataName[] = new String[newDataNumber];
			int importance[] = new int[newDataNumber];
			Image smallImage[] = new Image[newDataNumber];			

			int count = 0;
			for(int i=0;i<scene.dataNumber;i++)
			{

				if(scene.selected[i])
				{
					mergedWord += scene.network.object[i].word;
					logData += "MERGED NODE "+i+" : ("+scene.importance[i]+") "+scene.network.object[i].word+System.getProperty("line.separator");
				
					if(mergedIndex == -1)
					{
						mergedIndex = i;
						maxImportance = scene.importance[i];
						count++;
					}
					else
					{
						if(scene.importance[i] > maxImportance)
							maxImportance = scene.importance[i];
					}
					scene.selected[i] = false;					
				}
				else
				{
					dataName[count] = scene.dataName[i];
					importance[count] = scene.importance[i];
					smallImage[count] = scene.smallImage[i];
					count++;
				}
			}


			String inputText="";
            
            for(int i=maxInterpretation-1;i>=0;i--)
            {
                inputText = mergeText[i].getText();
                if(!inputText.equals(""))
                    break;
            }

			if(!inputText.equals(""))
			{
                for(int i=0;i<maxInterpretation;i++)
                    mergeText[i].setText("");
				dataName[mergedIndex] = inputText;
			}
			else
				dataName[mergedIndex] = mergedWord;

			importance[mergedIndex] = maxImportance;
			smallImage[mergedIndex] = null;
			
			logData += "CREATED NODE "+mergedIndex+" : ("+importance[mergedIndex]+") "+dataName[mergedIndex]+System.getProperty("line.separator");			
			
			scene = knowledgeCreationScene[currentSceneNumber] = new KnowledgeCreationScene(newDataNumber, dataName, importance, smallImage);			
			currentSceneNumber++;
			
			if(currentSceneNumber > maxSceneNumber)
				maxSceneNumber = currentSceneNumber;
			
			checkGoBackButton();
			
			scene.mergedNodeNumber[mergedIndex] += (mergedNumber-1);
			repaint();
			
			writeMergeLog(logData);
			
			mergeTimes++;
		}
		*/
		
		String mergeLogFilename;    
		public void writeMergeLog(String data)		//notFirstTime: true -> create new file, false -> add data
		{
			mergeLogFilename = control.absolutePath+"interpretation"+File.separator+"MERGELOG";
			try
			{
				BufferedWriter bw1 = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(mergeLogFilename, mergeTimes!=0), "Shift_JIS"));
				
				bw1.write(String.format(data+System.getProperty("line.separator")));
				bw1.close();
			}
			catch(Exception e){
				System.out.println("File Writing ERROR MERGELOG in Pop up for knowledge creation");
			}		
		}		
		
			
		public void drawTouchedData(Graphics2D g2)
		{			

			g2.setColor(Color.red);
			scene.network.fillOval(g2, touchNumber);
		
			g2.setColor(Color.black);
			scene.network.drawOval(g2, touchNumber);
			
//			g2.setFont(new Font(control.sp1.fontName, Font.BOLD, scene.network.object[touchNumber].fontSize));
//			scene.network.drawWord(g2, touchNumber, Color.red);
            
            g2.setColor(new Color(0xff, 0xf8, 0xdc));
            g2.fillRect(historyX,historyY,historyWidth,historyHeight);
            
            g2.setColor(Color.black);
            g2.setFont(new Font(control.sp1.fontName, Font.BOLD, control.sp1.fontSize));
            for(int i=0;i<message.length;i++)
                g2.drawString(message[i], historyX+2, historyY+control.sp1.fontSize*(i+1)+2);
            
            
//            for(int i=0;i<totalDataNumber;i++)
  //              if(scene.combinedOriginalNumber[touchNumber][i])
    //                System.out.println(""+i);
		}

		
		public void drawClickedData(Graphics2D g2)
		{			
			for(int i=0;i<scene.dataNumber;i++)
			{
				if(scene.selected[i])
				{			

					g2.setColor(Color.white);
					scene.network.fillOval(g2, i);
			
					g2.setColor(Color.blue);
					scene.network.drawOval(g2, i);
				}
			}
		}
		

		public boolean checkMultipleSelected()
		{			
			int count = 0;
			for(int i=0;i<scene.dataNumber;i++)
			{
				if(scene.selected[i])
				{
					count++;
					if(count == 2)
						return true;
				}
			}
			return false;
		}

/*
		public boolean checkMultipleSelected2()
		{			
			int count = 0;
			for(int i=0;i<scene.dataNumber;i++)
			{
				if(scene.selected[i])
				{
					count++;
				}
			}
			if(count == 1)
				return true;
			else
				return false;
		}
*/

        public int paintColorString(Graphics2D g2, String words[], Color wordColors[], int wordNum, int x, int y, String fontName, int fontSize, int maxLength, int option)
        {
            int drawX, drawY;
            int length;
            
            posX = getX();
//            posY = getY();
            sizeX = getWidth();
//            sizeY = getHeight();
            
            drawX = x;
            drawY = y;
            
            g2.setFont(new Font(fontName, Font.BOLD, fontSize));
            
            if(x+maxLength > posX+sizeX)
                maxLength = posX+sizeX-x;
            
            for(int i=0;i<wordNum;i++)
            {
                length = fontSize*words[i].length();
                
                if(drawX + length > x + maxLength)
                {
                    drawX = x;
                    drawY += fontSize;
                }
                
//                System.out.println("x,y,word,fontSize,x = "+drawX+","+drawY+","+words[i]+","+fontSize+"("+x);
                
                if(option == 0)
                {
                    g2.setColor(wordColors[i]);
                    g2.drawString(words[i],drawX,drawY+fontSize);
                }
                else
                {
                    g2.setColor(wordColors[i]);
                    g2.fillRect(drawX, drawY, length, fontSize);
                    g2.setColor(Color.white);
                    g2.drawString(words[i],drawX,drawY+fontSize);
                }
                
                drawX += fontSize*words[i].length();
            }
            
            return (drawY - y + fontSize);
        }
		
        public int paintColorString(Graphics2D g2, String words[], Color wordColor, int wordNum, int x, int y, String fontName, int fontSize, int maxLength, int option)
        {
            int drawX, drawY;
            int length;
            
            posX = getX();
			//            posY = getY();
            sizeX = getWidth();
			//            sizeY = getHeight();
            
            drawX = x;
            drawY = y;
            
            g2.setFont(new Font(fontName, Font.BOLD, fontSize));
            
            if(x+maxLength > posX+sizeX)
                maxLength = posX+sizeX-x;
            
            for(int i=0;i<wordNum;i++)
            {
                length = fontSize*words[i].length();
                
                if(drawX + length > x + maxLength)
                {
                    drawX = x;
                    drawY += fontSize;
                }
                
				//                System.out.println("x,y,word,fontSize,x = "+drawX+","+drawY+","+words[i]+","+fontSize+"("+x);
                
                if(option == 0)
                {
                    g2.setColor(wordColor);
                    g2.drawString(words[i],drawX,drawY+fontSize);
                }
                else
                {
                    g2.setColor(wordColor);
                    g2.fillRect(drawX, drawY, length, fontSize);
                    g2.setColor(Color.white);
                    g2.drawString(words[i],drawX,drawY+fontSize);
                }
                
                drawX += fontSize*words[i].length();
            }
            
            return (drawY - y + fontSize);
        }		

	
		public void paintComponent(Graphics g)
		{        
			Graphics2D g2 = (Graphics2D)g;
			
			g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);// Anti aliasing
			g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);			

			drawBackground(g2);	//Set background
			drawData(g2);
		}
		
		int checkCreationEnd() // 0: not finish, 1: only cause end, 2: only result end, 3: cause and result end
		{
			if(scene.dataNumber == 1)
			{
				if(scene.dataType[0] == 0 || scene.dataType[0] == 3)
					return 3;
				else if(scene.dataType[0] == 1)
					return 1;
				else if(scene.dataType[0] == 2)
					return 2;
			}
			
			if(scene.dataNumber == 2)
			{
				if(scene.dataType[0] == 1 && scene.dataType[1] == 2)
					return 3;
				if(scene.dataType[0] == 2 && scene.dataType[1] == 1)
					return 3;
			}
			
			return 0;
		}
		
		void drawBackground(Graphics2D g2)
		{
			sizeX = getWidth();
			sizeY = getHeight();

			g2.setColor(new Color(0xE0,0xFF,0xFF));	
			g2.fillRect(0,0, sizeX, sizeY);
			
			g2.setFont(new Font(control.sp1.fontName, Font.BOLD, scene.fontSize));			
			g2.setColor(Color.blue);
            
//            g2.drawString(inJapanese[27], (sizeX-inJapanese[27].length() * scene.fontSize)/2,scene.fontSize+2);
            g2.drawString(creationTitle, (sizeX-creationTitle.length() * scene.fontSize)/2,scene.fontSize+2);			
            
            if(control.sp1.inJapanese)
            {
                g2.drawString(inJapanese[19]+currentSceneNumber+"/"+maxTotalSceneNumber, 5,sizeY-5);
                g2.drawString(inJapanese[20]+scene.dataNumber+"/"+totalDataNumber, 5,sizeY-25);
            }
            else
            {
                g2.drawString("REST:"+scene.dataNumber+"/"+totalDataNumber, 5,sizeY-25);
                g2.drawString("TURN:"+currentSceneNumber+"/"+maxTotalSceneNumber, 5,sizeY-5);
            }
            

//            if(scene.dataNumber > 0)
  //              g2.drawString("value = "+(int)(totalDataNumber/scene.dataNumber), 5,sizeY-5);
			
			if(control.sp1.inJapanese)
			{
				g2.setColor(Color.red);
				g2.drawString(inJapanese[8], 100, sizeY-15);
				
				g2.setColor(Color.black);


//				System.out.println("CheckEnd = "+checkEnd);
				if(checkEnd > 0)
				{
					g2.drawString(inJapanese[20 + checkEnd], 500, sizeY-15);
				}
				else
				{
					if(multiSelected)
					{
						g2.setColor(new Color(0xB2,0x22,0x22));
						g2.drawString(inJapanese[10], 500, sizeY-15);
					}
					else
					{
                        g2.setColor(new Color(0xB2,0x22,0x22));
						g2.drawString(inJapanese[9], 500, sizeY-15);
					}
				}
                
//                System.out.println("Touch Number = "+touchNumber);
			}		
			
		}		

		void drawImage(Graphics2D g2)
		{
			for(int i=0;i<scene.dataNumber;i++)
				if(scene.mergedNodeNumber[i] == 1 && scene.network.object[i].active)
					g2.drawImage(scene.smallImage[i],(int)scene.network.object[i].x - scene.imageSize - scene.network.object[i].fontSize/2,
								 (int)scene.network.object[i].y - scene.imageSize + scene.network.object[i].fontSize/2,scene.imageSize,scene.imageSize,this);			
		}
	
		void drawData(Graphics2D g2)
		{

			if(linkDisplay)
			{
				g2.setColor(Color.gray);
				g2.setStroke(new BasicStroke(0.1f));			
				scene.network.drawLink(g2);////			
			}
			
			drawImage(g2);
			
			//NODE
			g2.setColor(Color.green);
			g2.setStroke(new BasicStroke(1.0f));			
			scene.network.fillOval(g2);

			g2.setColor(Color.black);
			scene.network.drawOval(g2);//
			

			
			
			//draw OVAL
			
//			g2.setStroke(new BasicStroke(4.0f));
			for(int i=0;i<scene.dataNumber;i++)
			{
				if(scene.network.object[i].active == false)
					continue;
				/*
                //CAUSE AND RESULT OVAL
				if(scene.dataType[i] == 0)
					g2.setColor(Color.blue);
				else if(scene.dataType[i] == 1)
					g2.setColor(new Color(0xff,0x00,0x99));
				else
					g2.setColor(Color.green);
                
				g2.drawOval((int)(scene.network.object[i].x-scene.network.object[i].fontSize),(int)scene.network.object[i].y,scene.network.object[i].fontSize,scene.network.object[i].fontSize);
                */
                
                
                int causeWidth=0, causeHeight=0;
                int resultWidth, resultHeight;
                //CAUSE STRING
                if(scene.dataType[i] == 3 || scene.dataType[i] == 1)
                {
                    causeWidth = inJapanese[24].length()*scene.network.object[i].fontSize+4;
                    causeHeight = scene.network.object[i].fontSize+4;
                    g2.setColor(new Color(0xff,0x00,0x99));
                    g2.fillRect((int)scene.network.object[i].x-4, (int)scene.network.object[i].y-scene.network.object[i].fontSize-4,
                                causeWidth, causeHeight);

                    g2.setColor(Color.white);
                    g2.setFont(new Font(scene.network.object[i].fontName, Font.BOLD, scene.network.object[i].fontSize));
                    g2.drawString(inJapanese[24], (int)scene.network.object[i].x-2, (int)scene.network.object[i].y-4);
                }
                
                //RESULT STRING
                if(scene.dataType[i] == 3 || scene.dataType[i] == 2)
                {
                    resultWidth = inJapanese[25].length()*scene.network.object[i].fontSize+4;
                    resultHeight = scene.network.object[i].fontSize+4;
                    
                    g2.setColor(Color.green);
                    g2.fillRect(causeWidth + (int)scene.network.object[i].x-4, (int)scene.network.object[i].y-scene.network.object[i].fontSize-4,
                                resultWidth, resultHeight);
                    g2.setColor(Color.black);
                    g2.setFont(new Font(scene.network.object[i].fontName, Font.BOLD, scene.network.object[i].fontSize));
                    g2.drawString(inJapanese[25], causeWidth + (int)scene.network.object[i].x-2, (int)scene.network.object[i].y-4);
                }
				            
			}
            
			//WORD
			g2.setStroke(new BasicStroke(1.0f));
            //			scene.network.drawWord(g2);
            for(int i=0;i<scene.dataNumber;i++)
            {
				if(scene.network.object[i].active == false)
					continue;
                
				if(i != touchNumber)
					paintColorString(g2,scene.wordList[i],scene.colorList[i],scene.wordNumber[i],
									 (int)scene.network.object[i].x,(int)scene.network.object[i].y,
									 control.sp1.fontName,scene.network.object[i].fontSize,1000,0);
            }

			//TOUCH
			if(touchNumber >= 0)
			{
				paintColorString(g2,scene.wordList[touchNumber],Color.red,scene.wordNumber[touchNumber],
								 (int)scene.network.object[touchNumber].x,(int)scene.network.object[touchNumber].y,
								 control.sp1.fontName,scene.network.object[touchNumber].fontSize,1000,0);				
				drawTouchedData(g2);				
			}
			
			//CLICK
			drawClickedData(g2);
			
		}			
		
		public void update(Graphics g)		//Avoid from blinking
		{
			paintComponent(g);
		}
	
		//MouseListener
		public void mousePressed(MouseEvent me)	//Press
		{
			mouseX = me.getX();
			mouseY = me.getY();
			
			if(touchNumber < 0)
			{
				oldMouseX = mouseX;
				oldMouseY = mouseY;
				fieldMove = true;
				return;
			}
		}
		
		public void mouseReleased(MouseEvent me)	//Release
		{
			fieldMove = false;
		}
	
		public void mouseEntered(MouseEvent me){}	//Enter an area
		public void mouseExited(MouseEvent me){}	//Exit an area
		
		public void mouseClicked(MouseEvent me)	//Click
		{
			int clickNumber;
			
			mouseX = me.getX();
			mouseY = me.getY();
			clickNumber = scene.network.getOnMouseObjectAddLeft(mouseX, mouseY);
			
			if(clickNumber >= 0)
			{
				if(scene.network.object[clickNumber].active == false)
					clickNumber = -1;
				else
				{
					scene.selected[clickNumber] = !scene.selected[clickNumber];
					
					multiSelected = checkMultipleSelected();
					
					if(multiSelected)
					{
						resultText.setText("");
						
                        for(int i=0;i<maxInterpretation;i++)
                            mergeText[i].setText("");
					}
					else
					{
						resultText.setText(inJapanese[14]);
						
                        mergeText[0].setText(inJapanese[15]);
                        for(int i=1;i<maxInterpretation;i++)
                            mergeText[i].setText(inJapanese[18]);
					}
					
					repaint();
				}
			}
		}	
		
		//MouseMotionListener
		public void mouseDragged(MouseEvent me)	//fieldMove
		{
			mouseX = me.getX();
			mouseY = me.getY();
			
			if(touchNumber >= 0)
			{
				if(scene.network.object[touchNumber].active)
				{
					scene.network.moveObjectByMouse(mouseX, mouseY, touchNumber);
					repaint();
				}
			}
			
			if(fieldMove == true)
			{
				scene.network.moveObjects(mouseX - oldMouseX, mouseY - oldMouseY);
				oldMouseX = mouseX;
				oldMouseY = mouseY;
				repaint();
			}
		}
		
		public void mouseMoved(MouseEvent me)
		{
			mouseX = me.getX();
			mouseY = me.getY();
			
			touchNumber = scene.network.getOnMouseObjectAddLeft(mouseX, mouseY);
            
			if(touchNumber >= 0)
			{
				if(scene.network.object[touchNumber].active == false)
					touchNumber = -1;
			}
//            else
  //              closeHistoryWindow();
			
			if(touchNumber != oldTouchNumber)
			{
				if(touchNumber >= 0)
				{
//                    closeHistoryWindow();
                    createHistoryWindow();
				}
				
				repaint();
				oldTouchNumber = touchNumber;
//                System.out.println("OLD="+oldTouchNumber+" NEW="+touchNumber);
			}
		}
        /*
        public void closeHistoryWindow()
        {
            if(historyWindow != null)
            {
                historyWindow.dispose();
                historyWindow = null;
            }
        }
		*/
        public void createHistoryWindow()
        {
            posX = getX();
            posY = getY();
            sizeX = getWidth();
            sizeY = getHeight();
            
            int count=0,maxLength=0;

            message = new String[scene.mergedNodeNumber[touchNumber]];
            
            count=0;
            for(int i=0;i<totalDataNumber;i++)
                if(scene.combinedOriginalNumber[touchNumber][i])
                {
                    if(scene.mergedNodeNumber[touchNumber] == 1)
                    {
                        if(control.sp1.inJapanese)
                            message[count] = inJapanese[26]+resultTexts[i];
                        else
                            message[count] = "[Output]"+resultTexts[i];
                    }
                    else
                        message[count] = knowledgeCreationScene[0].dataName[i];
                    if(message[count].length() > maxLength)
                        maxLength = message[count].length();
                    count++;
                }
            
            historyWidth = maxLength * control.sp1.fontSize +4;
            historyHeight = count * control.sp1.fontSize +4;
            
            if(scene.network.object[touchNumber].x < sizeX/2)
                historyX = posX+sizeX - historyWidth;
            else
                historyX = posX;
            
            historyY = posY+(int)scene.network.object[touchNumber].y;
            
            if(historyY < posY)
                historyY = posY;
            
            if(historyY+historyHeight > posY+sizeY)
                historyY = posY+sizeY - historyHeight;
            
 //           System.out.println("Node, x, y = "+scene.network.object[touchNumber].x +","+ scene.network.object[touchNumber].y);
 //           System.out.println("posX,posY,sizeX,sizeY = "+posX+","+posY+","+sizeX+","+sizeY);
   //         System.out.println("X,Y,Width,Height = "+historyX+","+historyY+","+historyWidth+","+historyHeight);
            
            
        //    historyWindow = new HistoryWindow(historyX,historyY,historyWidth,historyHeight,
             //                                 message,control.sp1.fontSize, control.sp1.fontName);
//            requestFocusInWindow();
        }
		
	}		
}
/*
class HistoryPanel extends JPanel
{
	JTextPane text1;
    
	HistoryPanel(String displayText, int fontSize, String fontName)
	{
		setBackground(new Color(0xff, 0xf8, 0xdc));
		text1 = new JTextPane();
		text1.setContentType("text/plain");
		text1.setFont(new Font(fontName, Font.BOLD, fontSize));//control.sp1.fontSize, control.sp1.fontName);
		text1.setForeground(Color.black);
		text1.setBackground(new Color(0xff, 0xf8, 0xdc));
        text1.setText(displayText);
        text1.setEditable(false);
		text1.setCaretPosition(0);
        add(text1);
	}
}

class HistoryWindow extends JFrame
{
	HistoryPanel historyPanel;
	Container pane = getContentPane();
	
	HistoryWindow(int X, int Y, int width, int height, String message, int fontSize, String fontName)
	{
		super("Information");
		pane.setLayout(new BorderLayout());
		
		setBounds(X, Y, width, height);
		setBackground(new Color(0xff, 0xf8, 0xdc));
		setUndecorated(true);
        
		historyPanel = new HistoryPanel(message, fontSize, fontName);
		pane.add(historyPanel);
		setVisible(true);
	}
}
  */

