package lt.ktu.mockus.srgm;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import defaultPackage.Counter_Portfel;
import defaultPackage.Counter_Sharp;
import java.math.BigDecimal;
import java.sql.DriverManager;
import java.util.*;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import test.UtilityPanel;

public class StockTradeThread extends Thread {
        final int nuostolingiausia = 0;
        final int nuostolinga = 1;
        final int pelninga = 2;
        final int pelningiausia = 3;
         
	private StartupApplet applet = null;
	private int delay = 0;
	private boolean requestStop = false;
	private GUIUpdateNotifier doGUIUpdate = null;
	public boolean running = false;
        /*
        protected String url = "jdbc:mysql://www.tm.lt:3306/tm2";
        protected String userName = "root";
        protected String password = "L8UWR8DJt16YXS9S6MaD";
	*/
        protected String url = "jdbc:mysql://localhost:3306/experiment";
        protected String userName = "root";
        protected String password = "";
        
        protected String tablePortfel = "portfel_table";
        protected String tablePredict = "predict_table";
        protected String tableProfit = "profit_table";

        
        //long term investment
        boolean Can = false;
        String IType, BankNames[] = new String[9], ShareNames[] = new String[9],
			InsuranceNames[] = new String[9], Method;
        
        public Counter_Sharp wCounter;
        public Counter_Portfel wCounterPortfel;
        //public Counter_Sharp wCounterSharp;
        //MeGraphics mGraphics;
        Vector wItVector = new Vector(0), wFVector = new Vector(0);
	JButton w1Button, w2Button, w3Button, w4Button;
        //JLabel wLabel, wALabel[];
        //JProgressBar wProgressBar;
        JTabbedPane wTabbedPane = new JTabbedPane();
        JComboBox w1ComboBox, w2ComboBox, w3ComboBox, wComboBox;
        
        //double [] testUF = {0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9} ;
        UtilityPanel p = new UtilityPanel();                       
        
        double resultGMJ [] ;
        
        double Uf[] = new double[9], 
        BankBankrupt[] = new double[9],
        ShareBankrupt[] = new double[9],
        InsuranceIncrease[] = new double[9],
        BankDividends[] = new double[9], 
        ShareMin[] = new double[9],
        ShareAvg[] = new double[9], 
        ShareMax[] = new double[9],
        PyP[] = new double[9], 
        RyP[] = new double[9],
        OyP[] = new double[9], 
        ShareProfit[] = new double[9],
        InsuranceDisaster[] = new double[9], ObjectValue[], AllBankrupt[],
        AllDividends[];
        
        JTextField w1TextField, w10TextField, w2TextField,
        wUTextField[] = new JTextField[7],
        wBTextField[] = new JTextField[18],
        wTextField[] = new JTextField[18],
        wPTextField[] = new JTextField[9],
        wRTextField[] = new JTextField[9],
        wOTextField[] = new JTextField[9],
        wITextField[] = new JTextField[9],
        wIwTextField[] = new JTextField[9],
        wIdTextField[] = new JTextField[9];
        
        int width = 150, height = 28, Left, Iterations[] = new int[2], Resources,
			It, Ip, ShareLength, ArrayLength, BankLength, InsuranceLength,
			ParamWidth, ParamHeight, fc = 0;
   
       JPanel wPanel, w1Panel, w2Panel, w3Panel, w4Panel, w5Panel, w1IPanel,
			w6Panel;
        
	public StockTradeThread( StartupApplet applet ) {
            this.applet = applet;
            doGUIUpdate = new GUIUpdateNotifier( applet );
            iinit();
	}
	
	public void setDelay( int delay ){
            this.delay = delay;
	}
	
	public void requestStop() {
            requestStop = true;
	}
        
        public void createDatabase() {
            String sql = "CREATE TABLE IF NOT EXISTS `" + tablePredict + "` (\n" +
                        "  `num` int(11) NOT NULL,\n" +
                        "  `day` int(11) NOT NULL,\n" +
                        "  `stock` int(11) NOT NULL,\n" +
                        "  `strategy` varchar(9) COLLATE utf8_lithuanian_ci NOT NULL,\n" +
                        "  `price` double NOT NULL,\n" +
                        "  `predict` double NOT NULL\n" +
                        ") ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_lithuanian_ci;";
            writeSQL(sql);
             sql = "CREATE TABLE IF NOT EXISTS `" + tablePortfel + "` (\n" +
                    "  `num` int(11) NOT NULL,\n" +
                    "  `day` int(11) NOT NULL,\n" +
                    "  `strategy` varchar(9) COLLATE utf8_lithuanian_ci NOT NULL,\n" +
                    "  `stock` int(11) NOT NULL,\n" +
                    "  `stockCount` int(11) NOT NULL\n" +
                    ") ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_lithuanian_ci;";
            writeSQL(sql);
            sql = "CREATE TABLE IF NOT EXISTS `"+tableProfit+"` (\n" +
                  "  `num` int(11) NOT NULL,\n" +
                  "  `day` int(11) NOT NULL,\n" +
                  "  `strategy_predict` varchar(9) COLLATE utf8_lithuanian_ci NOT NULL,\n" +
                  "  `strategy_bs` varchar(30) COLLATE utf8_lithuanian_ci NOT NULL,\n" +
                  "  `profit` double NOT NULL\n" +
                  ") ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_lithuanian_ci;";
            writeSQL(sql);
        }
        
        public void writeSQL( String sql ) {
            try {
                    Class.forName("com.mysql.jdbc.Driver").newInstance();
                    Connection con = (Connection) DriverManager.getConnection(url, userName, password);
                    Statement stmt = (Statement) con.createStatement();
                    stmt.execute(sql);
                    stmt.close();
                    con.close();
                    //con.abort(null);
            } catch (Exception e) {
                    System.out.println(e.getMessage());
            }
        }
        
        public void writeExperimentPortfel( int num, int day, String strategy[], /*int stock,*/ int stockCount[][]  ) {
           String sql = "";
           for ( int j = 0; j < strategy.length; j++ ) {
            for ( int i = 0; i < stockCount[0].length; i++ ) {
                if ( sql.length() > 0 ) sql = sql + ",";
                sql = sql + "( " + num + "," + day + ", '" + strategy[j] + "', " + i + "," + stockCount[j][i] + " ) ";
            }
           }
            sql = "INSERT INTO `"+tablePortfel+"` VALUES " + sql; 
            writeSQL(sql);
        }
        
        public void writeExperimentPaklaida( int num, int day, String strategy[], double price[], double predict[][] ) {  
            String sql = "";
           for ( int j = 0; j < strategy.length; j++ ) {
            for ( int i = 0; i < price.length; i++ ) {
                if ( sql.length() > 0 ) sql = sql + ",";
                sql = sql + " ( " + num + "," + day + "," + i + ",'" + strategy[j] + "'," + price[i] + "," + predict[j][i] + " ) ";
            }
           }
            sql = "INSERT INTO `"+tablePredict+"` VALUES " + sql;
            writeSQL(sql);
        }
        
        public void writePelnai( int num, int day, String [] strategy, String[] strategy2, double [] value ) {
           String sql = "";
           for ( int i = 0; i < strategy.length; i++ ) {
               if ( sql.length() > 0 ) sql = sql + ",";
               sql = sql + " ( " + num + "," + day + ", '" + strategy[i] + "', '" + strategy2[i] + "', '" + value[i] + "' ) ";
           }
           sql =  "INSERT INTO `"+tableProfit+"` VALUES " + sql;
           writeSQL(sql);
        }
        	
    @Override
	public void run() {
		running = true;
		while ( !requestStop )	{
			while ( applet.readingData ){
				try { sleep( 100 ); System.out.println( "sleep 100" ); }
                                //try { sleep( 1 ); }
				catch ( Exception ex ) { ex.printStackTrace(); }
			}					
			doShopping( applet );
			
                        try { SwingUtilities.invokeAndWait( doGUIUpdate ); }
			catch ( Exception ex )	{
				ex.printStackTrace();
			}
			
                        try { sleep( delay ); }
			catch ( Exception ex )	{
				ex.printStackTrace();
			}
		}
		running = false;
	}
                
        public double [] DuomenysAtgal( double a [], int len ) {
            return a;
        }
        
        public double prediction( int iStrategy, double a[]  ) {
            //double price = 0;
            //System.out.println( "Massiv");
            //printr(a);
            
            double pred = 0;
            double niu = 0.01;
            
            if ( iStrategy == 0  ) {
                return a[a.length - 1];
            }
            if ( ( iStrategy > 0 && iStrategy < 10 ) ) {
                //System.out.println( "---------------Spejam kaina metodu AR" + iStrategy + "--------------------------" );
                AR_method ar;
                double[] coef_AR;
                if ( a.length >= ( iStrategy * 2 ) ) {
                    //System.out.println( "----------------duomenu seka ( uztenka duomenu )-------------------------" );
                    //applet.LoggerWrite("<b>----------------duomenu seka ( uztenka duomenu )-------------------------</b><br/>\r\n");
                    //printr( a );
                    ar = new AR_method(a, iStrategy);
                    coef_AR = ar.rezult();
                    for ( int x = 0; x < coef_AR.length; x++ ) {
                        pred += coef_AR[x] * a[a.length-x-1];
                    }
                }
                else {
                    double temp[] = new double[iStrategy * 2];
                    int s = a.length;
                    int beta = 1;
                    for ( int i = ( temp.length - 1 ); i >= 0; i-- ) {
                        s = s-1;
                        if ( s >= 0 ) {
                            temp[i] = a[s];                                                    
                        }
                        else {
                            temp[i] = a[0] * (1 -  beta * niu);
                            temp[i] = round(temp[i],2);
                            beta+=1;
                        }
                    }
                    //System.out.println( "----------------duomenu seka ( neuztenka duomenu ) -------------------------" );
                    //printr( temp );
                    ar = new AR_method(temp, iStrategy);
                    coef_AR = ar.rezult();
                    for ( int x = 0; x < coef_AR.length; x++ ) {
                        pred += coef_AR[x] * temp[temp.length-x-1];
                    }
                }
                //System.out.println("pred AR " + pred);
                //return pred;
            }
            if ( iStrategy >= 10 ) {
                MyLp lp = new MyLp();
                int pAR = iStrategy - 9;
                double[] coef_ABS;
                ///System.out.println( "---------------Spejam kaina metodu AR-ABS: " + pAR + "--------------------------" );
                if ( a.length >= ( pAR * 2 ) ) {
                    //System.out.println( "----------------duomenu seka-------------------------" );
                    //printr( a );
                    coef_ABS = lp.predict( a, pAR );
                    /*
                    for ( int y = 0; y < pAR; y++ ) {
                        pred += coef_ABS[y] * a[a.length-y-1];
                    }
                    */
                    for ( int x = 0; x < coef_ABS.length; x++ ) {
                        pred += coef_ABS[x] * a[a.length-x-1];
                    }
                }
                else {
                    double temp[] = new double[(pAR * 2)];
                    int s = a.length;
                    int beta = 1;
                    for ( int i = ( temp.length - 1 ); i >= 0; i-- ) {
                        s = s-1;                                                
                        if ( s >= 0 ) {
                            temp[i] = a[s];                                                  
                        }
                        else {
                            temp[i] = a[0] * (1 -  (beta * niu));
                            temp[i] = round( temp[i], 2 );
                            beta++;
                        }
                    }
                    //System.out.println( "----------------duomenu seka-------------------------" );
                    //printr( temp );
                    coef_ABS = lp.predict( temp, pAR );
                    for ( int x = 0; x < coef_ABS.length; x++ ) {
                        pred += coef_ABS[x] * temp[temp.length-x-1];
                    }
                }
                ///System.out.println("pred ABS " + pred);
                //return pred;
                /*
                System.out.println( "AR-ABS coef ------------------------" );
                for( int i = 0; i < coef_ABS.length; i++ )
                    System.out.println( coef_ABS[i] );
                System.out.println( "AR-ABS coef ------------------------" );
                    * 
                    */
                }
            //System.out.println( "prediciotn = " + pred);
            if ( pred  <= 0.1 ) return 0.1d;
            else return pred;
            //return pred;
            ///System.out.println( "---------------Spejam kaina metodu WIENERIO --------------------------" );
            ///System.out.println("pred Wiener " + pred);
            //return price;
        }
        
        public boolean inInterval( int iteration, int customerInvestInterval ) {
            //90
            if ( ( ( Months( customerInvestInterval )  * applet.dayinmonth ) < iteration ) &&
                    //180
                    ( ( 2 *  Months( customerInvestInterval ) * applet.dayinmonth ) > iteration ) ) return true;
            return false;
        }
        
        public boolean beforeInteval( int iteration, int customerInvestInterval ) {
            //90
            if ( ( Months( customerInvestInterval )  * applet.dayinmonth ) >= iteration ) return true;
            return false;
        }
        
        //( ( 2 *  Months( customer.InvestmentInterval )  * applet.dayinmonth ) < iIterN )
        
        public boolean afterInteval( int iteration, int customerInvestInterval ) {
            //180
            if ( ( 2 *  Months( customerInvestInterval ) * applet.dayinmonth ) <= iteration ) return true;
            return false;
        }
	        	
	public boolean doShopping(StartupApplet applet ) {
                int iIterN = applet.stocksPrices[0].getIterNr() + 1;
                //System.out.println( "Iteration nachalo zdes: " + iIterN );
                if ( iIterN >= applet.termin ) return false;
                //System.out.println( "Iteration prodolzhenie zdes: " + iIterN );
                applet.LoggerWrite("<br/><br/><b> Diena: " + iIterN + "</b><br/>" );
                double price[] = new double[this.applet.MAX_STOCK_COUNT];
                double Beta[] = new double[this.applet.MAX_STOCK_COUNT];
                double p[] = new double[this.applet.MAX_STOCK_COUNT];
                double tau[] = new double[this.applet.MAX_STOCK_COUNT];
                
                int nt[] = new int[this.applet.MAX_STOCK_COUNT];
                int nb = 0;
                int ns = 0;

                int ns1 = 0;
                int ns2 = 0;
                int ns3 = 0;
                double ps1[] = new double[this.applet.MAX_STOCK_COUNT];
                double ps2[] = new double[this.applet.MAX_STOCK_COUNT];
                double ps3[] = new double[this.applet.MAX_STOCK_COUNT]; 

                double zs1[] = new double[this.applet.MAX_STOCK_COUNT];
                double zs2[] = new double[this.applet.MAX_STOCK_COUNT];
                double zs3[] = new double[this.applet.MAX_STOCK_COUNT];
                double zb = 0;
                double zs = 0;
                double minbuy[] = new double[this.applet.MAX_STOCK_COUNT];
                double maxsell[] = new double[this.applet.MAX_STOCK_COUNT];
                boolean buymade[] = new boolean[this.applet.MAX_STOCK_COUNT];
                boolean sellmade[] = new boolean[this.applet.MAX_STOCK_COUNT];
                
                LinkedHashMap JPliusLevel = null;
                LinkedHashMap JMinusLevel = null;
                
                for( int priceCount = 0; priceCount < this.applet.MAX_STOCK_COUNT; priceCount++ ) {
                    price[priceCount]   = applet.stocksPrices[priceCount].get(iIterN-1);
                    maxsell[priceCount] = applet.stocksPrices[priceCount].get(iIterN-1);
                    minbuy[priceCount]  = applet.stocksPrices[priceCount].get(iIterN-1);
                    buymade[priceCount] = sellmade[priceCount] = false;
                }
                
                int[] maxIndexP = new int[applet.firmCount];
                double[] maxP = new double[applet.firmCount];

                for ( int j = 0; j < applet.firmCount; j++ ) {
                    SRGMCustomer customer = (SRGMCustomer)applet.customers.get(j);
                    applet.LoggerWrite("<b>Customer:</b>  "  + j + "<br/>" );

                    maxIndexP[j] = -1;
                    maxP[j] = 0;
                    String buymadeHistory  = new String( "" );
                    String sellmadeHistory = new String( "" );
                    for (int c = 0; c < this.applet.MAX_STOCK_COUNT; c++ ) {
                        //applet.LoggerWrite("<b><br/>Dirbam su akcija :</b>  "  + c + "<br/>" );
                        //applet.LoggerWrite("<b><br/>Pradinis kiekis :</b>  "  + numberFont( ((Integer)customer.iN.get(c)).intValue() ) + "<br/>" );
                        customer.currentPrice.set(c, price[c]);                       
                        if ( customer.iStrategy == 0 ) customer.dZpred.set( c, price[c] );
                        else customer.dZpred.set(c, prediction( customer.iStrategy, applet.stocksPrices[c].toArrayRibojimas( this.applet.ribojimas )  ) );
                        //applet.LoggerWrite("<b>Vakar dienos kaina :</b> "  + numberFont( customer.currentPrice.get(c) ) + "<br/>" );
                        //applet.LoggerWrite("<b>Prediction :</b> "  + numberFont( customer.dZpred.get(c) ) + "<br/>" );
                        //System.out.println( "pred: " + customer.dZpred.get(c) + " kaina: " + price[c] );
                        //System.out.println();
                        Beta[c] = ( customer.dZpred.get(c) - price[c] ) / price[c];
                        if ( customer.iStrategy == 0 ) Beta[c] = 0;
                        
                        //applet.LoggerWrite("<b>Beta[" + c + "]:</b> "  + numberFont( Beta[c] ) + "<br/>" );
                        p[c] = Beta[c] + ( ( applet.dividend[c] / 365 ) / price[c] ) - ( applet.yieldOfCd / 365 ) ;
                        //applet.LoggerWrite("<b>p[" + c + "]:</b> "  + numberFont( p[c] ) + "<br/>" );
                        //System.out.println( " p[c] " + c + " " + p[c] );
                        if ( p[c] != 0 )  {
                            nt[c] = ( int )Math.round( Math.abs( (  applet.transactionCostValue / ( price[c]  * p[c] ) ) ) );
                            nt[c] += 1;
                        }
                        else nt[c] = 10000;
                        
                        tau[c] = applet.transactionCostValue / ( price[c] * nt[c] ) ;
                        //System.out.println( "p [" + c + "]="  + p[c]  );
                        //System.out.println( "tau [" + c + "]="  + tau[c]  );
                        
                        if ( p[c] > tau[c] ) {
                             //System.out.println(  p[c] + " > " + tau[c] );
                            if ( maxP[j] < p[c] ){
                                //System.out.println(  maxP[j] + " < " + p[c] );
                                  maxIndexP[j] = c;
                                  maxP[j] = p[c];
                             }
                        }
                        
                        //applet.LoggerWrite("<b>tau[" + c + "]" + "]:</b> "  + numberFont( tau[c] ) + "<br/>");
                        //applet.LoggerWrite("<b>nt[" + c + "]:</b> "  + numberFont( nt[c] ) + "<br/>" );   
                    }
                                        
                    if ( customer.riskStrategy == 1 || customer.riskStrategy == 2 || 
                                ( customer.riskStrategy == 7 && ( ( Months( customer.InvestmentInterval )  * applet.dayinmonth ) > iIterN ) ) || 
                                ( customer.riskStrategy == 8 && ( ( Months( customer.InvestmentInterval )  * applet.dayinmonth ) > iIterN ) )
                            ) { //sell all losers buy most profitable ( 1 ) and sell all ( 2 ) buy best
                        for (int c = 0; c < this.applet.MAX_STOCK_COUNT; c++ ) {
                            //jei pelningiausia praleidziam
                            if ( c == maxIndexP[j] ) continue;
                            
                            if ( customer.riskStrategy == 1 && ( Math.abs( p[c] ) < Math.abs( tau[c]) ) ) continue;// jei antras parduodam viska isskyrus best
                            if ( customer.riskStrategy == 7 && ( Math.abs( p[c] ) < Math.abs( tau[c]) ) ) continue;
                            if ( customer.riskStrategy == 1 && ( p[c] >= tau[c] ) ) continue;                        // jei pirmas paduodam tik nuostolingas ir kurias apsimoka parduot    
                            if ( customer.riskStrategy == 7 && ( p[c] >= tau[c] ) ) continue; 
                            
                            if (  ((Integer)customer.iN.get(c)).intValue() > 0 ) {
                                applet.LoggerWrite( j + " makes sell day " + iIterN );
                                sellmadeHistory = sellmadeHistory + " stock " + c + " : " + ((Integer)customer.iN.get(c)).intValue() + " ; ";
                                /*customer.C0 += price[c] * ((Integer)customer.iN.get(c)).intValue();
                                customer.iN.set(c, 0);*/
                                customer.SellAllStocksByIndex(c, price[c]);
                                
                                applet.LoggerWrite(j + " sell action - stock count: "  + ((Integer)customer.iN.get(c)).intValue() + " of " + c + " stock"+ "<br/>");
                                zs = customer.dZpred.get(c) / ( 1 + ( applet.dividend[c] / 365 ) - ( applet.yieldOfCd / 365 ) - tau[c] );
                                if ( maxsell[c] > zs ) maxsell[c] = zs;
                                sellmade[c] = true;
                            }
                        }
                    }
                    else if ( customer.riskStrategy == 4 || customer.riskStrategy == 5  ) {
                        if ( customer.longInvest && ( ( 2 *  Months( customer.InvestmentInterval )  * applet.dayinmonth ) < iIterN ) ) {
                         for (int c = 0; c < this.applet.MAX_STOCK_COUNT; c++ ) {                
                            if (  ((Integer)customer.iN.get(c)).intValue() > 0 ) {
                                //applet.LoggerWrite( j + " makes sell day " + iIterN );
                                sellmadeHistory = sellmadeHistory + " stock " + c + " : " + ((Integer)customer.iN.get(c)).intValue() + " ; ";
                                customer.SellAllStocksByIndex(c, price[c]);
                                //applet.LoggerWrite(j + " sell action - stock count: "  + ((Integer)customer.iN.get(c)).intValue() + " of " + c + " stock"+ "<br/>");
                                zs = customer.dZpred.get(c) / ( 1 + ( applet.dividend[c] / 365 ) - ( applet.yieldOfCd / 365 ) - tau[c] );
                                if ( maxsell[c] > zs ) maxsell[c] = zs;
                                sellmade[c] = true;
                            }
                          }
                        }
                    }
                    
                   /* else if ( customer.riskStrategy == 5  ) {
                        if ( customer.longInvest && ( ( 2 *  Months( customer.InvestmentInterval )  * applet.dayinmonth ) < iIterN ) ) {
                         for (int c = 0; c < this.applet.MAX_STOCK_COUNT; c++ ) {                
                            if (  ((Integer)customer.iN.get(c)).intValue() > 0 ) {
                                //applet.LoggerWrite( j + " makes sell day " + iIterN );
                                sellmadeHistory = sellmadeHistory + " stock " + c + " : " + ((Integer)customer.iN.get(c)).intValue() + " ; ";
                                customer.SellAllStocksByIndex( c, price[c] );
                                
                                //applet.LoggerWrite(j + " sell action - stock count: "  + ((Integer)customer.iN.get(c)).intValue() + " of " + c + " stock"+ "<br/>");
                                zs = customer.dZpred.get(c) / ( 1 + ( applet.dividend[c] / 365 ) - ( applet.yieldOfCd / 365 ) - tau[c] );
                                if ( maxsell[c] > zs ) maxsell[c] = zs;
                                sellmade[c] = true;
                            }
                        }
                        }
                    }*/
                    
                    else if ( customer.riskStrategy == 0 || ( ( customer.riskStrategy == 6 ) && ( ( Months( customer.InvestmentInterval )  * applet.dayinmonth ) > iIterN ) ) ) { // sell all loser by profitability levels
                        //sell loss buy profitable
                        //System.out.println("strategy 6 interval < 1");
                        for (int c = 0; c < this.applet.MAX_STOCK_COUNT; c++ ) {
                                // praleidziam pelningiausia, nors ir taip ja butu praleide veliau
                                if ( c == maxIndexP[j] ) continue;
                                //praleidziam kur reikia laukti
                                if ( Math.abs( p[c] ) < Math.abs( tau[c]) ) continue;
                                //praledziam pelningas
                                if ( p[c] >= tau[c] ) continue;
                                // skaiciuojam lygius!!!
                                ns3 = ((Integer)customer.iN.get(c)).intValue();
                                if ( ns3 <= 0 ) continue;
                                
                                ns2 = (int)(  ns3 / 2 );
                                ns1 = 1;

                                //if ( ns3[c] < ns2[c] ) ns3[c] = ns2[c];
                                if ( ns2 < ns1 ) ns2 = ns;
                                //if ( ns3[c] < ns2[c] ) ns3[c] = ns2[c];

                                //applet.LoggerWrite(" <table width=\"200px\" border=\"1\"> <tr> <td> ns1 </td> <td> ns2 </td> <td> ns3 </td> </tr> <tr> <td> " + ns1 + "</td><td> " + ns2 + "</td><td>" + ns3 + "</td></tr></table>" );
                                
                                ps1[c] = -tau[c] * 1;
                                ps2[c] = -tau[c] * 2;
                                ps3[c] = -tau[c] * 3;
                        
                                //applet.LoggerWrite(" <table width=\"200px\" border=\"1\"> <tr> <td> ps1 </td> <td> ps2 </td> <td> ps3 </td> </tr> <tr> <td> " + ps1[c] + "</td><td> " + ps2[c] + "</td><td>" + ps3[c] + "</td></tr></table>" );
                        
                                zs1[c] = ( customer.dZpred.get(c) ) / ( 1 - ( applet.dividend[c] / 365 ) + ( applet.yieldOfCd / 365 ) + ps1[c] );
                                zs2[c] = ( customer.dZpred.get(c) ) / ( 1 - ( applet.dividend[c] / 365 ) + ( applet.yieldOfCd / 365 ) + ps2[c] );
                                zs3[c] = ( customer.dZpred.get(c) ) / ( 1 - ( applet.dividend[c] / 365 ) + ( applet.yieldOfCd / 365 ) + ps3[c] );
                        
                                applet.LoggerWrite(" <table width=\"200px\" border=\"1\"> <tr> <td> zs1 </td> <td> zs2 </td> <td> zs3 </td> </tr> <tr> <td> " + zs1[c] + "</td><td> " + zs2[c] + "</td><td>" + zs3[c] + "</td></tr></table>" );
                                
                                if (  ( p[c] <= ps3[c] ) &&  ( ((Integer)customer.iN.get(c)).intValue() > 0 ) ) {
                                        applet.LoggerWrite(" p[c] <= ps3[c] && akcijuKiekis[c] > 0 "+ "<br/>");
                                        ns = ns3;
                                        zs = zs3[c];
                                }
                                else if ( p[c] <= ps2[c] && ( ((Integer)customer.iN.get(c)).intValue() > 0 ) ) {
                                        applet.LoggerWrite(" p[c] <= ps2[c] && akcijuKiekis[c] > 0 " + "<br/>");
                                        ns = ns2;
                                        zs = zs2[c];
                                }
                                else if ( p[c] <= ps1[c] && ( ((Integer)customer.iN.get(c)).intValue() > 0 ) ) {
                                        applet.LoggerWrite(" p[c] <= ps1[c] && akcijuKiekis[c] > 0 "+ "<br/>");
                                        ns = 1;
                                        zs = zs1[c];
                                }
                                else {
                                    applet.LoggerWrite("<b> p[c] sell else ( no sell ) </b>"+ "<br/>");
                                    ns = 0;
                                }
                                
                                if ( ns > 0 && ns <= ((Integer)customer.iN.get(c)).intValue() ) {
                                    //applet.LoggerWrite( j + " makes sell day " + iIterN );
                                    //applet.LoggerWrite(j + " sell action - stock count: "  + ns + " of " + c + " stock" + "<br/>");
                                    sellmadeHistory = sellmadeHistory + " stock " + c + " : " + ns + " ; ";
                                    customer.SellStocks( c, ns, price[c] );
                                    
                                    if ( maxsell[c] > zs ) maxsell[c] = zs;
                                    sellmade[c] = true;
                                }
                                else {
                                    applet.LoggerWrite(j + " MISTAKE SELL ns > stock count or ns < 0 ; ns = " + ns + "  >  stock count = "  + ((Integer)customer.iN.get(c)).intValue() );
                                }
                          }
                    }
                    
                    else if ( ( customer.riskStrategy == 6 || customer.riskStrategy == 7 || customer.riskStrategy == 8 || customer.riskStrategy == 9 ) && 
                            ( ( 2 *  Months( customer.InvestmentInterval )  * applet.dayinmonth ) < iIterN ) ){ 
                        //System.out.println( "Sell strategy x2 interval 6 7 8 9" );
                        for (int c = 0; c < this.applet.MAX_STOCK_COUNT; c++ ) {                
                           if (  ((Integer)customer.iN.get(c)).intValue() > 0 ) {
                               //applet.LoggerWrite( j + " makes sell day " + iIterN );
                               sellmadeHistory = sellmadeHistory + " stock " + c + " : " + ((Integer)customer.iN.get(c)).intValue() + " ; ";
                               customer.SellAllStocksByIndex( c, price[c] );
                               //applet.LoggerWrite(j + " sell action - stock count: "  + ((Integer)customer.iN.get(c)).intValue() + " of " + c + " stock"+ "<br/>");
                               zs = customer.dZpred.get(c) / ( 1 + ( applet.dividend[c] / 365 ) - ( applet.yieldOfCd / 365 ) - tau[c] );
                               if ( maxsell[c] > zs ) maxsell[c] = zs;
                               sellmade[c] = true;
                           }
                       }
                    }
                    
                    else if ( customer.riskStrategy == 3 || ( ( customer.riskStrategy == 9 ) && ( ( Months( customer.InvestmentInterval )  * applet.dayinmonth ) > iIterN ) ) ) {
                        //System.out.println( "Strategy " + customer.riskStrategy );
                        JMinusLevel = new StockContainer();
                        JPliusLevel = new StockContainer();
                        int plius = 0;
                        int minus = 0;
                        for (int c = 0; c < this.applet.MAX_STOCK_COUNT; c++ ) {
                            if ( p[c] > tau[c] ) {
                                JPliusLevel.put( new Integer(c) , new Double(p[c]) );
                                plius++;
                            }
                            else if ( p[c] < tau[c] ) {
                                JMinusLevel.put( new Integer(c) , new Double(p[c]));
                                minus++;
                            }
                            else {
                                //System.out.println( "Surusivimas nepavyko " + p[c] );  
                            }
                        }
                        JMinusLevel = sortHashMapByValuesD(JMinusLevel);
                        JPliusLevel = sortHashMapByValuesD(JPliusLevel);
                         
                        int minCount = JMinusLevel.size();
                        int level = 0;
                        Iterator entries = JMinusLevel.entrySet().iterator();
                        while (entries.hasNext()) {
                            Map.Entry entry = (Map.Entry) entries.next();
                            Integer key = (Integer)entry.getKey();
                            //Double value = (Double)entry.getValue();
                            //System.out.println( " Minus Key = " + key + ", Value = " + value);
                            ns = (int)((((Integer)customer.iN.get(key)).intValue() * 2 * ( minCount - level) ) / ( minCount * ( minCount + 1 ) ));
                            if ( ns > 0 && ns <= ((Integer)customer.iN.get(key)).intValue() ) {
                                    //applet.LoggerWrite( j + " makes sell day " + iIterN );
                                    //applet.LoggerWrite(j + " sell action - stock count: "  + ns + " of " + key + " stock" + "<br/>");
                                    sellmadeHistory = sellmadeHistory + " stock " + key + " : " + ns + " ; ";                                    
                                    customer.SellStocks( key, ns, price[key] );
                                    if ( maxsell[key] > zs ) maxsell[key] = zs;
                                    sellmade[key] = true;
                                }
                                else {
                                    //applet.LoggerWrite(j + " MISTAKE SELL ns > stock count or ns < 0 ; ns = " + ns + "  >  stock count = "  + ((Integer)customer.iN.get(key)).intValue() );
                                }
                            level++;
                        }
                        
                        entries = JPliusLevel.entrySet().iterator();
                        level = 1;
                        int maxCount = JPliusLevel.size();
                        while (entries.hasNext()) {
                            Map.Entry entry = (Map.Entry) entries.next();
                            Integer key = (Integer)entry.getKey();
                            //Double value = (Double)entry.getValue();
                            //System.out.println(" Plius Key = " + key + ", Value = " + value);
                            nb = (int)(( customer.getAvFunds() * 2 * level ) / ( ( maxCount * ( maxCount + 1 ) ) * price[key] ) );
                            //System.out.println( "nb  =  " + nb + " =  " + "(int)(( " + customer.getAvFunds() + " * 2 * " + level + " ) / ( " + maxCount + " * ( + " + maxCount + " + 1 ) * " + price[key] + "))" );
                            zb = customer.dZpred.get(key) / ( 1 + ( applet.dividend[key] / 365 ) - ( applet.yieldOfCd / 365 ) + tau[key] );
                            //System.out.println( "zb  =  " + zb );
                            //applet.LoggerWrite(" p[maxIndexP] buy, nb = " + nb + " stock " + " zb = " + zb + "<br/>");
                            if ( nb < 0 ) nb = 0;
                            if ( nb > 0 && ( nb <=  ( customer.getAvFunds() / price[key] ) ) ) {
                                buymadeHistory = buymadeHistory + " stock " + key + " : " + nb + " ; ";
                                customer.BuyStocks(key, nb, price[key]);
                                
                                //applet.LoggerWrite( j + " stock count " + nb + "<br/>");
                                if ( minbuy[key] < zb ) minbuy[key] = zb;
                                buymade[key] = true;
                            }
                            else if ( nb > 0 && nb >=  ( customer.getAvFunds() / price[key] )) {
                                //applet.LoggerWrite(j + " makes no action day " + iIterN + " insolvement "+ "<br/>");
                            }
                            else {
                                //applet.LoggerWrite(j + " makes no action day " + iIterN);
                            }
                            level++;
                        }
                    }
                    
                    if ( sellmadeHistory.length() > 5 ) applet.operationLastSell[j].setText(sellmadeHistory);

                    //pelningiausia
                    if ( customer.riskStrategy == 0 || customer.riskStrategy == 1 || customer.riskStrategy == 2  ||
                            ( ( customer.riskStrategy == 6 ) && ( ( Months( customer.InvestmentInterval )  * applet.dayinmonth ) > iIterN ) ) ||
                            ( ( customer.riskStrategy == 7 ) && ( ( Months( customer.InvestmentInterval )  * applet.dayinmonth ) > iIterN ) ) ||
                            ( ( customer.riskStrategy == 8 ) && ( ( Months( customer.InvestmentInterval )  * applet.dayinmonth ) > iIterN ) )
                            ) {
                        if ( maxIndexP[j] >= 0 ) {
                            nb =  ( int )( customer.getAvFunds() / price[maxIndexP[j]] );
                            zb = customer.dZpred.get(maxIndexP[j]) / ( 1 + ( applet.dividend[maxIndexP[j]] / 365 ) - ( applet.yieldOfCd / 365 ) + tau[maxIndexP[j]] );
                            //applet.LoggerWrite(" p[maxIndexP] buy, nb = " + nb + " stock " + " zb = " + zb + "<br/>");
                            if ( nb < 0 ) nb = 0;
                            if ( nb > 0 && ( nb <=  ( customer.getAvFunds() / price[maxIndexP[j]] ) ) ) {
                                buymadeHistory = buymadeHistory + " stock " + maxIndexP[j] + " : " + nb + " ; ";
                                customer.BuyStocks(maxIndexP[j], nb, price[maxIndexP[j]]);
                                //applet.LoggerWrite( j + " stock count " + nb + "<br/>");
                                if ( minbuy[maxIndexP[j]] < zb ) minbuy[maxIndexP[j]] = zb;
                                buymade[maxIndexP[j]] = true;
                            }
                            else if ( nb > 0 && nb >=  ( customer.getAvFunds() / price[maxIndexP[j]] )) {
                                //applet.LoggerWrite(j + " makes no action day " + iIterN + " insolvement "+ "<br/>");
                            }
                            else {
                                //applet.LoggerWrite(j + " makes no action day " + iIterN);
                            }
                        }
                        else {
                            nb = 0;
                            //applet.LoggerWrite("<b> " + maxIndexP[j] + " ( no buy )  </b>"+ "<br/>");
                        }
                    }
                    if ( customer.riskStrategy == 4 ) {
                        //System.out.println(  "Days  in strategy  4 " + Months( customer.InvestmentInterval ) * applet.dayinmonth );
                        if ( /* ( ( Months( customer.InvestmentInterval ) * applet.dayinmonth ) < iIterN )*/ 
                            inInterval(iIterN, customer.InvestmentInterval ) && !customer.longInvest ) {
                            //System.out.println( "interacija vnutri strategii 4" + iIterN );
                            WriteArray( customer, p );
                            WriteOneArray( customer, p );
                            try {
                                    int InType = customer.InvestmentType;
                                    Method = applet.INVESTMENT_METODS[customer.InvestmentMetod];
                                    double Resours = customer.getAvFunds();
                                    resultGMJ = new double[applet.stocksPrices.length];
                                    wCounter = new Counter_Sharp( Iterations, InType, Resours, Method,
                                                    applet.stocksPrices, resultGMJ );
                                    wCounter.setPriority(Counter_Sharp.MIN_PRIORITY);
                                    wItVector.clear();
                                    wFVector.clear();
                                    wCounter.Data(wItVector, wFVector);
                                    wCounter.start();
                            } catch (Exception ex) {
                                    System.out.println( "Error: Can't create thread!" );
                            }
                            while (wCounter.isAlive() ) { 
                                try {
                                    this.sleep(1000);
                                } catch (InterruptedException ex) {
                                }
                            }
                            double [] tempSums = new double [resultGMJ.length];
                            double funds = customer.getAvFunds();
                            for ( int i = 0 ; i < resultGMJ.length ; i++ ) {
                                //System.out.println( " koef " + i + " = " + resultGMJ[i] );
                                tempSums[i] = resultGMJ[i] * funds;
                                //System.out.println( " sum " + i + " = " + tempSums[i] );
                            }
                            //System.out.println( "SUM MAX COUNTER = " + wCounter.Counter_sum_max );
                            //System.out.println( "AVALIABLE FUNDS = " + funds );

                            for ( int i = 0 ; i < resultGMJ.length ; i++ ) { 
                                nb =  ( int )( tempSums[i] / price[i] );
                                zb = customer.dZpred.get(i) / ( 1 + ( applet.dividend[i] / 365 ) - ( applet.yieldOfCd / 365 ) + tau[i] );
                                //applet.LoggerWrite(" p[maxIndexP] buy, nb = " + nb + " stock " + " zb = " + zb + "<br/>");
                                if ( nb < 0 ) nb = 0;

                                if ( nb > 0 && ( nb <=  ( tempSums[i] / price[i] ) ) ) {
                                    buymadeHistory = buymadeHistory + " stock " + i + " : " + nb + " ; ";
                                    //applet.LoggerWrite( j + " makes buy id day " + iIterN + "<br/>");
                                    customer.BuyStocks(i, nb, price[i]);
                                    //applet.LoggerWrite( j + " stock count " + nb + "<br/>");
                                    if ( minbuy[i] < zb ) minbuy[i] = zb;
                                    buymade[i] = true;
                                    customer.longInvest = true;
                                }
                                else if ( nb > 0 && nb >=  ( customer.getAvFunds() / price[i] )) {
                                    //applet.LoggerWrite(j + " makes no action day " + iIterN + " insolvement "+ "<br/>");
                                }
                                else {
                                    //applet.LoggerWrite(j + " makes no action day " + iIterN);
                                }
                        
                            }
                        
                        }
                        else {
                            //System.out.println( "No action" );
                        }
                        
                    }
                    
                    //portfel
                    if ( customer.riskStrategy == 5 ) {
                        //System.out.println(  "Days " + Months( customer.InvestmentInterval ) * applet.dayinmonth );
                        if ( ( Months( customer.InvestmentInterval ) * applet.dayinmonth < iIterN ) && !customer.longInvest ) {
                        //if ( true ) {
                        WriteArray( customer, p );
                        WriteOneArray( customer, p );
                        try {
                                int InType = customer.InvestmentType;
                                Method = applet.INVESTMENT_METODS[customer.InvestmentMetod];
                                double Resours = customer.getAvFunds();
                                resultGMJ = new double[applet.stocksPrices.length];
                                wCounterPortfel = new Counter_Portfel( Iterations, InType, Resours, Method,
                                                applet.stocksPrices, resultGMJ, applet.bankruptProbability, customer.dZpred.toArray() );
                                wCounterPortfel.setPriority(Counter_Sharp.MIN_PRIORITY);
                                wItVector.clear();
                                wFVector.clear();
                                wCounterPortfel.Data(wItVector, wFVector);
                                wCounterPortfel.start();
                        } catch (Exception ex) {
                                System.out.println( "Error: Can't create thread!" );
                        }
                        while (wCounterPortfel.isAlive() ) { 
                            try {
                                this.sleep(1000);
                            } catch (InterruptedException ex) {
                            }
                        }
                        double [] tempSums = new double [resultGMJ.length];
                        double funds = customer.getAvFunds();
                        for ( int i = 0 ; i < resultGMJ.length ; i++ ) {
                            //System.out.println( " koef " + i + " = " + resultGMJ[i] );
                            tempSums[i] = resultGMJ[i] * funds;
                            //System.out.println( " sum " + i + " = " + tempSums[i] );
                        }
                        //System.out.println( "SUM MAX COUNTER = " + wCounterPortfel.Counter_sum_max );
                        //System.out.println( "AVALIABLE FUNDS = " + funds );

                        for ( int i = 0 ; i < resultGMJ.length ; i++ ) { 
                            nb =  ( int )( tempSums[i] / price[i] );
                            zb = customer.dZpred.get(i) / ( 1 + ( applet.dividend[i] / 365 ) - ( applet.yieldOfCd / 365 ) + tau[i] );
                            //applet.LoggerWrite(" p[maxIndexP] buy, nb = " + nb + " stock " + " zb = " + zb + "<br/>");
                            if ( nb < 0 ) nb = 0;

                            if ( nb > 0 && ( nb <=  ( tempSums[i] / price[i] ) ) ) {
                                buymadeHistory = buymadeHistory + " stock " + i + " : " + nb + " ; ";
                                //applet.LoggerWrite( j + " makes buy id day " + iIterN + "<br/>");
                                //cia perkam uz visus pinigus, todel pirmas netinka
                                customer.BuyStocks(i, nb, price[i]);
                                
                                //applet.LoggerWrite( j + " stock count " + nb + "<br/>");
                                if ( minbuy[i] < zb ) minbuy[i] = zb;
                                buymade[i] = true;
                                customer.longInvest = true;
                            }
                            else if ( nb > 0 && nb >=  ( customer.getAvFunds() / price[i] )) {
                                applet.LoggerWrite(j + " makes no action day " + iIterN + " insolvement "+ "<br/>");
                            }
                            else {
                                applet.LoggerWrite(j + " makes no action day " + iIterN);
                            }
                        }
                        }
                        else {
                           // System.out.println( "No action" );
                        }
                        
                    }

                    //System.out.println( "Perkam" );
                     if ( buymadeHistory.length() > 5 ) applet.operationLastBuy[j].setText(buymadeHistory);
                    
                    applet.LoggerWrite( "Customer turi pinigu suma " + customer.C0 + " ir gauna palikanas " + ( customer.C0 * ( applet.bankInterest / 365 ) ) + "<br/>");
                    if ( customer.C0 > 0 ) customer.C0 = customer.C0 * ( 1 + ( applet.bankInterest / 365 ) );
                    
                    customer.PayCredit();
                    
                    applet.bank1.Insolvement(customer.PayInsolvement());
                    
                    //applet.LoggerWrite(" vartotojas moka palukanas " + ( customer.B * ( applet.bankInterest / 365 ) ) + " ir jo kredito suma pasidaro " + ( customer.B * ( 1 + ( applet.bankInterest / 365 ) )) + "<br/>");
                    applet.bank1.bankProfit += customer.B * ( applet.bankInterest / 365 );
                    customer.B = customer.B * ( 1 + ( applet.bankInterest / 365 ) );
                    double vartotojoVisuAkcijuVerte = 0;
                    for( int ccc = 0; ccc < this.applet.MAX_STOCK_COUNT; ccc++ ) {
                        applet.LoggerWrite(" vartotojo " + j + " akcijos " + ccc + " akciju verte (kiekis = " + numberFont( ((Integer)customer.iN.get(ccc)).intValue() ) + 
                                " * ( akcijos kaina = " + numberFont( customer.currentPrice.get(ccc) ) + " = " + numberFont( ((Integer)customer.iN.get(ccc)).intValue() * customer.currentPrice.get(ccc) ) + "<br/>" );
                        vartotojoVisuAkcijuVerte += ((Integer)customer.iN.get(ccc)).intValue() * customer.currentPrice.get(ccc);
                    }
                    customer.dProfit = customer.C0 - customer.C0_ - customer.B + vartotojoVisuAkcijuVerte;
                    applet.LoggerWrite("<b> Plenas vartotojo " + j + "</b>" + " dabartine suma (" + customer.C0 + ") - pradine suma (" + customer.C0_ + ") - skola bankui (" + customer.B + ") + "
                             + "visu  vartotojoVisuAkcijuVerte (" + vartotojoVisuAkcijuVerte + ") = " + numberFont( customer.dProfit ) + "<br/>"  );
                    
                    applet.customers.set(j, customer);
               }
               nextDayPrice(iIterN, buymade, sellmade, price, minbuy, maxsell);
               return true;           
        }
                
        public LinkedHashMap sortHashMapByValuesD(HashMap passedMap) {
            List mapKeys = new ArrayList(passedMap.keySet());
            List mapValues = new ArrayList(passedMap.values());
            Collections.sort(mapValues);
            Collections.sort(mapKeys);

            LinkedHashMap sortedMap = new LinkedHashMap();

            Iterator valueIt = mapValues.iterator();
            while (valueIt.hasNext()) {
                Object val = valueIt.next();
                Iterator keyIt = mapKeys.iterator();

                while (keyIt.hasNext()) {
                    Object key = keyIt.next();
                    String comp1 = passedMap.get(key).toString();
                    String comp2 = val.toString();

                    if (comp1.equals(comp2)){
                        passedMap.remove(key);
                        mapKeys.remove(key);
                        sortedMap.put((Integer)key, (Double)val);
                        break;
                    }

                }

            }
            return sortedMap;
        }
         
        public void nextDayPrice( int iIterN, boolean [] buymade, boolean [] sellmade, double[] price, double [] minbuy, double [] maxsell ) {
                double Znext,dEps;
                double ro = 0.4;
                double teta;
                if ( applet.realDataCounter >= applet.termin ) this.stop();
                for( int ccc = 0; ccc < this.applet.MAX_STOCK_COUNT; ccc++ ) {
                        Znext = dEps = 0;
                        if ( applet.realData[ccc] ) {
                            //System.out.println( "real data count " + applet.realDataCounter + " termin " + applet.termin);
                            Znext = applet.stockRealData[ccc][applet.realDataCounter];
                        }
                        else {
                                Random rNorm;
                                if ( applet.RandomType.equals( new String ("seed") ) ) rNorm = new Random( (new Date()).getTime() );
                                else rNorm = new Random( applet.ConstRandTime );
                                //System.out.println( "----------------------------teta-------------------------------" );
                                if ( applet.stockEps[ccc].isEmpty() ) teta = 0;
                                else teta = Average( applet.stockEps[ccc].toArray() );

                                /*System.out.println( "----------------------------Eps vidurkis teta:-------------------------------" );
                                System.out.println( teta );*/
                                double tempintetia = applet.inertia[ccc];
                                if ( iIterN < 22 ) tempintetia = 1;
                                while ( ( Znext - ( 3 * applet.transactionCostValue ) ) < ro  ) {
                                    //System.out.println( "----------------------------test while-------------------------------" );
                                    dEps = applet.volatility[ccc] * rNorm.nextGaussian();
                                    dEps = dEps - teta;
                                    if ( buymade[ccc] && sellmade[ccc] ) {
                                        //System.out.println( "------------------------------------kaina rytoj po pirkimo ir pardavimo  Z(t)--------------------------------------------------");
                                        Znext = ( ( 1 - tempintetia ) * ( ( maxsell[ccc] + minbuy[ccc] ) / 2 ) ) + ( tempintetia * price[ccc] )  + dEps ;
                                        //System.out.println( Znext + " = ( ( 1 - " + tempintetia + " ) * " + " ( ( " + maxsell[ccc] + " + " + minbuy[ccc] +  " ) /2 ) + " + " ( " + tempintetia + " * " + price[ccc] + " ) " + dEps );
                                        //System.out.println( "------------------------------------kaina rytoj --------------------------------------------------");
                                    }
                                    else if ( buymade[ccc] ) {
                                        //System.out.println( "------------------------------------kaina rytoj po pirkimo  Z(t)--------------------------------------------------");
                                        Znext = ( ( 1 - tempintetia ) * minbuy[ccc] ) + ( tempintetia * price[ccc] ) + dEps;
                                        //System.out.println( Znext + " = ( ( 1 - " + tempintetia + " ) * " + minbuy[ccc] + " ) + ( " + tempintetia + " * " + price[ccc] + " ) + " + dEps );
                                        //System.out.println( "------------------------------------kaina rytoj--------------------------------------------------");
                                    }
                                    else if ( sellmade[ccc] ) {
                                        //System.out.println( "------------------------------------kaina rytoj po pardavimo  Z(t)--------------------------------------------------");
                                        Znext = ( ( 1 - tempintetia ) * maxsell[ccc] ) + ( tempintetia * price[ccc] ) + dEps;
                                        //System.out.println( Znext + " = ( ( 1 - " + tempintetia + " ) * " + maxsell[ccc] + " ) + ( " + tempintetia + " * " + price[ccc] + " ) + " + dEps );
                                        //System.out.println( "------------------------------------kaina rytoj--------------------------------------------------");
                                    }
                                    else {
                                        //System.out.println( "------------------------------------kaina rytoj veiksmo nebuvo Z(t)--------------------------------------------------");
                                        Znext = price[ccc] + dEps;
                                        //System.out.println( Znext + " =  " + price[ccc] + " + " + dEps );
                                        //System.out.println( "------------------------------------kaina rytoj--------------------------------------------------");
                                    }
                                    //System.out.println( "Eps: " + dEps );
                                    //dEps = ((Double)applet.volatility.get(stockNo)).doubleValue() * rNorm.nextGaussian();
                                    //dEps = applet.volatility * rNorm.nextGaussian();
                                    //System.out.println( "perskaiciuojam Eps: " + dEps );      
                            }
                        }
                        applet.stockEps[ccc].set(iIterN, dEps);
                        applet.stocksPrices[ccc].set( iIterN, Znext );
                    }
                    applet.realDataCounter++;
        }
        
        
        public String numberFont( double n ) {
            if ( n < 0 ) return "<font color=\"red\">" + n + "</font>";
            return "<font color=\"green\">" + n + "</font>";
        }
        
        public String numberFont( int n ) {
            if ( n < 0 ) return "<font color=\"red\">" + n + "</font>";
            return "<font color=\"green\">" + n + "</font>";
        }
        
        public static double Average( double[] a ) {
            double result = 0;
            for(int i = 0; i < a.length; i++){
              result = result + a[i];
            }
            return ( result / a.length );
        }
	
        public static void printr( double [] a  ) {
            String s = "";
            for ( int i = 0; i < a.length; i++ )
                s = s + a[i] + " ";
            System.out.println( s );
        }
        
        public static double round(double d, int decimalPlace){
            BigDecimal bd = new BigDecimal(Double.toString(d));
            bd = bd.setScale(decimalPlace,BigDecimal.ROUND_HALF_EVEN);
            return bd.doubleValue();
        }
        
        public int Months( int i ) {
            if ( i == 0 ) return 3;
            if ( i == 1 ) return 6;
            return 12;
        }
        
        void WriteOneArray( SRGMCustomer c, double [] profits ) // Write same data in one array
	{
		Iterations[0] = It;
		if (w10TextField != null)
			Iterations[1] = Ip;
		else
			Iterations[1] = -1;
	}

	// -----------------------------------------------------------
	void WriteArray( SRGMCustomer c, double [] profits ) // Wriite all data in arrays
	{
		int count = 0, Icount = 0;
		BankLength = 0;
		ShareLength = 0;
		InsuranceLength = 0;
		/*for (int i = 1; i < 9; i++)
			if (wITextField[i].getText().length() != 0)
				++Icount;*/
		ObjectValue = new double[Icount];

		//String Strr;
		//Strr = w1TextField.getText(); // Iterations
		try {
			//int n = Integer.parseInt(Strr);
                        int n = c.InvestmentIterations;
			It = n;
		} catch (NumberFormatException exc) {
			It = -1;
		}

		if (w10TextField != null) {
			//Strr = w10TextField.getText(); // Initial point
			try {
				int n = 10;// Integer.parseInt(Strr);
				Ip = n;
			} catch (NumberFormatException exc) {
				Ip = -1;
			}
		}

		try {
			double n = c.getAvFunds(); //Integer.parseInt(Strr);
			Resources = (int)n;
		} catch (NumberFormatException exc) {
			Resources = -1;
		}
	}
	// -----------------------------------------------------------
	
        public void iinit() {
		// Force SwingApplet to come up in the System L&F
		String laf = UIManager.getCrossPlatformLookAndFeelClassName();
		// String laf = UIManager.getSystemLookAndFeelClassName();
		try {
			System.out.println("");
			System.out.println("Started");
			UIManager.setLookAndFeel(laf);
			System.out.println("Found LookAndFeel: " + laf);
			System.out.println("");
		} catch (UnsupportedLookAndFeelException exc) {
			System.out.println("Warning: UnsupportedLookAndFeel: " + laf);
		} catch (Exception exc) {
			System.out.println("Error loading " + laf + ": " + exc);
		}
		
		w1Panel = new JPanel();
		w1Panel.setLayout(null);

		System.out.println("");
		System.out.println("Finished");

	}
}
    final class GUIUpdateNotifier implements Runnable {
	StartupApplet applet = null;
	public GUIUpdateNotifier( StartupApplet applet ){
            this.applet = applet;
	}
        public void run() {
            applet.updateGUI();
        }
    }
