package lt.ktu.mockus.srgm;

import com.jrefinery.chart.ChartFactory;
import com.jrefinery.chart.ChartPanel;
import com.jrefinery.chart.JFreeChart;
import com.jrefinery.data.BasicTimeSeries;
import com.jrefinery.data.Day;
import com.jrefinery.data.TimeSeriesCollection;
import java.awt.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class StartupApplet extends JApplet {
	//---------------stock preferences tab----------------
        private static final double STOCK_STARTUP_PRICE[] = { 10.0d, 5.0d, 15.0d, 11.0d, 7.0d, 17.0d, 12.0d, 2.0d, 14.0d };
	private static final int DEFAULT_STOCK_HISTORY_STORAGE = 2000;
        //-----------------customer preferences tab----------------
	public static final int STOCKCOUNT = 8;
        public static final int MAX_FIRM_COUNT = 9;
        
	private static final boolean DEFAULT_MARKET_PRICE_VISIBILITY = true;
        //private static final double  DEFAULT_CREDIT = 500d;
        public static final double   SMALL_DOUBLE = 0.01d;
        private static final String  DEFAULT_STOCK_NAME[] = { "MSFT", "AAPL", "GOOG", "NOK", "TM", "BAC", "BA", "ORCL" };//, "GOOG", "GOOG" };
        private static final double  DEFAULT_DIVIDEND[] = { 0.23d, 3.05d, 0.0d, 0.263d, 0.005d, 0.01d, 0.485d, 0.12d }; //0.2d;
        private static final double  DEFAULT_VOLATILITY = 0.9d;
        private static final double  DEFAULT_INERTIA = 0.5d;
        private static final boolean DEFAULT_REAL = false;
        private static final double  DEFAULT_BANKRUPT_PROBABILITY = 0.5d;
	
        public int MAX_STOCK_COUNT = 8;
        public String realDataPeriod = "day";
        public double volatility[] = null;
        public double bankruptProbability[] = null;//{ 0.9d, 0.9d, 0.9d };
        public double dividend[] = null;//{ 0.2d,0.2d,0.2d};
        public double inertia[] = null;//{0.5d,0.5d,0.9d};
	public double yieldOfCd = 0.02d;
        public double bankInterest = 0.1d;
        public double transactionCostValue = 0.5;
        public double interestRate = 0.01;
        public boolean realData[] = null;//{ false, false, false };
        public int realDataCounter = 0;
        public double limitCoff = 1000;
        public int startFromDay = 1;
        public int termin = 365;
        
        public final int ConstRandTime = 1343304948;
        
        public boolean realDataLoaded = false;

	private JPanel stocksPreferencesTabPanel = new JPanel();
        private JTextField[] volatilityField = null;
        private JTextField[] stockBankrotProbabilityField = null;
	private JTextField[] dividendField = null;
        private JTextField[] inertiaField = null;
        private JTextField limitCoffField = null;
        public JComboBox[] dataSelector = null;
        public JComboBox stockSelector = null;
        public JComboBox realDataPeriodSelector = null;
        private JTextField[] realStockName = null;
        private JTextField startFromDayField = null;
        private JTextField terminField = null;
        private JTextField RandomTypeField = null;
	private JTextField yieldOfCdField = null;
        private JTextField bankInterestField = null;
        private JTextField transactionCostField = null;
        
	
	//-----------stock market prices tab--------------							
	public ArrayList stocksVisibility = null;
	public ArrayList profitVisibility = null;
        StockContainer stocksPrices[] = null;
        StockContainer stockPricesDividendRatio[] = null;
        
        StockContainer stockEps[] = null;
	public int stockHistory = DEFAULT_STOCK_HISTORY_STORAGE;
	private int lastRemovedFromHistory = 1;
	
	private JTabbedPane stocksMarketTabPanel = new JTabbedPane();
	private JCheckBox[] customerStockVisibilityCheckBoxes = null;
	private JCheckBox[] customerProfitVisibilityCheckBoxes = null;
	
        private BasicTimeSeries stocksSeries[] = null;//new BasicTimeSeries[MAX_STOCK_COUNT];
        private BasicTimeSeries[] customerProfitSeries = null;
        private BasicTimeSeries[][] customerPredictSeries = null;
        public BasicTimeSeries bankSeries = null;
	
        private TimeSeriesCollection[] stockMarketGraphic = null;
        private JPanel stockMarketOneStockPanel[] = null;
	
	private JPanel stockMarketCustomerProfitPanel = null;
	private TimeSeriesCollection stockMarketCustomerProfitGraphic = null;
	
        //--------------------novaja panelka-------------------------------//
        private JPanel[] stockMarketCustomerPredictPanel = new JPanel[MAX_STOCK_COUNT];
	private TimeSeriesCollection[] stockMarketCustomerPredictGraphic = null;//new TimeSeriesCollection[MAX_STOCK_COUNT];
	
        //-------------------eshio odna panelka ( bank ) -----------------//
        private JPanel stockMarketBankPanel = null;
	private TimeSeriesCollection stockMarketBankGraphic = null;
        
	public int firmCount = 1;
        public int [] metodset = { 18, 15, 12, 10, 9, 6, 3 , 1 };//{0, 1, 6, 9, 10, 15, 18 , 0};//{ 18, 15, 12, 10, 9, 6, 3 , 1 };
        public int defaultRiskStrategy = 10;
        
        //public int bandymas = 1;
        public final int bandymaiDienos = 365;//182;//365;//730;
        public final int bandymai = 100;
	private final static String[] STRATEGY_METHODS = {"WIENER", "AR1", "AR2", "AR3", "AR4", "AR5", "AR6", "AR7", "AR8", "AR9", "AR-ABS1", "AR-ABS2", "AR-ABS3", "AR-ABS4", "AR-ABS5", "AR-ABS6", "AR-ABS7", "AR-ABS8", "AR-ABS9" };//,"SOROS"};
        private final static String[] RISK_STRATEGY_METHODS = { "B_BS_S_A_LS_BY_P", "B_BS_S_A_L", "B_BS_S_A" , "B_S_BY_PRFT_LVL",  "LONG_TERM_SHARP", "LONG_TERM_PORTF" , "LONG_B_BS_S_A_LS_BY_P", "LONG_B_BS_S_A_L", "LONG_B_BS_S_A", "LONG_B_S_BY_PRFT_LVL","LONG_TERM_SHARP_SH", "LONG_TERM_PORTF_SH" };
        
        public final static String[] INVESTMENT_TYPES = { "Realus", "Atsargus", "Rizikingas", "Turtingas" };
        public final static String[] LONG_INVEST_FOR_SHORT = { "OFF", "ON" };
        public final static String[] INVESTMENT_INTERVALS = { "3", "6", "12" };
        public final static int[] INVESTMENT_INTERVALSINT = { 3, 6, 12 };
        public final static String[] INVESTMENT_METODS = { "Mig1", "Bayes" };
        public final static int INVESTMENT_ITERATIONS = 1000;
        
        protected double [][] stockRealData;
        boolean Grafik = true;
        String RandomType = "seed";
        
        int ribojimas = 0;
        public JTextField ribojimasField = null;
        
        int dayinmonth = 30;
        public JTextField dayInMonthField = null;
        
        public ArrayList customers = null;
	
	private JPanel customerTabPanel = new JPanel();
	private JComboBox firmCountComboBox = null;
	private JComboBox[] customerStrategyComboBox = null;
        private JComboBox[] customerRiskStragegyComboBox = null;
        private JComboBox[] customerInvestmentForShortStrategies = null;
        //ilgalaikiai
        private JComboBox[] customerInvestmentType = null;
        private JComboBox[] customerInvestmentLaikas = null;
        private JComboBox[] customerInvestmentMetod = null;
        
        private JTextField[] customerInvestmentIterations = null;
        
        public JTextField[] operationLastSell = null;
        public JTextField[] operationLastBuy = null;
        
        
                
	private JTextField[] customerProfitField = null;
        private JTextField[][] customerHasStockField = null;
        private JTextField[] maxCreditField = null;
        private JTextField[] borowedSumField = null;
        public JTextField[] insovlementField = null;
        public JTextField[] forcebuyField = null;
        public JTextField[] forcesellField = null;
        
		
	//-------------------about tab-------------------
	private JPanel aboutPanel = new JPanel();

	///----------------main--------------
	private JTabbedPane mainPanel = new JTabbedPane();
	
	private static final String CONTROL_BUTTON_TRACE = "Trace";
	private JButton traceButton = new JButton( CONTROL_BUTTON_TRACE );
	
	private static final String CONTROL_BUTTON_RUN_WITH_DELAY = "Run with delay";
	private JButton runWithDelayButton = new JButton( CONTROL_BUTTON_RUN_WITH_DELAY );
	
	private static final String CONTROL_BUTTON_RUN = "Run";
	private JButton runWithoutDelayButton = new JButton( CONTROL_BUTTON_RUN );
	
	private static final String CONTROL_BUTTON_STOP = "Stop";
	private JButton stopButton = new JButton( CONTROL_BUTTON_STOP );

        private static final String CONTROL_BUTTON_XML = "save XML";
        private JButton xmlWrite = new JButton("save XML");
        
        private static final String CONTROL_BUTTON_YEAR = "Start Experiment";
        private JButton buttonYear = new JButton( CONTROL_BUTTON_YEAR );
		
	//----------------------------------------------------------------
	public boolean readingData = false;
	public static final int CALCULATION_THREAD_DELAY = 500;
	public static final int CALCULATION_THREAD_WITHOUT_DELAY = 10;	//time needed to repaint GUI
	
	//calculation thread
	StockTradeThread calculationThread = null;
	
	public Calendar startupTime = null;
	
	YieldFocusListener yieldFocusListener = null;
        TransactionFocusListner transactionFocusListner = null;
        BankInterestFocusListner bankInterestFocusListner = null;

	StockPreferencesFocusListener stockPreferencesFocusListener = null;
	FirmCountChangeListener firmCountChangeListener = null;
        StockCountChangeListener stockCountChangeListener = null;
        RealDataPeriodChangeListner realDataPeriodChangeListner = null;
	CustomerStrategyChangeListener customerStrategyChangeListener = null;
        CustomerRiskStrategyChangeListner customerRiskStrategyListner = null;
        CustomerInvestForShortStrategiesChangeListner customerInvestForShortStrategiesChangeListner = null;
	CustomerPreferencesFocusListener customerPreferencesFocusListener = null;
	CustomerPricesVisibilityChangeListener customerPricesVisibilityChangeListener = null;
	CustomerProfitVisibilityChangeListener customerProfitVisibilityChangeListener = null;//ed
	ControlButtonsListener controlButtonsListener = null;
        dataSelectorListner RealDataSelectorFocusLisntner = null;
        
        CustomerInvestmentTypeChangeListner customerInvestmentTypeListner = null;
        CustomerInvestmentMethodChangeListner customerInvestmentMetodListner = null;
        CustomerInvestmentIntervalChangeListner customerInvestmentIntervalListner = null;
        CustomerInvestmentIterationsChangeListner customerInvestmentInterationListner = null;
        

        Bank bank1 = null;
        
        FileHandler logfile = null;
        Logger log = null;
        boolean writeLog = true;

	private JPanel getControlButtonsPanel() {
		JPanel panel3 = new JPanel();
		panel3.setLayout( new FlowLayout() );
                panel3.add( traceButton );
		traceButton.addActionListener( controlButtonsListener );
		
                panel3.add( runWithDelayButton );
		runWithDelayButton.addActionListener( controlButtonsListener );
		
                panel3.add( runWithoutDelayButton );
		runWithoutDelayButton.addActionListener( controlButtonsListener );
		
                panel3.add( stopButton );
		stopButton.addActionListener( controlButtonsListener );
		stopButton.setEnabled( false );
                
                panel3.add( xmlWrite );
                xmlWrite.addActionListener( controlButtonsListener );
		xmlWrite.setEnabled( true );
                
                panel3.add( buttonYear );
                buttonYear.addActionListener( controlButtonsListener );
		buttonYear.setEnabled( true );

		return panel3;
	}
	
	public void reinitStockPreferencesTabPanel() {
                realData = new boolean[MAX_STOCK_COUNT];
                volatility = new double[MAX_STOCK_COUNT];
                bankruptProbability = new double[MAX_STOCK_COUNT];
                dividend = new double[MAX_STOCK_COUNT];
                inertia = new double[MAX_STOCK_COUNT];
                for( int i = 0; i < MAX_STOCK_COUNT; i++ ) {
                    realData[i] = DEFAULT_REAL;
                    volatility[i] = DEFAULT_VOLATILITY;
                    bankruptProbability[i] = DEFAULT_BANKRUPT_PROBABILITY;
                    dividend[i] = DEFAULT_DIVIDEND[i];
                    inertia[i] = DEFAULT_INERTIA;
                }
                
		stocksPreferencesTabPanel.removeAll();
		stocksPreferencesTabPanel.setLayout( new BorderLayout() );
                //setLayout( new GridLayout( 2 , 1 ));
		
                JPanel panel1 = new JPanel();
                //panel1.setSize(800, 50);
		//panel1.setLayout( new FlowLayout() );
                
                panel1.setBorder(new EmptyBorder(new Insets(20, 20, 20, 20)));
                panel1.setBorder(new TitledBorder( " Setting for all stocks ") );
                panel1.setLayout( new GridLayout( 7, 2 ) );
                //setSize(450, 100);
		
                panel1.add( new JLabel("   Yield of CD:") );
		yieldOfCdField = new JTextField( "" + yieldOfCd, 5 );
		yieldOfCdField.addFocusListener( yieldFocusListener );
		panel1.add( yieldOfCdField );
		//panel1.setBorder( BorderFactory.createEtchedBorder() );
                
                panel1.add( new JLabel("   Transaction cost:") );
		transactionCostField = new JTextField( "" + transactionCostValue, 5 );
		transactionCostField.addFocusListener( transactionFocusListner );
		panel1.add( transactionCostField );
		//panel1.setBorder( BorderFactory.createEtchedBorder() );
                
                panel1.add( new JLabel("   Bank interest:") );
		bankInterestField = new JTextField( "" + bankInterest, 5 );
		bankInterestField.addFocusListener( bankInterestFocusListner );
		panel1.add( bankInterestField );
		//panel1.setBorder( BorderFactory.createEtchedBorder() );
                
                panel1.add( new JLabel("   Limit X:") );
                limitCoffField = new JTextField( "" + new Double( limitCoff ).toString() );
                limitCoffField.addFocusListener( stockPreferencesFocusListener );
                panel1.add( limitCoffField );
                //panel1.setBorder( BorderFactory.createEtchedBorder() );
                
                panel1.add( new JLabel("   Start from day:"));
                startFromDayField = new JTextField( "" + new Integer( startFromDay ).toString() );
                startFromDayField.addFocusListener( stockPreferencesFocusListener );
                panel1.add( startFromDayField );
                
                panel1.add( new JLabel("   Termin:"));
                terminField = new JTextField( "" + new Integer( termin ).toString() );
                terminField.addFocusListener( stockPreferencesFocusListener );
                panel1.add( terminField );
                
                panel1.add( new JLabel("   Random type:"));
                RandomTypeField = new JTextField( RandomType );
                RandomTypeField.addFocusListener( stockPreferencesFocusListener );
                panel1.add( RandomTypeField );
                
                panel1.add( new JLabel( "   Choose stock count:" ) );
                String[] datastockcount = { "1","2","3","4","5","6","7","8" };
                stockSelector = new JComboBox( datastockcount );
                stockSelector.addItemListener( stockCountChangeListener );
                stockSelector.setSelectedItem(""+ MAX_STOCK_COUNT);
                panel1.add( stockSelector );
                
                panel1.add( new JLabel( "   Period of real data:" ) );
                String[] datarealDataPeriod = { "day","week","month" };
                realDataPeriodSelector = new JComboBox( datarealDataPeriod );
                realDataPeriodSelector.addItemListener( realDataPeriodChangeListner );
                realDataPeriodSelector.setSelectedItem( realDataPeriod );
                panel1.add( realDataPeriodSelector );
                
                panel1.add( new JLabel("   Predicion data length:"));
                ribojimasField = new JTextField( "" + new Integer( ribojimas ).toString() );
                ribojimasField.addFocusListener( stockPreferencesFocusListener );
                panel1.add( ribojimasField );
                
                
                panel1.add( new JLabel("    Day in month:"));
                dayInMonthField = new JTextField( "" + new Integer( dayinmonth ).toString() );
                dayInMonthField.addFocusListener( stockPreferencesFocusListener );
                panel1.add( dayInMonthField );
                
                
                //panel1.setBorder( BorderFactory. ) );
                //panel1.setBorder( BorderFactory.createEtchedBorder() );
                stocksPreferencesTabPanel.add(panel1, BorderLayout.NORTH );
		//stock preferences panels
		JPanel panel2[] = new JPanel[MAX_STOCK_COUNT];
                JPanel stockParamsPanel[] = new JPanel[MAX_STOCK_COUNT];
                volatilityField = new JTextField[MAX_STOCK_COUNT];
                stockBankrotProbabilityField = new JTextField[MAX_STOCK_COUNT];
                dividendField = new JTextField[MAX_STOCK_COUNT];
                inertiaField = new JTextField[MAX_STOCK_COUNT];
                dataSelector = new JComboBox[MAX_STOCK_COUNT];
                realStockName = new JTextField[MAX_STOCK_COUNT];
                JPanel tempstockPanel = new JPanel();
                tempstockPanel.setLayout( new GridLayout( 2, MAX_STOCK_COUNT ) );
                for( int i = 0; i < MAX_STOCK_COUNT; i++ ) {
                    panel2[i] = new JPanel();
                    panel2[i].setLayout( new FlowLayout() );
                    stockParamsPanel[i] = new JPanel(new GridLayout(0, 2, 6, 2));

                    stockParamsPanel[i].add(new JLabel("Volatility:"));
                    volatilityField[i] = new JTextField(  ( new Double(volatility[i]) ).toString() );
                    volatilityField[i].addFocusListener( stockPreferencesFocusListener );
                    stockParamsPanel[i].add( volatilityField[i] );

                    stockParamsPanel[i].add(new JLabel("Dividend:"));
                    dividendField[i] = new JTextField( new Double( dividend[i] ).toString() );
                    dividendField[i].addFocusListener( stockPreferencesFocusListener );
                    stockParamsPanel[i].add( dividendField[i] );

                    stockParamsPanel[i].add(new JLabel("Inertia:"));
                    inertiaField[i] = new JTextField( new Double( inertia[i] ).toString() );
                    inertiaField[i].addFocusListener( stockPreferencesFocusListener );
                    stockParamsPanel[i].add( inertiaField[i] );
                    
                    stockParamsPanel[i].add(new JLabel("Bankrupt prob:"));
                    stockBankrotProbabilityField[i] = new JTextField( new Double( bankruptProbability[i] ).toString() );
                    stockBankrotProbabilityField[i].addFocusListener( stockPreferencesFocusListener );
                    stockParamsPanel[i].add( stockBankrotProbabilityField[i] );

                    stockParamsPanel[i].add( new JLabel( "Choose data:" ) );
                    String[] datatypes = { "Generated data", "Real Data" };
                    dataSelector[i] = new JComboBox( datatypes );
                    dataSelector[i].addFocusListener(RealDataSelectorFocusLisntner);
                    stockParamsPanel[i].add( dataSelector[i] );

                    stockParamsPanel[i].add( new JLabel( "Stock name:" ) );
                    realStockName[i] = new JTextField( DEFAULT_STOCK_NAME[i] );
                    //realStockName.enable( false );
                    stockParamsPanel[i].add( realStockName[i] );


                    JPanel totalPanel = new JPanel(new BorderLayout());
                    totalPanel.setBorder(BorderFactory.createEtchedBorder());

                    JLabel label = new JLabel("Stock options:");
                    Font labelFont = label.getFont();
                    label.setFont(new Font(labelFont.getName(), labelFont.getStyle(), labelFont.getSize() + 4));

                    totalPanel.add(label, BorderLayout.NORTH);
                    totalPanel.add(stockParamsPanel[i], BorderLayout.SOUTH);

                    panel2[i].add( totalPanel );
                    tempstockPanel.add(panel2[i]);
                    //stocksPreferencesTabPanel.add(panel2[i], BorderLayout.CENTER); 
                }
                stocksPreferencesTabPanel.add(tempstockPanel, BorderLayout.CENTER); 
	}

	public void reinitMarketData()	{
           //System.out.println( "Reinit stock price" );
           stocksPrices = stockEps = stockPricesDividendRatio = null;
           stocksPrices = new StockContainer[MAX_STOCK_COUNT];
           stockEps = new StockContainer[MAX_STOCK_COUNT];
           stockPricesDividendRatio = new StockContainer[MAX_STOCK_COUNT];
           realDataCounter = 0;
           for ( int x = 0; x < MAX_STOCK_COUNT; x++ ) {
              stocksPrices[x] = new StockContainer();
              stockPricesDividendRatio[x] = new StockContainer();
              stockEps[x] = new StockContainer(); 
           }
           for ( int i = 0; i < startFromDay; i++ ) {
               for ( int x = 0; x < MAX_STOCK_COUNT; x++ ) {
                   if ( realData[x] ) {
                      //System.out.println( " realDataCounter " + realDataCounter );
                      stocksPrices[x].add( i, stockRealData[x][realDataCounter] ); 
                      stockPricesDividendRatio[x].add( i, stockRealData[x][realDataCounter] / dividend[x] );
                   }
               }
               realDataCounter++;
           }
            //for ( int i = 0; i < startFromDay; i++ ) {
            for ( int x = 0; x < MAX_STOCK_COUNT; x++ ) {
                if ( ! realData[x] ) {
                    stocksPrices[x].add( 0, STOCK_STARTUP_PRICE[x] );
                    stockPricesDividendRatio[x].add( 0, STOCK_STARTUP_PRICE[x] / dividend[x] );
                    double ro = 0.4;
                    double price = 0;
                    double dEps = 0;
                    //Random rNorm = new Random( (new Date()).getTime() );
                    Random rNorm;
                    if ( RandomType.equals( new String ("seed") ) ) rNorm = new Random( (new Date()).getTime() );
                    else rNorm = new Random( ConstRandTime );
                    for ( int i = 1; i < startFromDay; i++ ) {     
                        while ( ( price - ( 3 * transactionCostValue ) ) < ro  ) {
                            dEps = volatility[x] * rNorm.nextGaussian();
                            price = stocksPrices[x].get( i - 1 ) + dEps;
                        }
                        stocksPrices[x].set( i, price );
                        stockPricesDividendRatio[x].add( i, price / dividend[x] );
                        stockEps[x].set( i, dEps );
                   }
                }
            }
            profitVisibility = new ArrayList();
                if ( Grafik ) stocksVisibility = new ArrayList();
                for (int j = 0; j < firmCount; j++ ) {
                    if ( Grafik ) stocksVisibility.add( DEFAULT_MARKET_PRICE_VISIBILITY );
                    profitVisibility.add( DEFAULT_MARKET_PRICE_VISIBILITY );
            }
            //System.out.println( "End reinit stock price" );
        }

        private boolean reconstructMarketOneStockPanel() {
                if ( !Grafik ) return false;
                for ( int y =0 ; y < MAX_STOCK_COUNT ; y++ )
                    stockMarketOneStockPanel[y].removeAll();
                //stockMarketOneStockPanel.removeAll();
                JPanel panel3 = new JPanel();
                panel3.setLayout( new FlowLayout() );//GridLayout(1, firmCount*2 ) );
                stockMarketGraphic = new TimeSeriesCollection[MAX_STOCK_COUNT];
                for ( int y =0 ; y < MAX_STOCK_COUNT ; y++ ) {
                    if ( stockMarketGraphic[y] == null ) stockMarketGraphic[y] = new TimeSeriesCollection();
                    stockMarketGraphic[y].addSeries( stocksSeries[y] );
                }
                    
                //stockMarketGraphic[y].addSeries( stocksSeries[y] );
                
                stockMarketBankGraphic = new TimeSeriesCollection();
                stockMarketBankGraphic.addSeries( bankSeries );
                
                for (int j = 0; j < firmCount; j++ ){
                    boolean visible = ((Boolean)stocksVisibility.get(j)).booleanValue();
                    /*if ( visible == true ){
                            for ( int x = 0; x < MAX_STOCK_COUNT; x++ ) {
                                stockMarketGraphic[x].addSeries( customerPreditedBuyPricesSeries[j][x] );
                                stockMarketGraphic[x].addSeries( customerPreditedSellPricesSeries[j][x] );
                                stockMarketGraphic[x].addSeries( customerPreditedBuy1PricesSeries[j][x] );
                                stockMarketGraphic[x].addSeries( customerPreditedSell1PricesSeries[j][x] );
                                stockMarketGraphic[x].addSeries( customerPreditedBuy2PricesSeries[j][x] );
                                stockMarketGraphic[x].addSeries( customerPreditedSell2PricesSeries[j][x] );
                            }
                    }*/
                    customerStockVisibilityCheckBoxes[j] = new JCheckBox("Customer #" + j, visible);
                    customerStockVisibilityCheckBoxes[j].addActionListener( customerPricesVisibilityChangeListener );
                    panel3.add( customerStockVisibilityCheckBoxes[j] );
                }
                JFreeChart chart[] = new JFreeChart[MAX_STOCK_COUNT];
                ChartPanel panel1[] = new ChartPanel[MAX_STOCK_COUNT];
                for ( int x = 0; x < MAX_STOCK_COUNT; x++ ) {
                    chart[x] = ChartFactory.createTimeSeriesChart("Stock  market " + x, "Date", "Price", stockMarketGraphic[x], true);
                    panel1[x] = new ChartPanel( chart[x] );
                    stockMarketOneStockPanel[x].add( panel1[x], BorderLayout.CENTER );
                    stockMarketOneStockPanel[x].add( panel3, BorderLayout.SOUTH );
                }
                
                return true;
                
	}

	private void reconstructMarketCustomerProfitPanel() {
		if ( Grafik ) {
                    stockMarketCustomerProfitPanel.removeAll();
                    JPanel panel3 = new JPanel();
                    panel3.setLayout( new FlowLayout() );//GridLayout(1, firmCount*2 ) );
                    stockMarketCustomerProfitGraphic = new TimeSeriesCollection();
                    for (int j = 0; j < firmCount; j++ ) {
                        boolean visible = ((Boolean)profitVisibility.get(j)).booleanValue();
                            if ( visible == true )
                                    stockMarketCustomerProfitGraphic.addSeries( customerProfitSeries[j] );
                            customerProfitVisibilityCheckBoxes[j] = new JCheckBox("Customer #" + j, visible);			
                            customerProfitVisibilityCheckBoxes[j].addActionListener( customerProfitVisibilityChangeListener );	
                            panel3.add( customerProfitVisibilityCheckBoxes[j]);				
                    }
                    JFreeChart chart = ChartFactory.createTimeSeriesChart("Customers profit", "Date", "Profit", stockMarketCustomerProfitGraphic, true);
                    ChartPanel panel = new ChartPanel( chart );
                    stockMarketCustomerProfitPanel.add( panel, BorderLayout.CENTER );
                    stockMarketCustomerProfitPanel.add( panel3, BorderLayout.SOUTH );
                }
	}

        private void reconstructMarketCustomerPredictPanel() {
            if ( Grafik ) {
                JPanel[]  panel4 = new JPanel[MAX_STOCK_COUNT];
                JFreeChart[] CustomerPredictionChart = new JFreeChart[MAX_STOCK_COUNT];
                ChartPanel[] panel2 = new ChartPanel[MAX_STOCK_COUNT];
                //TimeSeriesCollection[MAX_STOCK_COUNT];
                for ( int x = 0; x < MAX_STOCK_COUNT; x++ ) {
                    stockMarketCustomerPredictPanel[x].removeAll();

                    panel4[x] = new JPanel();
                    panel4[x].setLayout( new FlowLayout() );//GridLayout(1, firmCount*2 ) );
                    stockMarketCustomerPredictGraphic[x] = new TimeSeriesCollection();
                    stockMarketCustomerPredictGraphic[x].addSeries( stocksSeries[x] );
                    
                    for (int j = 0; j < firmCount; j++ ) 
                        stockMarketCustomerPredictGraphic[x].addSeries( customerPredictSeries[j][x] );
                    
                    CustomerPredictionChart[x] = ChartFactory.createTimeSeriesChart("Customers predictiont of " + x + " stock", "Date", "Predict", stockMarketCustomerPredictGraphic[x], true);
                    panel2[x] = new ChartPanel( CustomerPredictionChart[x] );
                    stockMarketCustomerPredictPanel[x].add( panel2[x], BorderLayout.CENTER );
                    stockMarketCustomerPredictPanel[x].add( panel4[x], BorderLayout.SOUTH );
                }
            }
	}

        private void reconstructBankPredictPanel() {
            if ( Grafik ) {
                stockMarketBankPanel.removeAll();
                JPanel panelbank = new JPanel();
                panelbank.setLayout( new FlowLayout() );
                stockMarketBankGraphic = new TimeSeriesCollection();
                stockMarketBankGraphic.addSeries( bankSeries );
                JFreeChart chartbank = ChartFactory.createTimeSeriesChart("Bank profit", "Date", "Bank profit", stockMarketBankGraphic, true);
                ChartPanel panelchartbank = new ChartPanel( chartbank );
                stockMarketBankPanel.add( panelchartbank, BorderLayout.CENTER );
                stockMarketBankPanel.add( panelbank, BorderLayout.SOUTH );
            }
	}
	
	public void reinitMarketTabPanel() {
		if ( Grafik ) {
                    stocksMarketTabPanel.removeAll();
                    customerStockVisibilityCheckBoxes = new JCheckBox[firmCount];
                    customerProfitVisibilityCheckBoxes = new JCheckBox[firmCount];
                    bankSeries  =  new BasicTimeSeries("Bank profit");
                    /*
                    customerPreditedBuyPricesSeries = new BasicTimeSeries[firmCount][MAX_STOCK_COUNT];
                    customerPreditedSellPricesSeries = new BasicTimeSeries[firmCount][MAX_STOCK_COUNT];
                    customerPreditedBuy1PricesSeries = new BasicTimeSeries[firmCount][MAX_STOCK_COUNT];
                    customerPreditedSell1PricesSeries = new BasicTimeSeries[firmCount][MAX_STOCK_COUNT];
                    customerPreditedBuy2PricesSeries = new BasicTimeSeries[firmCount][MAX_STOCK_COUNT];
                    customerPreditedSell2PricesSeries = new BasicTimeSeries[firmCount][MAX_STOCK_COUNT];
                    */
                    customerProfitSeries = new BasicTimeSeries[firmCount];
                    customerPredictSeries = new BasicTimeSeries[firmCount][MAX_STOCK_COUNT];
                    stockMarketCustomerPredictGraphic = new TimeSeriesCollection[MAX_STOCK_COUNT];
                    stocksSeries = new BasicTimeSeries[MAX_STOCK_COUNT];
                    
                    stockMarketCustomerProfitGraphic = new TimeSeriesCollection();
                    for( int x = 0; x < MAX_STOCK_COUNT; x++ )
                        stockMarketCustomerPredictGraphic[x] = new TimeSeriesCollection();
                    stockMarketBankGraphic = new TimeSeriesCollection();
                    
                    bankSeries = new BasicTimeSeries("Bank profit" );
                                       
                    for( int x = 0; x < MAX_STOCK_COUNT; x++ )
                        stocksSeries[x] = new BasicTimeSeries( "Stock price " + x, Day.class );
                    
                    for (int j = 0; j < firmCount; j++ ){
                        for( int x = 0; x < MAX_STOCK_COUNT; x++ ) {
                            /*
                            customerPreditedBuyPricesSeries[j][x] = new BasicTimeSeries("zb1 user#" + j + " stock " + x );
                            customerPreditedSellPricesSeries[j][x] = new BasicTimeSeries("zs1 of user#" + j + " stock " + x );
                            customerPreditedBuy1PricesSeries[j][x] = new BasicTimeSeries("zb2 of user#" + j + " stock " + x );
                            customerPreditedSell1PricesSeries[j][x] = new BasicTimeSeries("zs2 of user#" + j + " stock " + x );
                            customerPreditedBuy2PricesSeries[j][x] = new BasicTimeSeries("zb3 of user#" + j + " stock " + x );
                            customerPreditedSell2PricesSeries[j][x] = new BasicTimeSeries("zs3 of user#" + j + " stock " + x );
                            */
                            customerPredictSeries[j][x] = new BasicTimeSeries("Customer # " + j + " stock " + x );
                        }

                        customerProfitSeries[j] = new BasicTimeSeries("Customer #" + j);
                        

                    }
                    
                    stockMarketOneStockPanel = new JPanel[MAX_STOCK_COUNT];
                    for ( int x = 0; x < MAX_STOCK_COUNT; x++ ) {
                        stockMarketOneStockPanel[x] = new JPanel();
                        stockMarketOneStockPanel[x].setLayout( new BorderLayout() );
                    }
                    reconstructMarketOneStockPanel();
                    for ( int x = 0; x < MAX_STOCK_COUNT; x++ )
                        stocksMarketTabPanel.addTab( "Stock  market " + x , stockMarketOneStockPanel[x] );
                    
                    
                    stockMarketCustomerPredictPanel = new JPanel[MAX_STOCK_COUNT];
                    for ( int x = 0; x < MAX_STOCK_COUNT; x++ ) {
                        stockMarketCustomerPredictPanel[x] = new JPanel();
                        stockMarketCustomerPredictPanel[x].setLayout( new BorderLayout() );
                    }
                    //stockMarketCustomerPredictPanel.setLayout( new BorderLayout() );
                    reconstructMarketCustomerPredictPanel();
                    for ( int x = 0; x < MAX_STOCK_COUNT; x++ )
                        stocksMarketTabPanel.addTab( "Customer Predictions " + x, stockMarketCustomerPredictPanel[x] );
                                        
                    stockMarketCustomerProfitPanel = new JPanel();
                    stockMarketCustomerProfitPanel.setLayout( new BorderLayout() );
                    reconstructMarketCustomerProfitPanel();
                    stocksMarketTabPanel.addTab( "Customer profit", stockMarketCustomerProfitPanel );
                    
                    stockMarketBankPanel  = new JPanel();
                    stockMarketBankPanel.setLayout( new BorderLayout() );
                    reconstructBankPredictPanel();
                    stocksMarketTabPanel.addTab( "Bank Profit", stockMarketBankPanel );
                }
                	
	}
	
	private void reinitCustomerData() {
                customers = null;
                customers = new ArrayList();
		int[]  iN = new int[MAX_STOCK_COUNT];
                double[] zPred = new double[MAX_STOCK_COUNT];
                for ( int i = 0; i < MAX_STOCK_COUNT; i++ ) {
                    iN[i] = 0;
                    zPred[i] = 0.0;
                }
                //int iIterN = 0;
                //double Delta = 0.0;
                //double dProfit = 0;
                //double credit = DEFAULT_CREDIT;
                for (int j = 0; j < firmCount; j++) {
                        SRGMCustomer customer = new SRGMCustomer( MAX_STOCK_COUNT );
                        customer.prepareStorage();
                        customer.iStrategy = this.metodset[j];
                        customer.riskStrategy = defaultRiskStrategy;
                        //this.customerRiskStrategyUpdated(customerRiskStragegyComboBox[j]);
                        customer.setInitialData( zPred, 0, iN, 0, 0.0, limitCoff );
                        customers.add( customer );	
		}
	}	

	private void reinitCustomerTabPanel() {
		customerTabPanel.removeAll();
		customerStrategyComboBox = new JComboBox[firmCount];
                customerRiskStragegyComboBox = new JComboBox[firmCount];
                customerHasStockField = new JTextField[firmCount][MAX_STOCK_COUNT];
                customerProfitField = new JTextField[firmCount];
                maxCreditField = new JTextField[firmCount];
                borowedSumField = new JTextField[firmCount];
                insovlementField = new JTextField[firmCount];
                forcebuyField = new JTextField[firmCount];
                forcesellField = new JTextField[firmCount];
                
                customerInvestmentType = new JComboBox[firmCount];
                customerInvestmentLaikas = new JComboBox[firmCount];;
                customerInvestmentMetod = new JComboBox[firmCount];
                customerInvestmentForShortStrategies = new JComboBox[firmCount];        
                customerInvestmentIterations = new JTextField[firmCount];
                operationLastSell = new JTextField[firmCount];
                operationLastBuy = new JTextField[firmCount];
                
                
		JPanel panel = new JPanel();
		panel.setLayout( new FlowLayout() );//GridLayout(1, firmCount) );
		for (int j = 0; j < firmCount; j++ ){	
			JPanel customerPanel = new JPanel();
                        customerPanel.setLayout( new GridLayout( ( 15 + MAX_STOCK_COUNT ) , 2) );
			customerPanel.add( new JLabel("Method:") );
			SRGMCustomer customer = (SRGMCustomer)customers.get( j );
			customerStrategyComboBox[j] = new JComboBox(STRATEGY_METHODS);
                        customerStrategyComboBox[j].setSelectedIndex( customer.iStrategy );
                        customerStrategyComboBox[j].addItemListener( customerStrategyChangeListener );
                        customerPanel.add( customerStrategyComboBox[j] );
                        
                        customerPanel.add( new JLabel("Risk:") );
                        customerRiskStragegyComboBox[j] = new JComboBox( RISK_STRATEGY_METHODS );
			customerRiskStragegyComboBox[j].setSelectedIndex(customer.riskStrategy);
                        customerRiskStragegyComboBox[j].addItemListener(customerRiskStrategyListner);
                        customerPanel.add( customerRiskStragegyComboBox[j] );

                        for ( int c = 0; c < MAX_STOCK_COUNT; c++ ){
                            int hasStock = ((Integer)customer.iN.get(c)).intValue();
                            customerHasStockField[j][c] = new JTextField("" + hasStock ,5 );
                            customerHasStockField[j][c].addFocusListener( customerPreferencesFocusListener );
                            customerPanel.add( new JLabel("Has stock " + c + " :" ) );
                            customerPanel.add( customerHasStockField[j][c] );
                        }
                        customerPanel.add(new JLabel("Profit:"));
			Double hasProfit = new Double ( customer.dProfit );
                        customerProfitField[j] = new JTextField( hasProfit.toString() );
                        customerProfitField[j].addFocusListener( customerPreferencesFocusListener);
			customerPanel.add(customerProfitField[j]);
                        
                        customerPanel.add(new JLabel("max Credit:"));
			Double hasCredit = new Double (customer.Limit);
                        maxCreditField[j] = new JTextField( hasCredit.toString() );
                        maxCreditField[j].addFocusListener( customerPreferencesFocusListener);
			customerPanel.add(maxCreditField[j]);
                        
                        customerPanel.add(new JLabel("Borrowed sum:"));
			Double hasBorrowed = new Double (customer.B);
                        borowedSumField[j] = new JTextField( hasBorrowed.toString() );
                        borowedSumField[j].addFocusListener( customerPreferencesFocusListener);
			customerPanel.add(borowedSumField[j]);
                        
                        customerPanel.add(new JLabel("Insolvement:"));
			Boolean hasInsolvement = new Boolean (customer.insolvement);
                        insovlementField[j] = new JTextField( hasInsolvement.toString() );
			insovlementField[j].addFocusListener( customerPreferencesFocusListener);
			customerPanel.add(insovlementField[j]);
                        
                        customerPanel.add(new JLabel("Force buy:"));
			//Boolean fbuy = new Boolean (customer.forcebuy);
                        Double fbuy = new Double( customer.forcebuy );
                        forcebuyField[j] = new JTextField( fbuy.toString() );
			forcebuyField[j].addFocusListener( customerPreferencesFocusListener);
			customerPanel.add(forcebuyField[j]);
                        
                        customerPanel.add(new JLabel("Force sell:"));
			//Boolean fsell = new Boolean (customer.forcesell);
                        Double fsell = new Double ( customer.forcesell );
                        forcesellField[j] = new JTextField( fsell.toString() );
			forcesellField[j].addFocusListener( customerPreferencesFocusListener);
			customerPanel.add(forcesellField[j]);
                        
                        /*customerPanel.add( new JLabel("Risk:") );
                        customerRiskStragegyComboBox[j] = new JComboBox( RISK_STRATEGY_METHODS );
			customerRiskStragegyComboBox[j].setSelectedIndex(customer.riskStrategy);
                        customerRiskStragegyComboBox[j].addItemListener(customerRiskStrategyListner);
                        customerPanel.add( customerRiskStragegyComboBox[j] );*/
                        
                        customerPanel.add(new JLabel("Long invest type:"));
			customerInvestmentType[j] = new JComboBox( INVESTMENT_TYPES );
                        customerInvestmentType[j].setSelectedIndex(customer.InvestmentType);
                        customerInvestmentType[j].addItemListener(customerInvestmentTypeListner);
                        customerPanel.add(customerInvestmentType[j]);
                        
                        customerPanel.add(new JLabel("Long invest interval:"));
			customerInvestmentLaikas[j] = new JComboBox( INVESTMENT_INTERVALS );
                        customerInvestmentLaikas[j].setSelectedIndex(customer.InvestmentInterval);
                        customerInvestmentLaikas[j].addItemListener(customerInvestmentIntervalListner);
                        customerPanel.add(customerInvestmentLaikas[j]);
                        
                        customerPanel.add(new JLabel("Long invest method:"));
			customerInvestmentMetod[j] = new JComboBox( INVESTMENT_METODS );
                        customerInvestmentMetod[j].setSelectedIndex(customer.InvestmentMetod);
                        customerInvestmentMetod[j].addItemListener(customerInvestmentMetodListner);
                        customerPanel.add(customerInvestmentMetod[j]);
                        
                        //customerInvestmentIterations = new JTextField[firmCount];
                        customerPanel.add(new JLabel("InvestmentIterations:"));
			Integer iterations = new Integer ( customer.InvestmentIterations );
                        customerInvestmentIterations[j] = new JTextField( iterations.toString() );
                        customerInvestmentIterations[j].addFocusListener( customerInvestmentInterationListner );
			customerPanel.add(customerInvestmentIterations[j]);
                        
                        customerPanel.add(new JLabel("Last sell operation:"));
                        operationLastSell[j] = new JTextField( "" );
                        operationLastSell[j].setEditable(false);
			customerPanel.add(operationLastSell[j]);
                        
                        customerPanel.add(new JLabel("Last buy operation:"));
                        operationLastBuy[j] = new JTextField( "" );
                        operationLastBuy[j].setEditable(false);
			customerPanel.add(operationLastBuy[j]);
                        
                        customerPanel.add( new JLabel("Long invest for shorts:") );
                        customerInvestmentForShortStrategies[j] = new JComboBox( LONG_INVEST_FOR_SHORT );
			customerInvestmentForShortStrategies[j].setSelectedIndex(customer.InvestmentForShortStrategies);
                        customerInvestmentForShortStrategies[j].addItemListener(customerInvestForShortStrategiesChangeListner);
                        customerPanel.add( customerInvestmentForShortStrategies[j] );
			
			JPanel fullCustomerPanel = new JPanel();
			fullCustomerPanel.setLayout( new BorderLayout() );
                        fullCustomerPanel.add( new JLabel("Customer #" + j), BorderLayout.NORTH );
                        fullCustomerPanel.add( customerPanel, BorderLayout.CENTER );
			fullCustomerPanel.setBorder( BorderFactory.createEtchedBorder() );
			
			panel.add( fullCustomerPanel );
		}
		
		JPanel firmCountPanel = new JPanel();
		firmCountPanel.setLayout( new FlowLayout() );
		firmCountPanel.add( new JLabel("FirmCount:") );
		String[] firmCounts = new String[MAX_FIRM_COUNT-1];
		for ( int j = 1; j < MAX_FIRM_COUNT; j++ )
			firmCounts[j - 1] = "" + j;
		firmCountComboBox = new JComboBox( firmCounts );
		firmCountComboBox.addItemListener( firmCountChangeListener );
		firmCountComboBox.setSelectedItem( "" + firmCount );
		firmCountPanel.add( firmCountComboBox );
		firmCountPanel.setBorder( BorderFactory.createEtchedBorder() );
		
		customerTabPanel.setLayout( new BorderLayout() );
		customerTabPanel.add( firmCountPanel, BorderLayout.NORTH );
		customerTabPanel.add( panel, BorderLayout.CENTER );
		
	}
	public void initListners() {
                yieldFocusListener = new YieldFocusListener(this);
                transactionFocusListner = new TransactionFocusListner(this);
                bankInterestFocusListner = new BankInterestFocusListner(this);
		stockPreferencesFocusListener = new StockPreferencesFocusListener(this);
		firmCountChangeListener = new FirmCountChangeListener(this);
                stockCountChangeListener = new StockCountChangeListener(this);
                realDataPeriodChangeListner = new RealDataPeriodChangeListner(this);
		customerStrategyChangeListener = new CustomerStrategyChangeListener(this);
                customerRiskStrategyListner = new CustomerRiskStrategyChangeListner(this);
                customerInvestForShortStrategiesChangeListner = new CustomerInvestForShortStrategiesChangeListner(this);
		customerPreferencesFocusListener = new CustomerPreferencesFocusListener(this);
		customerPricesVisibilityChangeListener = new CustomerPricesVisibilityChangeListener(this);
		customerProfitVisibilityChangeListener = new CustomerProfitVisibilityChangeListener(this);//ed
		controlButtonsListener = new ControlButtonsListener(this);
                RealDataSelectorFocusLisntner = new dataSelectorListner(this);
                
                customerInvestmentTypeListner = new CustomerInvestmentTypeChangeListner(this);
                customerInvestmentMetodListner = new CustomerInvestmentMethodChangeListner(this);
                customerInvestmentIntervalListner = new CustomerInvestmentIntervalChangeListner(this);
                customerInvestmentInterationListner = new CustomerInvestmentIterationsChangeListner(this);
                
        }
        
        public void LoggerInit() {
            /*
            if ( writeLog ) {
                   try{
                        logfile = new FileHandler("C:/logs/vk.log");
                        log = Logger.getLogger("log_file");
                        log.addHandler(logfile);
                   }
                   catch(IOException e){
                       System.out.println("klaida atidarius faila");
                       writeLog = false;
                   }
                        
            }*/
        }
        
        public void LoggerWrite( String mes ) {
            //System.out.println( mes );
            /*Writer output = null;
            File file = new File("write.html");
            try {
                output = new BufferedWriter(new FileWriter(file,true));
                //System.out.println("Your file has been written");
                output.write(mes);
                output.close();
            } catch (IOException ex) {
                Logger.getLogger(StartupApplet.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println("Your file has not been written");
            }*/
        }
        
        public void checkCurrentDir() {
            System.out.println();
            System.out.println();
            System.out.println("----------Directory for writing logs----------");
            String current = "";
            try {
                current = new java.io.File( "." ).getCanonicalPath();
                System.out.println("Current dir:"+current);
            } catch (IOException ex) {
                Logger.getLogger(StartupApplet.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println("Current dir:"+current);
            }
            String currentDir = System.getProperty("user.dir");
            System.out.println("Current dir using System: " + currentDir);
            System.out.println();
            System.out.println();
        }

        public StartupApplet()	{
            checkCurrentDir();
            LoggerInit();
            startupTime = Calendar.getInstance();
            initListners();
            reinitStockPreferencesTabPanel();
            reinitMarketData();
            reinitMarketTabPanel();
            reinitCustomerData();
            reinitCustomerTabPanel();
            constructAboutPanel();
            mainPanel.addTab( "Stock Preferences", stocksPreferencesTabPanel );
            mainPanel.addTab( "Market", stocksMarketTabPanel );
            //mainPanel.addTab( "Customer Preferences", customerTabPanel );
            mainPanel.addTab( "Customer Preferences", new JScrollPane( customerTabPanel ) );
            mainPanel.addTab( "About", aboutPanel );
            
            //tabs.addTab("Test", new JScrollPane(textPane));
            
            mainPanel.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
            
            getContentPane().add( mainPanel, BorderLayout.CENTER );
            getContentPane().add( getControlButtonsPanel(), BorderLayout.SOUTH );
            bank1 = new Bank();
            //getRealData();                  
	}
        /*
        public void getRealData() {
                loadYahooData yahoo = new loadYahooData(  realStockName.getText() ,2009,12,20,2011,12,20);
                String yahoo_data[][] = yahoo.rezult();
                stockRealData = new double[yahoo_data.length]; 
                int j_ = 0; 
                for (int i = yahoo_data.length-1; i >= 0; i--) {
                    stockRealData[j_] = Double.parseDouble(yahoo_data[i][4]);
                    j_++;
                } 
        }
	*/
        
        public void getRealData() {
            Calendar cal = Calendar.getInstance();
            int day_now = cal.get(Calendar.DAY_OF_MONTH);
            int month_now = cal.get(Calendar.MONTH);
            int year_now = cal.get(Calendar.YEAR);

            Calendar cal2 = Calendar.getInstance();
            cal2.add( Calendar.DATE, - ((int)( termin * 1.7 )) );
            //cal2.add(Calendar.MONTH, -18);
            int day_before = cal2.get(Calendar.DAY_OF_MONTH);
            int month_before = cal2.get(Calendar.MONTH);
            int year_before = cal2.get(Calendar.YEAR);
            stockRealData = new double [MAX_STOCK_COUNT][];
            
            for( int x = 0; x < MAX_STOCK_COUNT; x++ ) {
                if ( !realData[x] ) continue;
                String period = "d";
                if ( realDataPeriod == "month" ) {
                    period = "m";
                    System.out.println( "set period month" );
                }
                if ( realDataPeriod == "week" ) {
                    period = "w";
                    System.out.println( "set period week" );
                }
                
                loadYahooData yahoo = new loadYahooData( realStockName[x].getText(), year_before, month_before, day_before, year_now, month_now, day_now, period );
                String yahoo_data[][] = yahoo.rezult();
                if ( yahoo_data.length < termin ) {
                    termin = yahoo_data.length;
                    terminField.setText("" + new Integer( termin ).toString());
                    //stockRealData[x] = new double[yahoo_data.length];
                }
                stockRealData[x] = new double[termin];
                //System.out.println( " " + year_before + " " + month_before+ " " + day_before+ " " + year_now+ " " + month_now+ " " + day_now );
                int j_ = 0; 
                //System.out.println( " Duomenu ilgis " + yahoo_data.length );
                //System.out.println( " Duomenu ilgis faktinis " + termin );
                for ( int i = yahoo_data.length - 1; i >= 0; i-- ) {
                    if ( i < termin ) {
                        stockRealData[x][j_] = Double.parseDouble(yahoo_data[i][4]);
                        //System.out.println("aa = " + stockRealData[x][j_]);
                        j_++;
                    }
                    //if ( j_ >= termin ) break;
                }
                //System.out.println( " Duomenu ilgis faktas " + yahoo_data.length );
            }
            
        }
	public synchronized void updateGUI() {
                //System.out.println( "update gui" );
		readingData = true;
                int iterNr = stocksPrices[0].getIterNr();
                Calendar now = (Calendar)startupTime.clone();
                now.add(Calendar.DAY_OF_MONTH, iterNr);
                Day day = new Day( now.getTime() );
                //System.out.println( " day " + day );
                if ( Grafik ) {
                    bankSeries.add( day, bank1.bankProfit );
                    for ( int xx = 0; xx < MAX_STOCK_COUNT; xx++ )
                        stocksSeries[xx].add( day, stocksPrices[xx].get( stocksPrices[xx].getLastKey() - 1 ) );
                    
                    for ( int j = 0; j < firmCount; j++ ) {
                            SRGMCustomer customer = (SRGMCustomer)customers.get( j );
                            
                            for ( int x = 0; x < MAX_STOCK_COUNT; x++ ) {
                                customerPredictSeries[j][x].add( day , customer.dZpred.get(x) );
                            }
                    }
                    //remove obsolete market history
                    if ( iterNr - lastRemovedFromHistory > stockHistory ) {
                            now = (Calendar)startupTime.clone();
                            now.add(Calendar.DAY_OF_MONTH, lastRemovedFromHistory);
                            Day removeDay = new Day( now.getTime() );
                            //remove stock 'i' price
                            for ( int x = 0; x < MAX_STOCK_COUNT; x++ )
                                stocksSeries[x].delete( removeDay );
                            bankSeries.delete( removeDay );
                            lastRemovedFromHistory++;
                    }
                }
                                
                for ( int j = 0; j < firmCount; j++ ) {
			SRGMCustomer customer = (SRGMCustomer)customers.get( j );
                        for ( int counter = 0; counter < MAX_STOCK_COUNT; counter++) {
                            //System.out.println( " predicion " + j + " customer " + counter + " akcija " + " prediction  = " + customer.dZpred[counter] );
                            Integer hasStock = (Integer)customer.iN.get(counter);
                            //Integer hasStock = customer.iN[counter];
                            customerHasStockField[j][counter].setText( hasStock.toString() );
                        }
                        Double hasProfit = new Double ( customer.dProfit );
                        customerProfitField[j].setText( ((Integer)( hasProfit.intValue() ) ).toString() );
                        Double hasCredit = new Double (customer.Limit);
                        maxCreditField[j].setText( hasCredit.toString() );
			Double hasBorrowed = new Double (customer.B);
                        borowedSumField[j].setText( ((Integer)( hasBorrowed.intValue() ) ).toString() );
                        Boolean hasInsolvement = customer.insolvement;
                        insovlementField[j].setText( hasInsolvement.toString() );
                        Double fbuy = new Double ( customer.forcebuy );
                        forcebuyField[j].setText( fbuy.toString() );
                        Double fsell = new Double( customer.forcesell );
                        forcesellField[j].setText( fsell.toString() );
                        if ( Grafik ) customerProfitSeries[j].add( day, customer.dProfit );
		}
		readingData = false;
	}
	
	
	public double parseText(double initialValue, JTextField field ) {
		try {
			return Double.parseDouble(field.getText());
		}
		catch (NumberFormatException nfe) {
			Toolkit.getDefaultToolkit().beep();
			field.setText("" + initialValue);
			return initialValue;
		}
	}
        
        public double parseText(double initialValue, JTextField field, int minValue, int maxValue ) {
		try {
			//return Double.parseDouble(field.getText());
                        double value = Double.parseDouble( field.getText() );
			if ((value > maxValue) || (value < minValue)) {
				throw new NumberFormatException();
			}
			return value;
		}
		catch ( NumberFormatException nfe ) {
			Toolkit.getDefaultToolkit().beep();
			field.setText("" + initialValue);
			return initialValue;
		}
	}

	public int parseText(int initialValue, JTextField field, int minValue, int maxValue) {
		try {
			int value = Integer.parseInt(field.getText());
			if ((value > maxValue) || (value < minValue)) {
				throw new NumberFormatException();
			}
			return value;
		}
		catch (NumberFormatException nfe) {
			Toolkit.getDefaultToolkit().beep();
			field.setText("" + initialValue);
			return initialValue;
		}
	}
        /*
        private boolean parseTextBool( boolean initialValue, JTextField field ) {
            if ( field.getText().equals( new String("false") ) ) {
                field.setText("false");
                return false;
            }
            if ( field.getText().equals(new String( "true" ) ) ) {
                field.setText("true");
                return true;
            }
            field.setText( new Boolean( initialValue ).toString() );
            return initialValue;
        }
	*/
	private void constructAboutPanel(){
		JPanel tmpPanel = new JPanel();
		tmpPanel.setLayout(new BoxLayout(tmpPanel, BoxLayout.Y_AXIS));
		tmpPanel.add(new JLabel("Stock rate game model."));
		tmpPanel.add(new JLabel(" "));
		tmpPanel.add(new JLabel("Theory: prof. Jonas Mockus"));
                tmpPanel.add(new JLabel("Author: Igor Katin"));
		aboutPanel.add(tmpPanel, BorderLayout.CENTER);
	}

    @Override
	public String getAppletInfo() {
		return "Stock Rate Game Model Test. Author: Igor Katin.";
	}

	public static void main(String[] args) 	{
		StartupApplet sa = new StartupApplet();
		sa.setVisible( true );
	}
        
        public void init() {
            StartupApplet sa = new StartupApplet();
            sa.setVisible( true );
        }

	public void firmCountUpdated() 	{
		int _firmCount = Integer.parseInt( (String)firmCountComboBox.getSelectedItem() );
		if ( firmCount == _firmCount ) return;
		
		firmCount = _firmCount;
                //getRealData();
		reinitCustomerData();
		reinitCustomerTabPanel();
		reinitMarketData();
		reinitMarketTabPanel();
                reconstructMarketCustomerPredictPanel();
                reconstructMarketOneStockPanel();
	}
        
        public void stockCountUpdated() {
            int _stockCount = Integer.parseInt( (String)stockSelector.getSelectedItem() );
            if ( MAX_STOCK_COUNT == _stockCount ) return;
            MAX_STOCK_COUNT = _stockCount;
            //System.out.println( "System max stock count " + MAX_STOCK_COUNT );
            reinitStockPreferencesTabPanel();
            reinitMarketData();
            reinitMarketTabPanel();
            reinitCustomerData();
            reinitCustomerTabPanel();
            
            //reinitCustomerData( false );
            //reinitCustomerTabPanel();
           // reinitMarketData();
            //reinitMarketTabPanel();
            reconstructMarketCustomerPredictPanel();
            reconstructMarketOneStockPanel();
            //reinitStockPreferencesTabPanel();
            
            //startupTime = Calendar.getInstance();
		//initListners();
		//reinitStockPreferencesTabPanel();
		//reinitMarketData();
		//reinitMarketTabPanel();
		//reinitCustomerData( false );
		//reinitCustomerTabPanel();
        }
        
        public void realDataPeriodUpdated() {
            String _temp = (String) realDataPeriodSelector.getSelectedItem();
            if ( realDataPeriod == _temp ) return;
            realDataPeriod = _temp;
            System.out.println( "Real data period " + realDataPeriod );
            reinitStockPreferencesTabPanel();
            reinitMarketData();
            reinitMarketTabPanel();
            reinitCustomerData();
            reinitCustomerTabPanel();
            
            //reinitCustomerData( false );
            //reinitCustomerTabPanel();
           // reinitMarketData();
            //reinitMarketTabPanel();
            reconstructMarketCustomerPredictPanel();
            reconstructMarketOneStockPanel();
            //reinitStockPreferencesTabPanel();
            
            //startupTime = Calendar.getInstance();
		//initListners();
		//reinitStockPreferencesTabPanel();
		//reinitMarketData();
		//reinitMarketTabPanel();
		//reinitCustomerData( false );
		//reinitCustomerTabPanel();
        }
	
	public void customerStrategyUpdated( JComboBox combo ) 	{
            for (int j = 0; j < firmCount; j++)
              if ( combo == customerStrategyComboBox[j] ) {
                    SRGMCustomer customer = (SRGMCustomer)customers.get( j );
                    customer.iStrategy = combo.getSelectedIndex();
                    customers.set(j, customer);
                    break;
              }
	}
        
        public void customerRiskStrategyUpdated( JComboBox combo ) 	{
            for (int j = 0; j < firmCount; j++)
              if ( combo == customerRiskStragegyComboBox[j] ) {
                    SRGMCustomer customer = (SRGMCustomer)customers.get( j );
                    customer.riskStrategy = combo.getSelectedIndex();
                    customers.set(j, customer);
                    break;
              }
	}
        
        public void customerInvestmentTypeUpdated( JComboBox combo ) 	{
            for (int j = 0; j < firmCount; j++)
              if ( combo == customerInvestmentType[j] ) {
                    SRGMCustomer customer = (SRGMCustomer)customers.get( j );
                    customer.InvestmentType = combo.getSelectedIndex();
                    customers.set(j, customer);
                    System.out.println( customer.InvestmentType );
                    break;
              }
	}
        
        public void customerInvestmentMetodUpdated( JComboBox combo ) 	{
            for (int j = 0; j < firmCount; j++)
              if ( combo == customerInvestmentMetod[j] ) {
                    SRGMCustomer customer = (SRGMCustomer)customers.get( j );
                    customer.InvestmentMetod = combo.getSelectedIndex();
                    customers.set(j, customer);
                    //System.out.println( customer.InvestmentMetod );
                    break;
              }
	}
        
        public void customerShortStrategyUpdated ( JComboBox combo ) 	{
            for (int j = 0; j < firmCount; j++)
              if ( combo == customerInvestmentForShortStrategies[j] ) {
                    SRGMCustomer customer = (SRGMCustomer)customers.get( j );
                    customer.InvestmentForShortStrategies = combo.getSelectedIndex();
                    customers.set(j, customer);
                    //System.out.println( " for short invest " + customer.InvestmentForShortStrategies );
                    break;
              }
	}
        
        public void customerInvestmentIntervalUpdated( JComboBox combo ) 	{
            for (int j = 0; j < firmCount; j++)
              if ( combo == customerInvestmentLaikas[j] ) {
                    SRGMCustomer customer = (SRGMCustomer)customers.get( j );
                    customer.InvestmentInterval = combo.getSelectedIndex();
                    customers.set(j, customer);
                    System.out.println( customer.InvestmentInterval );
                    break;
              }
	}
        	
	public void yieldFieldUpdated() {
            yieldOfCd = parseText(yieldOfCd, yieldOfCdField);
	}

        public void transactionCostFieldUpdates() {
            transactionCostValue = parseText( transactionCostValue, transactionCostField );
        }
        
        public void bankInterestFieldUpdates() {
            bankInterest = parseText( bankInterest, bankInterestField );
        }
        
        public void dataSelectorUpdates( int a, int index ) {
            if ( a > 0 ) realData[index] = true;
            else realData[index] = false;
        }
	
	public void stockPreferencesUpdated(JTextField textField) {
                        for ( int i = 0; i < MAX_STOCK_COUNT; i++ ) {
                            if ( volatilityField[i] == textField ) 
                                volatility[i] = parseText(volatility[i], textField);
                            else if ( dividendField[i] == textField )   
                                dividend[i] = parseText(dividend[i], textField);
                            else if ( limitCoffField == textField ) 
                                limitCoff = parseText( limitCoff, textField);
                            
                            else if ( inertiaField[i] == textField )
                                inertia[i] = parseText( inertia[i], textField, 0, 1 );
                            else if ( stockBankrotProbabilityField[i] == textField )
                                bankruptProbability[i] = parseText( bankruptProbability[i], textField, 0, 1 );
                        }
                        if ( terminField == textField )
                            termin = parseText( termin, textField, 1, 2000 );
                        else if ( startFromDayField == textField ) 
                                startFromDay = parseText( startFromDay, textField, 0, 1000 );
                        else if ( RandomTypeField == textField ) {
                            if ( ! RandomTypeField.getText().equals( new String ( "seed" ) ) ) {
                                RandomTypeField.setText("const");
                                RandomType = RandomTypeField.getText();
                            }
                        }
                        else if ( ribojimasField == textField ) {
                            ribojimas = parseText( ribojimas, textField, 0, 1000 );
                        }
                        else if ( dayInMonthField == textField ) {
                            dayinmonth = parseText( dayinmonth, textField, 10, 1000 );
                        }
	}

	public void customerPreferencesUpdated( JTextField textField )	{
            for (int j = 0; j < firmCount; j++) {
                if ( maxCreditField[j] == textField ) {
                        SRGMCustomer customer = (SRGMCustomer)customers.get( j );
                        customer.Limit = parseText(customer.Limit, textField);
                        break;
                } else if ( borowedSumField[j] == textField ) {
                        SRGMCustomer customer = (SRGMCustomer)customers.get( j );
                        customer.B = parseText(customer.B, textField);
                        break;
                } else if ( forcebuyField[j] == textField ) {
                   SRGMCustomer customer = (SRGMCustomer)customers.get(j);
                   customer.forcebuy = parseText( customer.forcebuy, textField );
                   customers.set( j, customer );
                   break;
               } else if ( forcesellField[j] == textField ) {
                   SRGMCustomer customer = (SRGMCustomer)customers.get(j);
                   customer.forcesell = parseText( customer.forcesell, textField );
                   customers.set( j, customer );
                   break;
               }
               else if ( customerInvestmentIterations[j] == textField ) {
                   SRGMCustomer customer = (SRGMCustomer)customers.get(j);//parseText( termin, textField, 1, 2000 );
                   customer.InvestmentIterations = parseText( customer.InvestmentIterations, textField, 1, 10000 );
                   customers.set( j, customer );
                   break;
               }
               else {
                   int stock;
                   for ( int c = 0; c < MAX_STOCK_COUNT; c++) {
                       if ( customerHasStockField[j][c] == textField )  {
                            SRGMCustomer customer = (SRGMCustomer)customers.get( j );
                            stock = ((Integer)customer.iN.get(c)).intValue();
                            stock = parseText(stock, textField, 0, Integer.MAX_VALUE );
                            customer.iN.set( c, stock );
                            customers.set( j, customer );
                            break;
                       }
                   }
               }
            }
	}	

			
	public void customerPricesVisibilityChanged( JCheckBox checkbox ) {
            for (int j = 0; j < firmCount; j++)
                if ( customerStockVisibilityCheckBoxes[j] == checkbox ) {
                        stocksVisibility.set( j, ( !(Boolean)stocksVisibility.get( j ) ) );
                        reconstructMarketOneStockPanel();
                        stocksMarketTabPanel.validate();
                        break;
                }
	}
        
	public void customerProfitVisibilityChanged( JCheckBox checkbox ) {
	   for (int j = 0; j < firmCount; j++)
            if ( customerProfitVisibilityCheckBoxes[j] == checkbox ) {
                    profitVisibility.set( j, ( !(Boolean)profitVisibility.get( j ) ) );
                    reconstructMarketCustomerProfitPanel();
                    reconstructMarketCustomerPredictPanel();
                    reconstructBankPredictPanel();
                    stocksMarketTabPanel.validate();
                    break;
            }
	}
			
	private void setEnabledActions( boolean enable ) {
		yieldOfCdField.setEnabled( enable );
                for ( int c = 0; c < MAX_STOCK_COUNT; c++ ){
                    volatilityField[c].setEnabled( enable );
                    dividendField[c].setEnabled( enable );
                }
		firmCountComboBox.setEnabled( enable );
		for ( int j = 0; j < firmCount; j++ ) {
                        //customerStockVisibilityCheckBoxes[j].setEnabled( enable );
			customerStrategyComboBox[j].setEnabled( enable );
                        customerRiskStragegyComboBox[j].setEnabled( enable );
                        maxCreditField[j].setEnabled(enable);
                        customerProfitField[j].setEnabled(enable);
                        borowedSumField[j].setEnabled(enable);
                        insovlementField[j].setEnabled(enable);
                        forcebuyField[j].setEditable(enable);
                        forcesellField[j].setEditable(enable);
                        for ( int c = 0; c < MAX_STOCK_COUNT; c++ )
                            customerHasStockField[j][c].setEnabled( enable );
		}              
		traceButton.setEnabled( enable );
                xmlWrite.setEnabled(enable);
		runWithDelayButton.setEnabled( enable );
		runWithoutDelayButton.setEnabled( enable );
		stopButton.setEnabled( !enable );
		
	}
	
	private void startCalculation( int delay )	{
		calculationThread = new StockTradeThread( this );
		calculationThread.setDelay( delay );
		calculationThread.start();
	}
	
	private void stopCalculation() 	{
		calculationThread.requestStop();
		//while ( calculationThread.running )
		{
			try { Thread.sleep( 300 ); }
			catch ( Exception ex ) { ex.printStackTrace(); }
		}
	}
	
	private void traceCalculation()	{
		calculationThread = new StockTradeThread( this );
                calculationThread.doShopping( this );
                calculationThread.requestStop();
		updateGUI();
	}
        
        private void startExperiment( int delay ) {
            int i,j;
            String [] str = new String[firmCount];
            String [] str2 = new String[firmCount];
            for (int ii = 0; ii < firmCount; ii++) {
                SRGMCustomer customer = (SRGMCustomer)customers.get(ii);
                str[ii] = STRATEGY_METHODS[customer.iStrategy];
                str2[ii] = RISK_STRATEGY_METHODS[customer.riskStrategy];
            }
            double [] values = new double[firmCount];
            double [][] predicts = new double[firmCount][MAX_STOCK_COUNT];
            //int iIterN = stocksPrices[0].getIterNr();
            for ( i = 0; i < bandymai; i++ ) {
                calculationThread = new StockTradeThread( this );
                calculationThread.setDelay( delay );
                int iIterN = stocksPrices[0].getIterNr();
                //int iIterN = stocksPrices[0].getIterNr();
                //oshybka
                int in[][];
                in = new int[firmCount][MAX_STOCK_COUNT];
                // create tables
                calculationThread.createDatabase();
                for ( j = 0; j < bandymaiDienos; j++  ) {
                    iIterN = stocksPrices[0].getIterNr();
                    //System.out.println( "Iteracija nr " + iIterN );
                    //calculationThread.doShopping( this );
                    //int iIterN = stocksPrices[0].getIterNr();
                    double price[] = new double[MAX_STOCK_COUNT];
                    for ( int stockCount = 0; stockCount < MAX_STOCK_COUNT; stockCount++ ){
                        price[stockCount] = stocksPrices[stockCount].get(iIterN);
                        //predicts[ii][stockCount] = customer.dZpred.get(stockCount);
                    }
                    for (int ii = 0; ii < firmCount; ii++) {
                        SRGMCustomer customer = (SRGMCustomer)customers.get(ii);
                        values[ii] = customer.dProfit;
                         for ( int stockCount = 0; stockCount < MAX_STOCK_COUNT; stockCount++ ) {
                            predicts[ii][stockCount] = customer.dZpred.get(stockCount);
                            //novyj kod
                            in[ii][stockCount] = ((Integer)customer.iN.get(stockCount)).intValue();                
                         }
                    }
                    calculationThread.writeExperimentPaklaida( i, j, str, price, predicts );
                    calculationThread.writeExperimentPortfel( i, j, str, in );
                    calculationThread.writePelnai( i, j, str, str2, values );
                    calculationThread.doShopping( this ); // poprobujem perenesti eto siuda
                   // ??? updateGUI();
                }
                calculationThread.requestStop();
                startupTime = Calendar.getInstance();
                //dlia exp ne nado
                //initListners();
                //reinitStockPreferencesTabPanel();
                reinitMarketData();
                //reinitMarketTabPanel();
                reinitCustomerData();
                //reinitCustomerTabPanel();
                bank1 = new Bank();
            }
            setEnabledActions( true );
        }
	
	public void controlButtonsPressed( JButton button ) throws IOException, ParserConfigurationException, TransformerConfigurationException, TransformerException {
		if ( !realDataLoaded ) {
                    getRealData();
                    reinitMarketData();
                    realDataLoaded = true;
                    /*for (int j = 0; j < firmCount; j++) { 
                        SRGMCustomer customer = (SRGMCustomer)customers.get(j);
                        customer.Limit = customer.Limit * limitCoff;
                    }*/
                }
                for( int i = 0; i < MAX_STOCK_COUNT; i++ )
                    dataSelector[i].enable(false);
                limitCoffField.enable( false );
                String action = button.getText();
                if ( action.equals( CONTROL_BUTTON_TRACE ) ) {
			setEnabledActions( false );
			traceCalculation();
			setEnabledActions( true );
		}
		else if ( action.equals( CONTROL_BUTTON_RUN_WITH_DELAY ) ){
			setEnabledActions( false );
			startCalculation( CALCULATION_THREAD_DELAY );
		}
		else if ( action.equals( CONTROL_BUTTON_RUN ) )	{
			setEnabledActions( false );
			startCalculation( CALCULATION_THREAD_WITHOUT_DELAY );
		}
		else if ( action.equals( CONTROL_BUTTON_STOP ) ){
			stopCalculation();
			setEnabledActions( true );
		}
                else if ( action.equals( CONTROL_BUTTON_XML ) )	{
			write();
			setEnabledActions( true );
		}
                else if ( action.equals( CONTROL_BUTTON_YEAR ) ){
                    Grafik = false;
                    System.out.println( "Experimentas" );
                    setEnabledActions( false );
                    startExperiment( 1 );
                    setEnabledActions( true );
		}
	}

        public void write() throws IOException {
            final JFileChooser fc = new JFileChooser();
            int returnVal = fc.showSaveDialog(this);
            File f = fc.getSelectedFile();

            	try {
                 if(!f.exists()){
                        f.createNewFile();
                  }
                  else {
                        f.delete();
                        f.createNewFile();
                  }
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
		Document doc = docBuilder.newDocument();
                doc.setXmlStandalone(true);
		Element rootElement = doc.createElement("datavalues");
		doc.appendChild(rootElement);

                double [] temp = stocksPrices[0].toArray();
                for (int i = 0; i < temp.length; i++ ) {
                   Element data = doc.createElement("data");
                   data.appendChild(doc.createTextNode( "" + temp[i] ) );
		   rootElement.appendChild(data);
                }
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(f);
                //StreamResult result2 = new StreamResult(f2);
		transformer.transform(source, result);
		//System.out.println("File saved!");

              } 
              catch (ParserConfigurationException pce) {
                    pce.printStackTrace();
              } 
              catch (TransformerException tfe) {
                    tfe.printStackTrace();
              }
              catch ( java.io.IOException iof ) {
                    iof.printStackTrace();
              }
	}
        
        public static void printr( double [] a  ) {
            String s = "";
            for ( int i = 0; i < a.length; i++ )
                s = s + a[i] + " ";
            System.out.println( s );
        }
	
}