/*
 * Created on 13.12.2004
 *
 * 
 * Window - Preferences - Java - Code Style - Code Templates
 */
package de.farafin.snEADy.control.GaphixStuff;
 
import de.farafin.snEADy.I_Main_interface;
import de.farafin.snEADy.communication.*;
import de.farafin.snEADy.player.*;
import de.farafin.snEADy.C_DebugMonitor;
import de.farafin.snEADy.GameParameter;
import de.farafin.snEADy.control.*;


import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;

import java.io.*;
import java.text.DecimalFormat;

/* TODO @lars alles mal schön kommentieren
 *
 */

/**
 * @author larsonmars
 *
 * 
 * 
 * @version $Revision: 1.65 $ 
 */
public class M_GraphixEngineUI extends GrWindow implements I_Control_interface, I_Constants,I_GraphixConstants{

	/*
	 * C_GraphixEngineUI.java
	 *
	 * Created on 1. Dezember 2004, 01:09
	 */
        
    /** Grafikrepräsentation der Arena */
    
    private class Gr_Arena{
        protected char [][] field;
        protected int sizeX;
        protected int sizeY;
        

        public Gr_Arena(int size_y, int size_x, char clearByte){
            this(size_y,size_x);
            for (int i=0;i<size_y;i++)
                for (int j=0;j<size_x;j++)
                    field[i][j]=clearByte;
        }
        public Gr_Arena(int size_y, int size_x){
            field=new char[size_y][size_x];
            sizeX=size_x;
            sizeY=size_y;
        }
        public Gr_Arena(char newField[][],D_GameInfo gameInfo){
            sizeX=newField[0].length;
            sizeY=newField.length;
            field=new char[sizeY][sizeX];
            convert(field,newField,gameInfo);
            
        }
        public void fill(char clearByte){
            for (int i=0;i<sizeY;i++)
                for (int j=0;j<sizeX;j++)
                    field[i][j]=clearByte;
        }
        public void update(char src[][],D_GameInfo gameInfo){
            
        	convert(field,src,gameInfo);
        }
        public void update(char src[][]){
            for (int i=0;i<sizeY;i++)
                for (int j=0;j<sizeX;j++)
                    field[i][j]=src[i][j];
        }
        private void convert(char fieldDest[][],char fieldSrc[][],D_GameInfo gameInfo){

            int succ_i,prev_i,succ_j,prev_j,i,j,lenX,lenY;
            lenY=fieldSrc.length;
            lenX=fieldSrc[0].length;
            D_PlayerData pd[]=gameInfo.playerData;
            
            for (i=0;i<lenY;i++){
                prev_i=(i-1+lenY)%lenY;
                succ_i=(i+1)%lenY;
                for (j=0;j<lenX;j++){
                    prev_j=(j-1+lenX)%lenX;
                    succ_j=(j+1)%lenX;
                    fieldDest[i][j]=0;
                    if (fieldSrc[i][j]==C_WALL){
                        if (fieldSrc[i][prev_j]!=C_WALL)
                            fieldDest[i][j]=C_WALLCORNER_W;
                        else if (fieldSrc[i][succ_j]!=C_WALL)
                            fieldDest[i][j]=C_WALLCORNER_E;
                            
                        if (fieldSrc[prev_i][j]!=C_WALL)
                            if (fieldDest[i][j]==C_WALLCORNER_W)
                                fieldDest[i][j]=C_WALLCORNER_NW_CV;
                            else if (fieldDest[i][j]==C_WALLCORNER_E)
                                fieldDest[i][j]=C_WALLCORNER_NE_CV;
                            else
                                fieldDest[i][j]=C_WALLCORNER_N;
                        else if (fieldSrc[succ_i][j]!=C_WALL)
                            if (fieldDest[i][j]==C_WALLCORNER_W)
                                fieldDest[i][j]=C_WALLCORNER_SW_CV;
                            else if (fieldDest[i][j]==C_WALLCORNER_E)
                                fieldDest[i][j]=C_WALLCORNER_SE_CV;
                            else
                                fieldDest[i][j]=C_WALLCORNER_S;
                        else
                            if (fieldDest[i][j]==0)
                                if (fieldSrc[succ_i][succ_j]!=C_WALL)
                                    fieldDest[i][j]=C_WALLCORNER_SE_CC;
                                else if (fieldSrc[succ_i][prev_j]!=C_WALL)
                                    fieldDest[i][j]=C_WALLCORNER_SW_CC;
                                else if (fieldSrc[prev_i][succ_j]!=C_WALL)
                                    fieldDest[i][j]=C_WALLCORNER_NE_CC;
                                else if (fieldSrc[prev_i][prev_j]!=C_WALL)
                                    fieldDest[i][j]=C_WALLCORNER_NW_CC;
                                else
                                    fieldDest[i][j]=C_WALL;
                    }
                    else{
                        if (fieldSrc[i][j]==C_EXIT){
                            if (fieldSrc[prev_i][j]!=C_EXIT  && fieldSrc[i][prev_j]!=C_EXIT){
                                
                            
                                if (gameInfo.gameTime>=gameInfo.exitTime)
                                    fieldDest[i][j]=C_EXITO;
                                else
                                    fieldDest[i][j]=C_EXIT;
                            }
                            else
                                fieldDest[i][j]=C_NOTHING;
                                
                        }
                        else{
                            fieldDest[i][j]=fieldSrc[i][j];
                        }
                    }
                }
               
            }
            
            for (i=0;i<pd.length;i++)
                if (pd[i].length>0 && pd[i].snakeStatus==IN_ACTION){
                    field[pd[i].headPos.y][pd[i].headPos.x]=(char)(i + C_PLAYERH_S);
                    
                }
             
            // System.out.println(this);  

        }
        public String toString(){
            StringBuffer ret=new StringBuffer(sizeY*sizeX);
            for (int i=0; i<sizeY;i++){
                for (int j=0;j<sizeX;j++){
                    ret.append((char)(field[i][j]+' '));
                }
                ret.append('\n');
            }
            return ret.toString();
            
            	
        }
    }
    private class Gr_DiffArena extends Gr_Arena{
        public Gr_DiffArena(Gr_Arena a1,Gr_Arena a2){
            super(a1.sizeY,a1.sizeX,C_FLOOR);
            update(a1,a2);
        }
        public Gr_DiffArena(Gr_Arena a){
        	super(a.sizeY,a.sizeX);
            for (int i=0; i<a.sizeY;i++)
                for (int j=0;j<a.sizeX;j++){
                    field[i][j]= a.field[i][j];
                }
        }
        public void update(Gr_Arena a1,Gr_Arena a2){
            for (int i=a1.sizeY-1;i>=0;i--)
                for (int j=a1.sizeX-1;j>=0;j--)
                    field[i][j]=(a1.field[i][j]==a2.field[i][j])? 0 : a2.field[i][j];
        }

        
    }


    private int frameC;
    private long lastTime;
    private float fps;
    
    D_GameInfo oldGameInfo;
    
    private C_Human[] humans;
    private int humanPlayerC=1; 


    private VolatileImage img_arena;
    private Graphics gr_arena;
    
    private VolatileImage img_pTab[]=new VolatileImage[10];
    private VolatileImage img_tab[]=new VolatileImage[10];
    Graphics gr_tab[]=new Graphics[10];

    
    private int monPosX,monPosY,monWidth=450,monHeight=450;
            
       

    private Gr_Arena arena[]=new Gr_Arena[2];
    private int actArena=0;
    private Gr_DiffArena diff;
    
    //private D_GameInfo lastGameInfo=new D_GameInfo();
    private int last_killPoints[]=new int[10];
    private int m_length[]=new int[10],m_killpoints[]=new int[10],m_cycles[]=new int[10],m_name[]=new int[10];
    private int lastPlayerC;
    private int playerOrd[];
    
    private M_GraphixEngineUI root;
    
    private Graphics actGraphics;
    
    private GrButton butt_run;
    private GrButton butt_stop;
    private GrButton butt_min;
    private GrButton butt_quit;
    private GrButton butt_arena;
    private GrButton butt_player;
    private GrButton butt_options;
    private GrButton butt_credits;
    private GrButton butt_rmPlayer[]=new GrButton[10];
    
    
    private Frame commandFrame;
    private TextField cf_text;
    private Label cf_lab;

    private GrDlgWindow arenaFS;
    private GrDlgWindow playerFS;
    private GrTextField text_hPlayerName;
    
    private GrButton butt_addHPlayer,butt_addCPlayer,butt_plOK;
    private GrSelCanvas sel_player;
    private GrTextArea area_commentsPlayer;
    private GrScroll scroll_player;
        
    private String[] fileList_player;

    
    
    private GrButton butt_loadArena,butt_arenaOK;
    private GrSelCanvas sel_arena;
	private GrTextArea area_commentsArena;
    private GrScroll scroll_arena;
    
    private String[] fileList_arena;

    
    
    private GrDlgWindow options;
    private GrTextField text_exitT,text_suddenDT,
						text_iLength,text_iDelay,
						text_aGrow,text_aSlowd,
						text_maxDelay,
						text_pLength,text_pSpeed,text_pSlowd,text_pPoints,
						text_maxTime,text_maxMem;
    
    private GrButton 	tgl_timeKill,
						tgl_showSC,
						tgl_debugMon,
						tgl_pPTime,
						tgl_pPMem,tgl_log;
    
						
   

    private String commandHist[]=new String[MAXCOMMANDHIST];
    private int selectedCommand=-1,lastInserted=MAXCOMMANDHIST-1;
    
    private C_DebugMonitor debugMon;
    
    private GameParameter gameParam;
    
    
    /** Creates a new instance of C_GraphixEngineUI */
    public M_GraphixEngineUI(I_Main_interface calling,GameParameter p,C_DebugMonitor debMon,int version){
        super("snEADy",800,600);
        C_GraphixData.version=version;
        C_GraphixData.main=calling;

    	debugMon=debMon;
    	root=this;
    	gameParam=p;
    	
        if (C_GraphixTools.loadImages())
        	if(DEBUG)
        		System.out.println("Images loaded sucessfully!");
        	
        
    	for (int i=0;i<10;i++){
    	    img_pTab[i]=C_GraphixTools.createBackBufferVI(C_GraphixData.menuImages[M_TABOPEN].getWidth(null),C_GraphixData.menuImages[M_TABOPEN].getHeight(null));
    	    img_tab[i]=C_GraphixTools.createBackBufferVI(C_GraphixData.menuImages[M_TABOPEN].getWidth(null),C_GraphixData.menuImages[M_TABOPEN].getHeight(null));
    	    gr_tab[i]=img_tab[i].getGraphics();
    	}
        drawPlayerTab(new boolean[]{true,true,true,true,true,true,true,true,true,true});

        addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
            	C_GraphixData.main.control("quit");
            }
        });

	    try{
	    addKeyListener(new KeyListener(){
	        public void keyTyped(KeyEvent e){}
	        public void keyPressed(KeyEvent e){
	            int key=e.getKeyCode(),i;
	
	            switch(key){
	           	case (KeyEvent.VK_ESCAPE):
	           		C_GraphixData.main.control("quit");
	           		return;
	           	case (KeyEvent.VK_F12):
	           		commandFrame.setVisible(!commandFrame.isVisible());
	            }
	           
	            for (i=0;i<humanPlayerC;i++){
	                if 			(key==humanPlayerKeyL[i]) humans[i].setNewDirection(PubConstants.WEST);
	           	   	else if 	(key==humanPlayerKeyU[i]) humans[i].setNewDirection(PubConstants.NORTH);
	           	   	else if 	(key==humanPlayerKeyR[i]) humans[i].setNewDirection(PubConstants.EAST);
	           	   	else if 	(key==humanPlayerKeyD[i]) humans[i].setNewDirection(PubConstants.SOUTH);
	            }
	        }
	        public void keyReleased(KeyEvent e){}
	    });
	    }catch(Exception e){}



        
        butt_run=new GrButton(212,142,GrButton.TOGGLEBUTTON,M_BUTTRUN,false){
        	public void stateChanged(int state){
    	    	C_GraphixData.main.control("run");
        	}
        };
        butt_stop=new GrButton(212,187,GrButton.NORMALBUTTON,M_BUTTSTOP,false){
        	public void stateChanged(int state){
        	        if (state==GrButton.BUTTON_PRESSEDHOVERED){
        	        	C_GraphixData.main.control("stop");
        	        }
        	}
        };
        butt_quit=new GrButton(752,14,GrButton.NORMALBUTTON,M_BUTTQUIT,true){
        	public void stateChanged(int state){
        		if (state==GrButton.BUTTON_PRESSEDHOVERED)
        			C_GraphixData.main.control("quit");
        	}
        };
        butt_min=new GrButton(715,14,GrButton.NORMALBUTTON,M_BUTTMIN,true){
        	public void stateChanged(int state){
        		if (state==GrButton.BUTTON_PRESSEDHOVERED)
        			root.setState(Frame.ICONIFIED);
        	}
        };
        butt_credits=new GrButton(293,84,GrButton.NORMALBUTTON,M_BUTTCREDITS,false){
        	public void stateChanged(int state){
        		if (state==GrButton.BUTTON_PRESSEDHOVERED){
        			
        		}
        			
        	}
        };
        butt_arena=new GrButton(10,209,GrButton.NORMALBUTTON,M_BUTTARENA,false){
        	public void stateChanged(int state){
        		if (arenaFS.isVisible())
        			arenaFS.requestFocus();
        		else
        			arenaFS.setVisible(true);
        		
        	}
        };
        butt_player=new GrButton(102,213,GrButton.NORMALBUTTON,M_BUTTPLAYER,false){
        	public void stateChanged(int state){
        		
        		if (playerFS.isVisible())
        			playerFS.requestFocus();
        		else
        			playerFS.setVisible(true);
        		text_hPlayerName.setText("Player_"+(lastPlayerC+1),F_NORMAL,playerFS.isVisible());
        	}
        };
        butt_options=new GrButton(233,232,GrButton.NORMALBUTTON,M_BUTTOPTIONS,false){
        	public void stateChanged(int state){
        		
        		if (options.isVisible())
        			options.requestFocus();
        		else
        			options.setVisible(true);
        		updateOptions(options.isVisible());
        	}
        };
        
        for (int i=0;i<10;i++){
        	butt_rmPlayer[i]=new GrButton(292,316+i*26,GrButton.NORMALBUTTON,M_BUTTRMPLAYER,false,i){
            	public void stateChanged(int state){
            		if (state==GrButton.BUTTON_PRESSEDHOVERED){
            			C_GraphixData.main.control("delplayer " + playerOrd[iData] );
            		}
            	}
            };
        }
        
        add(butt_run);
        add(butt_stop);
        add(butt_min);
        add(butt_credits);
        add(butt_quit);
        add(butt_arena);
        add(butt_player);
        add(butt_options);
        for (int i=0;i<10;i++)add(butt_rmPlayer[i]);

        setVisible(true);
    	actGraphics=getGraphics();
        

        setupFileSelectorArena();
        setupFileSelectorPlayer();
        setupOptions();
        setupCommandFrame();
    }
    private M_GraphixEngineUI(){}
    private void setupOptions(){
    	options=new GrDlgWindow("snEADy - Options",C_GraphixData.menuImagesO[S_OPTIONSBG]);
        text_exitT=new GrTextField(60,85,6,String.valueOf(gameParam.getExit_time()),ALLIG_LEFT,true,"set " + exit_time);
		text_suddenDT=new GrTextField(220,85,6,String.valueOf(gameParam.getSuddend_time()),ALLIG_LEFT,true,"set "+ suddend_time);
		text_iLength=new GrTextField(77,125,4,String.valueOf(gameParam.getInit_length()),ALLIG_LEFT,true,"set "+init_length);
		text_iDelay=new GrTextField(177,125,2,String.valueOf(gameParam.getInit_move_delay()),ALLIG_LEFT,true,"set "+init_move_delay);
		text_aGrow=new GrTextField(66,165,5,String.valueOf(gameParam.getAuto_grow_delay()),ALLIG_LEFT,true,"set "+auto_grow_delay);
		text_aSlowd=new GrTextField(201,165,5,String.valueOf(gameParam.getAuto_slowdown_delay()),ALLIG_LEFT,true,"set "+auto_slowdown_delay);
		text_maxDelay=new GrTextField(93,205,4,String.valueOf(gameParam.getMax_goody_occ_delay()),ALLIG_LEFT,true,"set "+max_goody_occ_delay);
		text_pLength=new GrTextField(66,245,2,String.valueOf(gameParam.getGoody_length_occ()),ALLIG_LEFT,true,"set "+goody_length_occ);
		text_pSpeed=new GrTextField(126,245,2,String.valueOf(gameParam.getGoody_speed_occ()),ALLIG_LEFT,true,"set "+goody_speed_occ);
		text_pSlowd=new GrTextField(198,245,2,String.valueOf(gameParam.getGoody_slowdown_occ()),ALLIG_LEFT,true,"set "+goody_slowdown_occ);
		text_pPoints=new GrTextField(257,245,2,String.valueOf(gameParam.getGoody_points_occ()),ALLIG_LEFT,true,"set "+goody_points_occ);
		text_maxTime=new GrTextField(232,325,6,String.valueOf(gameParam.getMax_thinking_ms()),ALLIG_LEFT,true,"set "+max_thinking_ms);
		text_maxMem=new GrTextField(140,346,8,String.valueOf(gameParam.getMax_player_mem()),ALLIG_LEFT,true,"set "+max_player_mem);
		
        tgl_timeKill=new GrButton(76,321,GrButton.TOGGLEBUTTON,M_TGLBUTT,true){
        	
            	public void stateChanged(int state){
            		if (state==GrButton.BUTTON_PRESSEDHOVERED){
            			C_GraphixData.main.control("set TIMEOUT_MS " + gameParam.getMax_thinking_ms());
            		}
            		else C_GraphixData.main.control("set TIMEOUT_MS 0");
            	}
         };
         if (gameParam.getTimeout_ms()>0) tgl_timeKill.bState=GrButton.BUTTON_PRESSED;
         tgl_showSC=new GrButton(122,401,GrButton.TOGGLEBUTTON,M_TGLBUTT,true){
        	public void stateChanged(int state){
        		if (state==GrButton.BUTTON_PRESSEDHOVERED) C_GraphixData.main.control("set SHOW_SUBCYCLES 1");
				else C_GraphixData.main.control("set SHOW_SUBCYCLES 0");
        	}
         };
         if (gameParam.getShow_subcycles()>0) tgl_showSC.bState=GrButton.BUTTON_PRESSED;
         tgl_debugMon=new GrButton(268,401,GrButton.TOGGLEBUTTON,M_TGLBUTT,true){
        	public void stateChanged(int state){
        		debugMon.setVisible(state==GrButton.BUTTON_PRESSEDHOVERED);
        	}
         };
         if (debugMon.isVisible()) tgl_debugMon.bState=GrButton.BUTTON_PRESSED;
         tgl_pPTime=new GrButton(98,461,GrButton.TOGGLEBUTTON,M_TGLBUTT,true){
        	public void stateChanged(int state){
        		if (state==GrButton.BUTTON_PRESSEDHOVERED) C_GraphixData.main.control("set PRINT_CALC_MS 1");
				else C_GraphixData.main.control("set PRINT_CALC_MS 0");
        	}
         };
         if (gameParam.getPrint_calc_ms()>0) tgl_pPTime.bState=GrButton.BUTTON_PRESSED;
         tgl_pPMem=new GrButton(253,461,GrButton.TOGGLEBUTTON,M_TGLBUTT,true){
        	public void stateChanged(int state){
        		if (state==GrButton.BUTTON_PRESSEDHOVERED) C_GraphixData.main.control("set PRINT_PLAYER_MEM 1");
				else C_GraphixData.main.control("set PRINT_PLAYER_MEM 0");
        	}
         };
         if (gameParam.getPrint_player_mem()>0) tgl_pPMem.bState=GrButton.BUTTON_PRESSED;
         tgl_log=new GrButton(129,483,GrButton.TOGGLEBUTTON,M_TGLBUTT,true){
        	public void stateChanged(int state){
        		if (state==GrButton.BUTTON_PRESSEDHOVERED) C_GraphixData.main.control("set LOGGING 1");
				else C_GraphixData.main.control("set LOGGING 0");
        	}
         };
         if (gameParam.getLogging()>0) tgl_pPMem.bState=GrButton.BUTTON_PRESSED;

//*/
		options.add(text_exitT);
		options.add(text_suddenDT);
		options.add(text_iLength);
		options.add(text_iDelay);
		options.add(text_aGrow);
		options.add(text_aSlowd);
		options.add(text_maxDelay);

		options.add(text_pLength);
		options.add(text_pSpeed);
		options.add(text_pSlowd);
		options.add(text_pPoints);
		options.add(text_maxTime);
		options.add(text_maxMem);
		
		options.add(tgl_timeKill);
		options.add(tgl_showSC);
		options.add(tgl_debugMon);
		options.add(tgl_pPTime);
		options.add(tgl_pPMem);
		options.add(tgl_log);
    }
    private void updateOptions(boolean grUp){
        text_exitT.setText(String.valueOf(gameParam.getExit_time()),F_NORMAL,grUp);
		text_suddenDT.setText(String.valueOf(gameParam.getSuddend_time()),F_NORMAL,grUp);
		text_iLength.setText(String.valueOf(gameParam.getInit_length()),F_NORMAL,grUp);
		text_iDelay.setText(String.valueOf(gameParam.getInit_move_delay()),F_NORMAL,grUp);
		text_aGrow.setText(String.valueOf(gameParam.getAuto_grow_delay()),F_NORMAL,grUp);
		text_aSlowd.setText(String.valueOf(gameParam.getAuto_slowdown_delay()),F_NORMAL,grUp);
		text_maxDelay.setText(String.valueOf(gameParam.getMax_goody_occ_delay()),F_NORMAL,grUp);
		text_pLength.setText(String.valueOf(gameParam.getGoody_length_occ()),F_NORMAL,grUp);
		text_pSpeed.setText(String.valueOf(gameParam.getGoody_speed_occ()),F_NORMAL,grUp);
		text_pSlowd.setText(String.valueOf(gameParam.getGoody_slowdown_occ()),F_NORMAL,grUp);
		text_pPoints.setText(String.valueOf(gameParam.getGoody_points_occ()),F_NORMAL,grUp);
		text_maxTime.setText(String.valueOf(gameParam.getMax_thinking_ms()),F_NORMAL,grUp);
		text_maxMem.setText(String.valueOf(gameParam.getMax_player_mem()),F_NORMAL,grUp);
        if (gameParam.getTimeout_ms()>0) tgl_timeKill.bState=GrButton.BUTTON_PRESSED;

        if (gameParam.getShow_subcycles()>0) tgl_showSC.bState=GrButton.BUTTON_PRESSED;

        
        if (debugMon.isVisible()) tgl_debugMon.bState=GrButton.BUTTON_PRESSED;

        if (gameParam.getPrint_calc_ms()>0) tgl_pPTime.bState=GrButton.BUTTON_PRESSED;

        if (gameParam.getPrint_player_mem()>0) tgl_pPMem.bState=GrButton.BUTTON_PRESSED;

        if (gameParam.getLogging()>0) tgl_pPMem.bState=GrButton.BUTTON_PRESSED;

        if (grUp){
            tgl_timeKill.repaint();
            tgl_showSC.repaint();
            tgl_debugMon.repaint();
            tgl_pPTime.repaint();
            tgl_pPMem.repaint();
            tgl_pPMem.repaint();
            tgl_pPMem.repaint();
            
        }

    }
    private static final void appendCuttedString(StringBuffer dest,String src,int maxLen){
    	if (src.length()>maxLen){
    		dest.append(src.substring(0,maxLen-3));
    		dest.append("...");
    	}
    	else
    		dest.append(src);
    }
    private void setupFileSelectorArena(){
   	
    	
    	FilenameFilter filt=new FilenameFilter(){
    		public boolean accept(File f,String s){
    			return s.toLowerCase().endsWith(".smp");
    		}
    	};
    	fileList_arena=dir_arena.list(filt);
        
    	arenaFS=new GrDlgWindow("snEADy - Arena Loader",C_GraphixData.menuImagesO[S_ARENABG]);
        sel_arena=new GrSelCanvas(18,72,256,210,fileList_arena){
        	public void action(){
        		StringBuffer str;
        		D_Level lev;
    			int i,maxLen;
    			maxLen=area_commentsArena.showW/8-8;
    			i=sel_arena.showedLinesStart+sel_arena.selected;
    			lev=C_GraphixData.main.getLevelHeader(fileList_arena[i].substring(0,fileList_arena[i].lastIndexOf('.')));
    			str=new StringBuffer(lev.name.length()+lev.autor.length()+42);
    			str.append(  "NAME:   ");
    			appendCuttedString(str,lev.name,maxLen);
    			str.append("\nAUTHOR: ");
    			appendCuttedString(str,lev.autor,maxLen);
    			str.append("\nSIZE:   ");
    			str.append(lev.height);
    			str.append('x');
    			str.append(lev.width);
    			str.append("\nPLAYER: ");
    			str.append(lev.maxPlayer);
    			str.append("\nSKIN:   ");
    			str.append(C_GraphixTools.getAvailLevelGraphix(lev.fileName));
    			
    			area_commentsArena.setText(str.toString(),F_NORMAL,true);

        	}
        };
        area_commentsArena=new GrTextArea(18,314,176,84,"",ALLIG_LEFT,true);
        scroll_arena=new GrScroll(282,68,22,218,sel_arena);
        butt_loadArena=new GrButton(214,310,GrButton.NORMALBUTTON,S_BUTTLOAD,true){
        	public void stateChanged(int state){
        		int i;
        		if (state==GrButton.BUTTON_PRESSEDHOVERED){
        			i=sel_arena.showedLinesStart+sel_arena.selected;
        			if (i>=0){
        				C_GraphixData.main.control(loadlevel +  fileList_arena[i].substring(0,fileList_arena[i].lastIndexOf('.')));
        			}
        		}
		
        	}
         };
        butt_arenaOK=new GrButton(129,433,GrButton.NORMALBUTTON,S_BUTTOK,true){
        	public void stateChanged(int state){
        		if (state==GrButton.BUTTON_PRESSEDHOVERED){
        			arenaFS.setVisible(false);
        		}
		
        	}
         };

        arenaFS.add(sel_arena);
        arenaFS.add(area_commentsArena);
        arenaFS.add(scroll_arena);
        arenaFS.add(butt_loadArena);
        arenaFS.add(butt_arenaOK);    	
    }
    private void setupFileSelectorPlayer(){
    	FilenameFilter filt=new FilenameFilter(){
    		public boolean accept(File f,String s){
    			return s.toLowerCase().endsWith(".class");
    		}
    	};
       
    	fileList_player=dir_player.list(filt);
    	
        playerFS=new GrDlgWindow("snEADy - Player Loader",C_GraphixData.menuImagesO[S_PLAYERBG]);
        text_hPlayerName=new GrTextField(18,392,17,"Player_"+(lastPlayerC+1),ALLIG_LEFT,false,null);
        sel_player=new GrSelCanvas(18,72,256,168,fileList_player){
        	public void action(){
    			int i;
    			String str;
    			i=sel_player.showedLinesStart+sel_player.selected;
        		str=C_GraphixData.main.getPlayerComment(fileList_player[i].substring(0,fileList_player[i].lastIndexOf('.')));
        		area_commentsPlayer.setText(str,ALLIG_LEFT,true);
        	}
        };
        area_commentsPlayer=new GrTextArea(18,272,176,42,"",ALLIG_LEFT,true);
        scroll_player=new GrScroll(282,68,22,176,sel_player);
        butt_addHPlayer=new GrButton(214,384,GrButton.NORMALBUTTON,S_BUTTADD,true){
        	public void stateChanged(int state){
        		if (state==GrButton.BUTTON_PRESSEDHOVERED){
        			C_GraphixData.main.control(loadhuman + text_hPlayerName.text.toString());
        			text_hPlayerName.setText("Player_"+(lastPlayerC+1),F_NORMAL,true);
        		}
		
        	}
         };
        butt_addCPlayer=new GrButton(214,268,GrButton.NORMALBUTTON,S_BUTTADD,true){
        	public void stateChanged(int state){
        		int i;
        		if (state==GrButton.BUTTON_PRESSEDHOVERED){
        			i=sel_player.showedLinesStart+sel_player.selected;
        			if (i>=0)
        				C_GraphixData.main.control(loadplayer +  fileList_player[i].substring(0,fileList_player[i].lastIndexOf('.')));
        		}
		
        	}
         };
        butt_plOK=new GrButton(129,433,GrButton.NORMALBUTTON,S_BUTTOK,true){
        	public void stateChanged(int state){
        		if (state==GrButton.BUTTON_PRESSEDHOVERED){
        			playerFS.setVisible(false);
        		}
		
        	}
         };

        playerFS.add(sel_player);
        playerFS.add(area_commentsPlayer);
        playerFS.add(scroll_player);
        playerFS.add(text_hPlayerName);
        playerFS.add(butt_addHPlayer);
        playerFS.add(butt_addCPlayer);
        playerFS.add(butt_plOK);
    }
        
    private void setupCommandFrame(){
        commandFrame=new Frame("snEADy Command Window");
       
        commandFrame.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                commandFrame.setVisible(false);
            }
        });
        

        cf_lab=new Label("Enter Commends here!");
        //textA_commandHist=new TextArea(0,64);
        //textA_commandHist.setEditable(false);
        
        cf_lab.setBackground(Color.WHITE);
       // textA_commandHist.setSize(getWidth(),20);
        cf_text=new TextField("",64);

        cf_text.addKeyListener(new KeyListener(){
            public void keyTyped(KeyEvent e){
                
            }
            public void keyPressed(KeyEvent e){
                int key=e.getKeyCode();
                String t;
                switch(key){
                	case (KeyEvent.VK_ESCAPE):
                	    commandFrame.setVisible(false);
                		break;
                	case (KeyEvent.VK_ENTER):
                	    t=cf_text.getText();
                	    
                	    cf_text.setText("");
                	    if (C_GraphixData.main.control(t)){
                	        cf_lab.setText(t+" executed!");
                	    }
                	    else
                	        cf_lab.setText(t+" FAILED!");
                	    
                	    lastInserted=(lastInserted+1)%(MAXCOMMANDHIST);
                	    commandHist[lastInserted]=t;
                	    selectedCommand=-1;
                	    root.requestFocusInWindow();
            	        if (e.getModifiers()==InputEvent.CTRL_MASK){
            	        	commandFrame.setVisible(false);
            	        }
                	    break;
                	case (KeyEvent.VK_UP):
                	    
                		if (selectedCommand<(MAXCOMMANDHIST-1) && commandHist[(MAXCOMMANDHIST+lastInserted-selectedCommand-1)%MAXCOMMANDHIST]!=null)
                			selectedCommand++;
                		cf_text.setText(commandHist[(MAXCOMMANDHIST+lastInserted-selectedCommand)%MAXCOMMANDHIST]);
                	    break;
                	case (KeyEvent.VK_DOWN):
                	    if (selectedCommand>0){
                			selectedCommand--;
                			cf_text.setText(commandHist[(MAXCOMMANDHIST+lastInserted-selectedCommand)%MAXCOMMANDHIST]);
                	    }
                		else
                		    cf_text.setText("");
                		break;
                }
                
           
            }
            public void keyReleased(KeyEvent e){
                
            }

        });
        
        commandFrame.setBounds(getX(),getY()+getHeight(),getWidth(),70);
        commandFrame.setResizable(false);
        commandFrame.add(cf_lab,BorderLayout.CENTER);
        commandFrame.add(cf_text,BorderLayout.SOUTH);

		//transferFocus();

    }


    /*
    public static VolatileImage getDoubledImage(VolatileImage img_src){
        
        int w=img_src.getWidth();
        int h=img_src.getHeight();
        VolatileImage img_res;
        Graphics2D g;
        
   		img_res = createBImage(w*2,h*2);
   		img_res = createBImage(w*2,h*2);
   		
        g=img_res.createGraphics();
        g.drawImage(img_src,0,0,Color.BLACK,null);
       	g.drawImage(img_src,w,0,Color.BLACK,null);
        g.drawImage(img_src,0,h,Color.BLACK,null);
        g.drawImage(img_src,w,h,Color.BLACK,null);

        
        return img_res;
     }
    */

  


    private void updateGraphics(){
         char actC;
         int i,j;
         int x,y=0,
         srcStartX=0,srcStartY=0,
         srcEndX=0,srcEndY=0,
         destEndX=FIELDELEMSIZE,destEndY=FIELDELEMSIZE,
         sy=diff.sizeY,sx=diff.sizeX;
         int imgID=0;
         Gr_Arena a=diff;
       
         do{
	         if (img_arena.validate(C_GraphixData.gc)!=VolatileImage.IMAGE_OK){
	         	if (img_arena.validate(C_GraphixData.gc)==VolatileImage.IMAGE_INCOMPATIBLE){
		         	if (img_arena!=null){
		         		img_arena.flush();
		         		img_arena=null;
		         	}
		         	img_arena=C_GraphixTools.createBackBufferVI(sx*FIELDELEMSIZE,sx*FIELDELEMSIZE);
	         	}
	         	a=arena[actArena];
	         }
	         
	        // System.out.println(diff);
	         for (i=0;i<sy;i++){
	             x=0;
	             for (j=0;j<sx;j++){
	
	                actC=a.field[i][j];
	
	                if (actC>0){
	                    
	                    if (actC==C_FLOOR){
	                    	
	                        srcStartX=x%(C_GraphixData.gameImages[C_FLOOR].getWidth(null));
	                        srcStartY=y%(C_GraphixData.gameImages[C_FLOOR].getHeight(null));
	                        srcEndX=srcStartX+FIELDELEMSIZE;
	                        srcEndY=srcStartY+FIELDELEMSIZE;
	                        destEndX=x+FIELDELEMSIZE;
	                        destEndY=y+FIELDELEMSIZE;
	                        imgID=C_FLOOR;
	                    }
	                    else if	(actC>= C_WALL_S && actC<= C_WALL_E){
	                        srcStartX=(actC-C_WALL_S)*FIELDELEMSIZE;
	                        srcStartY=0;
	                        srcEndX=srcStartX+FIELDELEMSIZE;
	                        srcEndY=FIELDELEMSIZE;
	                        destEndX=x+FIELDELEMSIZE;
	                        destEndY=y+FIELDELEMSIZE;
	                        imgID=C_WALL_S;
	                    }
	                    else if (actC>= C_PLAYERH_S && actC<= C_PLAYERH_E){
	                        srcStartX=(actC-C_PLAYERH_S)*FIELDELEMSIZE;
	                        srcStartY=0;
	                        srcEndX=srcStartX+FIELDELEMSIZE;
	                        srcEndY=FIELDELEMSIZE;
	                        destEndX=x+FIELDELEMSIZE;
	                        destEndY=y+FIELDELEMSIZE;
	                        imgID=C_PLAYER_S;
	                    }
	                    else if (actC>= C_PLAYER_S && actC<= C_PLAYER_E){
	                        srcStartX=(actC-C_PLAYER_S)*FIELDELEMSIZE;
	                        srcStartY=FIELDELEMSIZE;
	                        srcEndX=srcStartX+FIELDELEMSIZE;
	                        srcEndY=srcStartY+FIELDELEMSIZE;
	                        destEndX=x+FIELDELEMSIZE;
	                        destEndY=y+FIELDELEMSIZE;
	                        imgID=C_PLAYER_S;
	                    }
	                    else if (actC>= C_GOODY_S && actC<= C_GOODY_E){
	                        srcStartX=(actC-C_GOODY_S)*FIELDELEMSIZE;
	                        srcStartY=0;
	                        srcEndX=srcStartX+FIELDELEMSIZE;
	                        srcEndY=FIELDELEMSIZE;
	                        destEndX=x+FIELDELEMSIZE;
	                        destEndY=y+FIELDELEMSIZE;
	                        imgID=C_GOODY_S;
	                    }
	                    else if (actC==C_EXIT){
	                        srcStartX=0;
	                        srcStartY=0;
	                        srcEndX=C_GraphixData.gameImages[C_EXIT].getWidth(null)/2;
	                        srcEndY=C_GraphixData.gameImages[C_EXIT].getHeight(this);
	                        destEndX=x+srcEndX;
	                        destEndY=y+srcEndY;
	
	                        imgID=C_EXIT;
	                        
	                    }
	                    else if (actC==C_EXITO){
	                        srcStartX=C_GraphixData.gameImages[C_EXIT].getWidth(null)/2;
	                        srcStartY=0;
	                        srcEndX=C_GraphixData.gameImages[C_EXIT].getWidth(null);
	                        srcEndY=C_GraphixData.gameImages[C_EXIT].getHeight(null);
	                        imgID=C_EXIT;
	                        destEndX=x+srcEndY;
	                        destEndY=y+srcEndY;
	
	                    }
	                    else{
	                        
	                        srcStartX=0;
	                        srcStartY=0;
	                        srcEndX=FIELDELEMSIZE;
	                        srcEndY=FIELDELEMSIZE;
	                        destEndX=x+FIELDELEMSIZE;
	                        destEndY=y+FIELDELEMSIZE;
	                        imgID=actC;
	                        if (C_GraphixData.gameImages[imgID]==null) imgID=C_UNKNOWN;
	                        
	                    }
	
	
	                    C_GraphixTools.drawGameImageToBackbuffer(img_arena,imgID,x,y,destEndX,destEndY,srcStartX,srcStartY,srcEndX,srcEndY);
	                    //gr_arena.drawImage(img,x,y,destEndX,destEndY,srcStartX,srcStartY,srcEndX,srcEndY,null,null);
	                    //if (!complete)actGraphics.drawImage(img,monPosX+x,monPosY+y,monPosX+destEndX,monPosY+destEndY,srcStartX,srcStartY,srcEndX,srcEndY,null,null);
	                    //actGraphics.drawImage(gameImages[imgID],monPosX+x,monPosY+y,monPosX+destEndX,monPosY+destEndY,srcStartX,srcStartY,srcEndX,srcEndY,null,null);
	                }
	                x+=FIELDELEMSIZE;      
	             }
	             y+=FIELDELEMSIZE;
	         }
	         actGraphics.drawImage(img_arena,monPosX,monPosY,null,null);
	         
         }while (img_arena.contentsLost());
    }
    
    private void updateTexts(D_GameInfo gameInfo,Graphics g){
        int mode=F_NORMAL;
        final String leer6[]=new String[7];
        leer6[0]="      ";  leer6[1]="     ";leer6[2]="    ";leer6[3]="   ";leer6[4]="  ";leer6[5]=" ";leer6[6]="";

        StringBuffer tmpStrB=new StringBuffer(6);;

        tmpStrB.append(gameInfo.gameTime);
        tmpStrB.insert(0,leer6[tmpStrB.length()]);
        C_GraphixTools.drawBitmapString(tmpStrB.toString(),63,179,M_FONTSERP8X14,g,ALLIG_RIGHT,mode);

        if (gameInfo.exitTime<=gameInfo.gameTime)
            mode=F_GREEN;
        else
            mode=F_NORMAL;
        
        tmpStrB.delete(0,6);
        tmpStrB.append(gameInfo.exitTime);
        tmpStrB.insert(0,leer6[tmpStrB.length()]);
        C_GraphixTools.drawBitmapString(tmpStrB.toString(),127,179,M_FONTSERP8X14,g,ALLIG_RIGHT,mode);
        
        if (gameInfo.suddenDeath<=gameInfo.gameTime)
            mode=F_RED;
        else
            mode=F_NORMAL;
        tmpStrB.delete(0,6);
        tmpStrB.append(gameInfo.suddenDeath);
        tmpStrB.insert(0,leer6[tmpStrB.length()]);
        C_GraphixTools.drawBitmapString(tmpStrB.toString(),191,179,M_FONTSERP8X14,g,ALLIG_RIGHT,mode);
        
        
    }
    
    private void updatePlayer(D_GameInfo gameInfo){
        D_PlayerData pd[]=gameInfo.playerData;
        for (int i=0;i<pd.length;i++){

        	if (pd[i].snakeStatus==IN_ACTION){
                if (pd[i].delayChanged>0) m_cycles[i]=F_RED;
	            else if (pd[i].delayChanged<0)m_cycles[i]=F_GREEN;
	            else m_cycles[i]=F_NORMAL;
             
	            if (pd[i].lengthChanged<0)m_length[i]=F_RED;
	            else if (pd[i].lengthChanged>0)m_length[i]=F_GREEN;
	            else m_length[i]=F_NORMAL;
	            
 	            if (last_killPoints[i]>pd[i].killPoints){
 	                m_killpoints[i]=F_RED;
 	                last_killPoints[i]=pd[i].killPoints;
 	            }
	            else if (last_killPoints[i]<pd[i].killPoints){
	                m_killpoints[i]=F_GREEN;
	                last_killPoints[i]++;
	            }
	            else m_killpoints[i]=F_NORMAL;


 	            
 	            if (m_name[i]==F_INACTIVE){
 	            	m_name[i]=F_NORMAL;
 	            	m_length[i]=F_NORMAL;
 	            	m_cycles[i]=F_NORMAL;
 	            	m_killpoints[i]=F_NORMAL;
 	            }
          	
        	}
        	else{
                if (last_killPoints[i]>pd[i].killPoints){
                    last_killPoints[i]=pd[i].killPoints;
            		m_name[i]=F_NORMAL;
            		m_length[i]=F_NORMAL;
            		m_cycles[i]=F_NORMAL;
            		m_killpoints[i]=F_NORMAL;

                }
                else if (last_killPoints[i]<pd[i].killPoints){
                    m_killpoints[i]=F_GREEN;
            		m_name[i]=F_NORMAL;
            		m_length[i]=F_NORMAL;
            		m_cycles[i]=F_NORMAL;
                    last_killPoints[i]++;
                }
                else{
	        		m_name[i]=F_INACTIVE;
	        		m_length[i]=F_INACTIVE;
	        		m_cycles[i]=F_INACTIVE;
	        		m_killpoints[i]=F_INACTIVE;
                }
        	}
            //if gameInfo.gameTime
        }
    }

    private void updatePlayerTab(D_GameInfo gameInfo){
        int i,j,r=1;
        
        int valid;
        boolean array[]=new boolean[10];
        
        D_PlayerData pd[]=new D_PlayerData[gameInfo.playerData.length];
        D_PlayerData tmpP;
        StringBuffer strB=new StringBuffer(13);
        
        playerOrd=new int[gameInfo.playerData.length];
        
        //D_PlayerData tmp;
        int tmp;

        
        //for (i=0;i<ord.length;i++)ord[i]=i;
        
        if (gameInfo.playerData.length>0){
	        pd[0]=gameInfo.playerData[0];
	        playerOrd[0]=0;
	        for (i=1;i<playerOrd.length;i++){
	            j=i;
	            playerOrd[i]=i;
	            //pd[i]=gameInfo.playerData[i];
	            pd[i]=gameInfo.playerData[i];
	            
	            while (j>0 && pd[playerOrd[j]].killPoints>(pd[playerOrd[j-1]]).killPoints){
	                //tmp=pd[j];pd[j]=pd[j-1];
	                tmp=playerOrd[j];playerOrd[j]=playerOrd[j-1];
	                playerOrd[--j]=tmp;
	            }
	        }
	
	        for (i=0;i<playerOrd.length;i++){
	        	
	        	do{
		        	valid=img_tab[i].validate(C_GraphixData.gc);
		
		    		if (valid==VolatileImage.IMAGE_INCOMPATIBLE){
				    	img_tab[i]=C_GraphixTools.createBackBufferVI(C_GraphixData.menuImages[M_TABOPEN].getWidth(null),C_GraphixData.menuImages[M_TABOPEN].getHeight(null));
				    	gr_tab[i]=img_tab[i].getGraphics();
		    		}
		    		//do{
			        	if (img_pTab[playerOrd[i]].validate(C_GraphixData.gc)!=VolatileImage.IMAGE_OK){
			        		for (int k=0;k<10;k++)array[k]=false;
			        		array[i]=true;
			        		drawPlayerTab(array);
			        	}
		    		//}while(img_pTab[ord[i]].contentsLost());
		        		
		        		
		        		
		            gr_tab[i].drawImage(img_pTab[playerOrd[i]],0,0,null);
		
		            tmpP=pd[playerOrd[i]];
		            if (pd[playerOrd[i]].name.length()>16){
		                strB.delete(0,13);
		                strB.append(pd[i].name.substring(0,12));
		                strB.append('.');
		                tmpP.name=strB.toString();
		            }
		            if (i>=1 && pd[playerOrd[i]].killPoints!=pd[playerOrd[i-1]].killPoints) r++;
		            C_GraphixTools.drawBitmapString(String.valueOf(r),18,4,M_FONTSERP8X14,gr_tab[i],ALLIG_RIGHT,m_cycles[playerOrd[i]]);
		            
		            C_GraphixTools.drawBitmapString(tmpP.name,58,4,M_FONTSERP8X14,gr_tab[i],ALLIG_LEFT,m_name[playerOrd[i]]);
		            
		            if (pd[playerOrd[i]].length<1000)
		            	C_GraphixTools.drawBitmapString(String.valueOf(pd[playerOrd[i]].length),218,4,M_FONTSERP8X14,gr_tab[i],ALLIG_RIGHT,m_length[playerOrd[i]]);
		            else
		            	C_GraphixTools.drawBitmapString("WOW",218,4,M_FONTSERP8X14,gr_tab[i],ALLIG_RIGHT,m_length[playerOrd[i]]);
		            
		            C_GraphixTools.drawBitmapString(String.valueOf(pd[playerOrd[i]].waitCycles),235,4,M_FONTSERP8X14,gr_tab[i],ALLIG_RIGHT,m_cycles[playerOrd[i]]);
		
		            C_GraphixTools.drawBitmapString(String.valueOf(last_killPoints[playerOrd[i]]),276,4,M_FONTSERP8X14,gr_tab[i],ALLIG_RIGHT,m_killpoints[playerOrd[i]]);
	        	}while(img_tab[i].contentsLost());            
	        }
        }
        for (i=pd.length;i<10;i++){
        	valid=img_tab[i].validate(C_GraphixData.gc);

        	do{
	    		if (valid==VolatileImage.IMAGE_INCOMPATIBLE){
			    	img_tab[i]=C_GraphixTools.createBackBufferVI(C_GraphixData.menuImages[M_TABOPEN].getWidth(null),C_GraphixData.menuImages[M_TABOPEN].getHeight(null));
			    	gr_tab[i]=img_tab[i].getGraphics();
	    		}
	    		
	    		C_GraphixTools.wantReadMenuImage(M_TABCLOSE);
	    		gr_tab[i].drawImage(C_GraphixData.menuImages[M_TABCLOSE],0,0,null);
        	}while (img_tab[i].contentsLost());
        }
        
    }
    private void drawMenuElements(Graphics g,D_GameInfo gameInfo){
    	for (int i=0;i<10;i++){
    		do{
	    		if (img_tab[i].validate(C_GraphixData.gc)!=VolatileImage.IMAGE_OK)
	    			updatePlayerTab(gameInfo);
    		}while (img_tab[i].contentsLost());
    		g.drawImage(img_tab[i],10,i*26+318,null);
    	}
    	updateTexts(gameInfo,g);
    	
    }



    private void drawPlayerTab(boolean drawArray[]){
        int i;
        final int psX=40,psY=2;
        int valid;

        Graphics g;



        for (i=0;i<10;i++){
        	if (drawArray[i]){
        		do{
	        		valid=img_pTab[i].validate(C_GraphixData.gc);
	        		
	        		if (valid!=VolatileImage.IMAGE_OK){
	        			if (valid==VolatileImage.IMAGE_INCOMPATIBLE)
	        				img_pTab[i]=C_GraphixTools.createBackBufferVI(C_GraphixData.menuImages[M_TABOPEN].getWidth(null),C_GraphixData.menuImages[M_TABOPEN].getHeight(null));
	        		}
	                g=img_pTab[i].getGraphics();
	                C_GraphixTools.wantReadMenuImage(M_TABOPEN);
		            g.drawImage(C_GraphixData.menuImages[M_TABOPEN],0,0,null);
		            g.drawImage(C_GraphixData.gameImages[C_PLAYER_S],psX,psY,psX+FIELDELEMSIZE,psY+FIELDELEMSIZE,FIELDELEMSIZE*i,0,FIELDELEMSIZE*(i+1),FIELDELEMSIZE,null,null);
		            g.drawImage(C_GraphixData.gameImages[C_PLAYER_S],psX,psY+FIELDELEMSIZE,psX+FIELDELEMSIZE,psY+2*FIELDELEMSIZE,FIELDELEMSIZE*i,FIELDELEMSIZE,FIELDELEMSIZE*(i+1),2*FIELDELEMSIZE,null,null);
		            g.drawImage(C_GraphixData.gameImages[C_PLAYER_S],psX-FIELDELEMSIZE,psY+FIELDELEMSIZE,psX,psY+2*FIELDELEMSIZE,FIELDELEMSIZE*i,FIELDELEMSIZE,FIELDELEMSIZE*(i+1),2*FIELDELEMSIZE,null,null);
		            g.drawImage(C_GraphixData.gameImages[C_PLAYER_S],psX-FIELDELEMSIZE,psY+2*FIELDELEMSIZE,psX,psY+3*FIELDELEMSIZE,FIELDELEMSIZE*i,FIELDELEMSIZE,FIELDELEMSIZE*(i+1),2*FIELDELEMSIZE,null,null);
        		}while (img_pTab[i].contentsLost());
        	}
        }
        
    }
    
  /*  
    private void drawRanks(D_GameInfo gameInfo,Graphics g){
        for (int i=gameInfo.playerData.length-1;i>=0;i--){
            g.drawImage(menuImages[M_TABR],9,i*26+317,null);
            drawBitmapString(String.valueOf(i+1),30,323+i*26,M_FONTSERP8X14,g,ALLIG_RIGHT,F_NORMAL);
        }
    }
    //*/

    public void paint(Graphics g){
     	
    	C_GraphixTools.drawVMenuImage(M_BG,g);
    	
        
    	
    	if (img_arena !=null){
	    	if (img_arena.validate(C_GraphixData.gc)!=VolatileImage.IMAGE_OK)
	    		updateGraphics();
	    	else
		         g.drawImage(img_arena,monPosX,monPosY,null,null);
        }
        
        if (oldGameInfo!=null){
        	drawMenuElements(g,oldGameInfo);
        }
        
   //     g.drawImage(gameImages[C_EXIT],0,0,null);

    }
    


    /*
    public void update(Graphics g){
        paint(g);
        System.out.println("bigUpd");
        
    }//*/

    private void checkActivations(D_GameInfo gameInfo){
    	int i;
    	if (gameInfo.gameRunning){
    		butt_run.setEnabled(true);
    		butt_loadArena.setEnabled(false);
    		butt_addCPlayer.setEnabled(false);
    		butt_addHPlayer.setEnabled(false);
    		butt_stop.setEnabled(true);
    		for (i=0;i<gameInfo.playerData.length;i++)
    			butt_rmPlayer[i].setEnabled(false);
    		
    	}
    	else{
    		butt_loadArena.setEnabled(true);
    		butt_addCPlayer.setEnabled(true);
    		butt_addHPlayer.setEnabled(true);
    		if (gameInfo.playerData.length>0)
    			butt_run.setEnabled(true);
    		else
    			butt_run.setEnabled(false);
    		
    		butt_stop.setEnabled(false);
    		for (i=0;i<gameInfo.playerData.length;i++)
    			butt_rmPlayer[i].setEnabled(true);
    		for (i=gameInfo.playerData.length;i<MAX_PLAYERS;i++)
    			butt_rmPlayer[i].setEnabled(false);

    	}

    	butt_arena.setEnabled(true);
    	butt_player.setEnabled(true);
    	butt_options.setEnabled(true);
    	
    }
    public void setActive(boolean active){
        if (active){
        	checkActivations(oldGameInfo);
	        //butt_stop.setEnabled(true);
        }
        else{
	        butt_run.setEnabled(false);
	        butt_stop.setEnabled(false);
    		butt_loadArena.setEnabled(false);
    		butt_addCPlayer.setEnabled(false);
    		butt_addHPlayer.setEnabled(false);
	        for (int i=0;i<10;i++)
	        	if (i<playerOrd.length)
	        		butt_rmPlayer[i].setEnabled(false);
//*/
        }
		        
    }

    
	/* (non-Javadoc)
	 * @see de.farafin.snEADy.I_Control_interface#update(de.farafin.snEADy.communication.D_GameInfo)
	 */
	public void update(D_GameInfo gameInfo,C_Human[] humanPlayer) {

	    long time;
	    
	    
	    if (DEBUG) time=System.currentTimeMillis();


	    humans=humanPlayer;
	    
	    if (humans!=null) humanPlayerC=humans.length;
	    else humanPlayerC=0;
	    
	    if (!gameInfo.gameRunning){
	    	if (gameInfo.level!=null && (oldGameInfo==null || oldGameInfo.level==null || gameInfo.level.fileName.compareTo(oldGameInfo.level.fileName)!=0))
    			C_GraphixTools.loadCustomLevelGraphix(gameInfo.level.fileName);
	    }
	    
	    if (gameInfo.level==null){
	    	actGraphics.fillRect(MONSTARTX,MONSTARTY,ARENAMAXSIZE*FIELDELEMSIZE,ARENAMAXSIZE*FIELDELEMSIZE);
	    }
	    else{
		    if ( arena[actArena]==null || arena[actArena].sizeX!=gameInfo.level.width || arena[actArena].sizeY!=gameInfo.level.height){   
		    	arena[actArena]=new Gr_Arena(gameInfo.level.playField,gameInfo);
		    	diff=new Gr_DiffArena(arena[actArena]);
	
		    	//gr_arena.GraphicsConfiguration.createCompatibleImage(arena[actArena].sizeX*FIELDELEMSIZE,arena[actArena].sizeY*FIELDELEMSIZE);
		    	img_arena=C_GraphixTools.createBackBufferVI(arena[actArena].sizeX*FIELDELEMSIZE,arena[actArena].sizeY*FIELDELEMSIZE);
		    	gr_arena=img_arena.getGraphics();
	
		        
		        monPosX=MONSTARTX+(ARENAMAXSIZE*FIELDELEMSIZE-arena[actArena].sizeX*FIELDELEMSIZE)/2;
		        monPosY=MONSTARTY+(ARENAMAXSIZE*FIELDELEMSIZE-arena[actArena].sizeY*FIELDELEMSIZE)/2;
	
		        monWidth=arena[actArena].sizeX*6;
		        monHeight=arena[actArena].sizeY*6;
		        //if (monWidth>45)monWidth=45;
		        //if (monHeight>45)monHeight=45;
		        actGraphics.fillRect(MONSTARTX,MONSTARTY,ARENAMAXSIZE*FIELDELEMSIZE,monPosY-MONSTARTY);
		        actGraphics.fillRect(MONSTARTX,monPosY,monPosX-MONSTARTX,monHeight);
		        actGraphics.fillRect(monPosX+monWidth,monPosY,monPosX-MONSTARTX,monHeight);
		        actGraphics.fillRect(MONSTARTX,monPosY+monHeight,ARENAMAXSIZE*FIELDELEMSIZE,monPosY-MONSTARTY);
		        updateGraphics();
	
		    }
		    else{
		        if (arena[1-actArena]==null || arena[1-actArena].sizeX!=gameInfo.level.width || arena[1-actArena].sizeY!=gameInfo.level.height)
		            arena[1-actArena]=new Gr_Arena(gameInfo.level.playField,gameInfo);
		        else
		            arena[1-actArena].update(gameInfo.level.playField,gameInfo);
		       	diff.update(arena[actArena], arena[1-actArena]);
	
		        actArena=1-actArena;
		        
		        
		        updateGraphics();
		    }
	    }

	    if (oldGameInfo!=null && (oldGameInfo.gameRunning!=gameInfo.gameRunning  || gameInfo.playerData.length!=oldGameInfo.playerData.length)){
	    	checkActivations(gameInfo);
	    }

    
	    lastPlayerC=gameInfo.playerData.length;
	    
        updatePlayer(gameInfo);
        
        updatePlayerTab(gameInfo);
        drawMenuElements(actGraphics,gameInfo);
        
        if (oldGameInfo==null)
        	oldGameInfo=new D_GameInfo(gameInfo);
        else
        	oldGameInfo.copyOnMe(gameInfo);

        
        
        debugMon.sayBuffered();
        if (DEBUG){
	        lastTime+=(System.currentTimeMillis()-time);
	        frameC++;
	        if (frameC>=MAXFRAMECOUNT){
	            fps=1000.0f*frameC/lastTime;
	            DecimalFormat df=new DecimalFormat(".##");
	            //DecimalFormat df =new DecimalFormat( "0.00" );
	            System.out.println("DEBUG GraphixEngine FPS: " + df.format(fps));           // 12.345,68
	            frameC=0;
	            lastTime=0;
	        }
       
        
	    }//*/
	}

	public void beep(){
		System.out.println("BEEP!!!");
	}
	public void beep(String str){
		System.out.println("BEEP: " + str);
	}
	public void beep(int i){
		System.out.println("BEEP: " + i);
	}
	//*/
}
