/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package csa.tiletools.map;

import csa.config.Configuration;
import csa.gui.Windowable;
import csa.gui.components.CSAView;
import csa.gui.dialogs.InternalFrameFileChoser;
import csa.gui.ImageCache;
import csa.gui.image.OctTreeQuantizer;
import csa.tiletools.graphics.BaseImageData;
import csa.tiletools.graphics.ClickListener;
import csa.tiletools.graphics.ImageComponent;
import csa.tiletools.graphics.ImageSequence;
import csa.tiletools.graphics.ImageSequenceData;
import csa.tiletools.graphics.ImageSequenceDataPool;
import csa.tiletools.graphics.MustSaveAsOneDialog;
import csa.tiletools.graphics.OriginJPanel;
import csa.tiletools.script.ExportFrame;
import csa.tiletools.tiles.Tile;
import csa.tiletools.tiles.TileData;
import csa.tiletools.tiles.TileDataPool;
import csa.tiletools.worldgen.heroextant.ElevationGenerationPhase;
import csa.tiletools.worldgen.heroextant.Hemisphere;
import csa.tiletools.worldgen.heroextant.TileType;
import csa.tiletools.worldgen.heroextant.WorldGenerator;
import csa.tiletools.worldgen.heroextant.maptoolkit.data.DenseMapData;
import csa.tiletools.worldgen.mapgen.MapGen;
import csa.tiletools.worldgen.worldgen.WorldGen;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Point;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.File;
import java.util.*;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.TransferHandler;
import javax.swing.border.Border;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import net.sourceforge.jiu.color.quantization.MedianCutQuantizer;
import net.sourceforge.jiu.color.quantization.OctreeColorQuantizer;
import net.sourceforge.jiu.color.quantization.PopularityQuantizer;
import net.sourceforge.jiu.gui.awt.BufferedRGB24Image;

/**
 *
 * @author salchr
// does keep Alpha! But reduces colors only in respect to RGB not to A
 */
public class BuildLayerFromAlgorythmPanel extends javax.swing.JPanel implements Windowable, ClickListener{

    class ColorRenderer extends JLabel implements TableCellRenderer
    {
        Border unselectedBorder = null;
        Border selectedBorder = null;
        boolean isBordered = true;

        public ColorRenderer(boolean isBordered) {
            this.isBordered = isBordered;
            setOpaque(true); //MUST do this for background to show up.
        }

        @Override
        public Component getTableCellRendererComponent(
                                JTable table, Object color,
                                boolean isSelected, boolean hasFocus,
                                int row, int column) {
            Color newColor = (Color)color;
            setBackground(newColor);
            if (isBordered) {
                if (isSelected) {
                    if (selectedBorder == null) {
                        selectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
                                                  table.getSelectionBackground());
                    }
                    setBorder(selectedBorder);
                } else {
                    if (unselectedBorder == null) {
                        unselectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
                                                  table.getBackground());
                    }
                    setBorder(unselectedBorder);
                }
            }

            setToolTipText("RGB value: " + newColor.getRed() + ", "
                                         + newColor.getGreen() + ", "
                                         + newColor.getBlue());
            return this;
        }
    }
    class BufferedImageRenderer extends JLabel implements TableCellRenderer
    {
        Border unselectedBorder = null;
        Border selectedBorder = null;
        boolean isBordered = true;

        public BufferedImageRenderer(boolean isBordered) {
            this.isBordered = isBordered;
            setOpaque(true); //MUST do this for background to show up.
        }

        @Override
        public Component getTableCellRendererComponent(
                                JTable table, Object im,
                                boolean isSelected, boolean hasFocus,
                                int row, int column) {
            if (isBordered) {
                if (isSelected) {
                    if (selectedBorder == null) {
                        selectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
                                                  table.getSelectionBackground());
                    }
                    setBorder(selectedBorder);
                } else {
                    if (unselectedBorder == null) {
                        unselectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
                                                  table.getBackground());
                    }
                    setBorder(unselectedBorder);
                }
            }
            setToolTipText("");
            setIcon(null);
            if (im == null)
                return this;

            BufferedImage image = (BufferedImage)im;
            setIcon(new ImageIcon(image));

            setToolTipText("TileName: " + currentColorTileMap.mTileFile.elementAt(row)+"->"+currentColorTileMap.mTileName.elementAt(row));
            setHorizontalAlignment(CENTER);
            setVerticalAlignment(CENTER);
            return this;
        }
    }
    class MyTransferHandler extends TransferHandler
    {
        public MyTransferHandler()
        {
        }
        @Override
        public boolean canImport(TransferHandler.TransferSupport support)
        {
            return true;
        }
        @Override
        public boolean importData(TransferHandler.TransferSupport support)
        {
            try
            {
                if (mAllTilesInClass == null) return false;
                DataFlavor stringFlavor = DataFlavor.stringFlavor;
                Component c = support.getComponent(); // target
                Transferable t = support.getTransferable();
                String data = t.getTransferData(stringFlavor).toString();
                System.out.println("Dropped: " + data);
                int number = -1;

                JTable table=(JTable)support.getComponent();
                // fetch the drop location
                JTable.DropLocation dl = (JTable.DropLocation)support.getDropLocation();

                int row = dl.getRow();
                int col = dl.getColumn();

                int rowColor = currentColorTileMap.mColor.elementAt(row);


                TileData tileData = null;
                for (int i = 0; i < mAllTilesInClass.size(); i++)
                {
                    tileData = mAllTilesInClass.elementAt(i);
                    if (tileData.mName.equals(data)) break;
                }

                if (tileData == null) return false;
                ImageSequenceData iSData = getImageSequenceDataForTile(tileData);
                String name = tileData.mName;
                String filename = tileData.getTileSetFileName();
                filename = jTextFieldTileFile.getText();
                Vector <BaseImageData> biddata = BaseImageData.toBase(iSData);
                BufferedImage newItem = null;

                if (biddata.size()>0)
                {
                    BaseImageData baseImageData = biddata.elementAt(0);
                    newItem = ImageCache.getImageCache().getDerivatScale(baseImageData.image, (int)(25), (int)(25));
                }
                currentColorTileMap.mImages.insertElementAt(newItem, row);
                currentColorTileMap.mImages.removeElementAt(row+1);

                currentColorTileMap.mTileFile.insertElementAt(filename, row);
                currentColorTileMap.mTileFile.removeElementAt(row+1);

                currentColorTileMap.mTileName.insertElementAt(name, row);
                currentColorTileMap.mTileName.removeElementAt(row+1);
            }
            catch (Throwable e)
            {
                e.printStackTrace();
            }

            return true;
        }
    }
    int inSetting;
    boolean displayAsImages = true;
    //private ColorTileMap mColorTileMap = new ColorTileMap();
    Color textBack = Color.WHITE;
    Color currentBackground = null;
    private ColorTileMapPool mColorTileMapPool;

    private ColorTileMap currentColorTileMap =null;

    HashMap<String, TileData> tileCache = new HashMap<String, TileData>();


    Vector <TileData> mAllTilesInClass = new Vector <TileData>();
    private TileDataPool mTileDataPool = null;
    private int mClassSetting=0;
    private CSAView mParent = null;
    private javax.swing.JMenuItem mParentMenuItem = null;
    private BufferedImage orgImage = null;
    int selectedRow = -1;
    //Vector<Integer> vcolors = new Vector<Integer>();
    //HashMap<Integer, TileImageData> colors = new HashMap<Integer, TileImageData>();
    boolean notDragged = true;
    Layer mLayer = null;
    boolean mSuccessfull = false;
    public boolean successfull()
    {
        return mSuccessfull;
    }

    class TileImageData
    {
        TileData tile=null;
        BufferedImage image=null;
    }


    @Override
    public void closing(){}
    @Override
    public void setParentWindow(CSAView jpv)
    {
        mParent = jpv;
    }
    @Override
    public void setMenuItem(javax.swing.JMenuItem item)
    {
        mParentMenuItem = item;
        mParentMenuItem.setText("Build Layer...");
    }
    @Override
    public javax.swing.JMenuItem getMenuItem()
    {
        return mParentMenuItem;
    }
    @Override
    public javax.swing.JPanel getPanel()
    {
        return this;
    }

    /**
     * Creates new form ColorReduceJPanel
     */
    public BuildLayerFromAlgorythmPanel() {
        initComponents();
        jTable1.setModel(getTableModel());
        singleImagePanel1.addClickListener(this);
        jTable1.setDefaultRenderer(Color.class, new ColorRenderer(true));
        jTable1.setDefaultRenderer(BufferedImage.class, new BufferedImageRenderer(true));
        jTable1.setRowHeight(30);
        jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(80);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(40);

        mColorTileMapPool = new ColorTileMapPool();
        resetConfigPool(false, "");
        jTable1.setTransferHandler(new MyTransferHandler());
        textBack = jTextField5.getBackground();
    }
    MapEdit mMPParent = null;
    public BuildLayerFromAlgorythmPanel(Layer l, MapEdit p) {
        initComponents();

        mLayer = l;
        mMPParent = p;
        jTable1.setModel(getTableModel());
        singleImagePanel1.addClickListener(this);
        jTable1.setDefaultRenderer(Color.class, new ColorRenderer(true));
        jTable1.setDefaultRenderer(BufferedImage.class, new BufferedImageRenderer(true));
        jTable1.setRowHeight(30);
        jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(80);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(40);

        mColorTileMapPool = new ColorTileMapPool();
        resetConfigPool(false, "");
        jTable1.setTransferHandler(new MyTransferHandler());
        textBack = jTextField5.getBackground();
    }

    private void resetConfigPool(boolean select, String klasseToSet) /* allneeded*/
    {
        mClassSetting++;
        Collection<String> collectionKlasse = mColorTileMapPool.getKlassenHashMap().values();
        Iterator<String> iterKlasse = collectionKlasse.iterator();
        int i = 0;
        String klasse = "";

        jComboBoxKlasse.removeAllItems();
        while (iterKlasse.hasNext())
        {
            String item = iterKlasse.next();
            jComboBoxKlasse.addItem(item);
            if (select)
            {
                if (klasseToSet.length()==0)
                {
                    if (i==0)
                    {
                        jComboBoxKlasse.setSelectedIndex(i);
                        jTextFieldKlasse.setText(item);
                        klasse = item;
                    }
                }
                else
                {
                    if (klasseToSet.equalsIgnoreCase(item))
                    {
                        jComboBoxKlasse.setSelectedIndex(i);
                        jTextFieldKlasse.setText(item);
                        klasse = item;
                    }
                }
            }
            i++;
        }
        if ((select) && (klasse.length()==0))
        {
            if (jComboBoxKlasse.getItemCount()>0)
            {
                jComboBoxKlasse.setSelectedIndex(0);
                jTextFieldKlasse.setText(jComboBoxKlasse.getSelectedItem().toString());
                klasse = jComboBoxKlasse.getSelectedItem().toString();
            }
        }
        if (!select)  jComboBoxKlasse.setSelectedIndex(-1);

        Collection<ColorTileMap> colC = mColorTileMapPool.getMapForKlasse(klasse).values();
        Iterator<ColorTileMap> iterC = colC.iterator();

        jComboBoxName.removeAllItems();
        i = 0;
        while (iterC.hasNext())
        {
            ColorTileMap item = iterC.next();
            jComboBoxName.addItem(item.mName);
            if ((i==0) && (select))
            {
                jComboBoxName.setSelectedIndex(0);
                currentColorTileMap = mColorTileMapPool.get(item.mName);
                setAllFromCurrent();
            }
            i++;
        }
        if (!select)  jComboBoxName.setSelectedIndex(-1);
        mClassSetting--;
    }

    private void clearAll() /* allneeded*/
    {
        mClassSetting++;
        currentColorTileMap = new ColorTileMap();
        setAllFromCurrent();
        mClassSetting--;
    }

    private void setAllFromCurrent() /* allneeded*/
    {
        mClassSetting++;
        jComboBoxKlasse.setSelectedItem(currentColorTileMap.mClass);
        jTextFieldKlasse.setText(currentColorTileMap.mClass);
        jComboBoxName.setSelectedItem(currentColorTileMap.mName);
        jTextFieldName.setText(currentColorTileMap.mName);


        for (int t=0; t < currentColorTileMap.mTileName.size(); t++)
        {
            currentColorTileMap.mImages.insertElementAt(null, t);

            TileData tileData = null;
            String name = currentColorTileMap.mTileName.elementAt(t);
            String filename = currentColorTileMap.mTileFile.elementAt(t);

            TileDataPool localTileDataPool = new TileDataPool("Tile"+File.separator+filename+".xml");
            if (localTileDataPool == null) continue;
            Collection<TileData> colDk = localTileDataPool.getHashMap().values();

            tileData = localTileDataPool.get(name);

            if (tileData == null) continue;
            ImageSequenceData iSData = getImageSequenceDataForTile(tileData);

            Vector <BaseImageData> biddata = BaseImageData.toBase(iSData);
            BufferedImage newItem = null;

            if (biddata.size()>0)
            {
                BaseImageData baseImageData = biddata.elementAt(0);
                newItem = ImageCache.getImageCache().getDerivatScale(baseImageData.image, (int)(25), (int)(25));
            }
            
            currentColorTileMap.mImages.insertElementAt(newItem, t);
            currentColorTileMap.mImages.removeElementAt(t+1);
        }

        jTable1.tableChanged(null);
        jTable1.setRowHeight(30);
        jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(80);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(40);

        mClassSetting--;
    }

    private void readAllToCurrent() /* allneeded*/
    {
        currentColorTileMap.mClass = jTextFieldKlasse.getText();
        currentColorTileMap.mName = jTextFieldName.getText();
    }

    @Override
    public void clicked(MouseEvent evt)
    {
        if (currentColorTileMap == null) return;
        int r = singleImagePanel1.getR();
        int g = singleImagePanel1.getG();
        int b = singleImagePanel1.getB();

        if (singleImagePanel1.isShiftPressedOnClick())
        {
            currentBackground = new Color(r,g,b) ;
            jTextField5.setBackground(currentBackground);
            jTextField5.setText(""+r + ", " + g + ", " + b);
            jTextField5.setToolTipText(""+r + ", " + g + ", " + b);
            return;
        }

        selectedRow = -1;

        for (int i = 0; i < currentColorTileMap.mColor.size(); i++) {
            Color c = new Color(currentColorTileMap.mColor.elementAt(i));
            if (   (c.getRed() == r)
                && (c.getGreen() == g)
                && (c.getBlue() == b))
            {
                selectedRow = i;
                break;
            }
        }
        if (selectedRow != -1)
            jTable1.setRowSelectionInterval(selectedRow, selectedRow);



    }



    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel4 = new javax.swing.JPanel();
        singleImagePanel1 = new csa.tiletools.graphics.SingleImagePanel();
        jPanel18 = new javax.swing.JPanel();
        jScrollPane10 = new javax.swing.JScrollPane();
        jPanelIMageCollection2 = new javax.swing.JPanel();
        jPanel19 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jButtonFileSelect1 = new javax.swing.JButton();
        jTextFieldTileFile = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jComboBoxTileKlasse = new javax.swing.JComboBox();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel5 = new javax.swing.JPanel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jTextFieldName = new javax.swing.JTextField();
        jTextFieldKlasse = new javax.swing.JTextField();
        jComboBoxKlasse = new javax.swing.JComboBox();
        jComboBoxName = new javax.swing.JComboBox();
        jButtonDelete = new javax.swing.JButton();
        jButtonSaveAsNew = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jButtonSave = new javax.swing.JButton();
        jButtonNew = new javax.swing.JButton();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel3 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldImageSource = new javax.swing.JTextField();
        jButtonFileSelect = new javax.swing.JButton();
        jTextField4 = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jTextField2 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jCheckBoxScaled = new javax.swing.JCheckBox();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton7 = new javax.swing.JButton();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton2 = new javax.swing.JRadioButton();
        jTextFieldTileX = new javax.swing.JTextField();
        jTextFieldTileY = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        jTextField5 = new javax.swing.JTextField();
        jButtonBuildMap = new javax.swing.JButton();
        jButton8 = new javax.swing.JButton();
        jCheckBoxUseNearest = new javax.swing.JCheckBox();
        jCheckBoxnNearestCanBeEmpty = new javax.swing.JCheckBox();
        jButtonBuildISO2 = new javax.swing.JButton();
        jButtonBuildISO1 = new javax.swing.JButton();
        jButtonBuildISO = new javax.swing.JButton();
        jPanel6 = new javax.swing.JPanel();
        jButtonHeroBuildImage = new javax.swing.JButton();
        jTextField6 = new javax.swing.JTextField();
        jTextField7 = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        jTextField8 = new javax.swing.JTextField();
        jLabel13 = new javax.swing.JLabel();
        jTextField9 = new javax.swing.JTextField();
        jButton11 = new javax.swing.JButton();
        jTextField20 = new javax.swing.JTextField();
        jLabel28 = new javax.swing.JLabel();
        jTextField25 = new javax.swing.JTextField();
        jLabel29 = new javax.swing.JLabel();
        jLabel30 = new javax.swing.JLabel();
        jTextField28 = new javax.swing.JTextField();
        jLabel31 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel32 = new javax.swing.JLabel();
        jTextField24 = new javax.swing.JTextField();
        jButton14 = new javax.swing.JButton();
        jPanel7 = new javax.swing.JPanel();
        jButton9 = new javax.swing.JButton();
        jLabel14 = new javax.swing.JLabel();
        jTextField10 = new javax.swing.JTextField();
        jLabel15 = new javax.swing.JLabel();
        jTextField11 = new javax.swing.JTextField();
        jTextField12 = new javax.swing.JTextField();
        jTextField13 = new javax.swing.JTextField();
        jLabel16 = new javax.swing.JLabel();
        jCheckBox1 = new javax.swing.JCheckBox();
        jCheckBox2 = new javax.swing.JCheckBox();
        jTextField14 = new javax.swing.JTextField();
        jLabel17 = new javax.swing.JLabel();
        jCheckBox3 = new javax.swing.JCheckBox();
        jLabel18 = new javax.swing.JLabel();
        jTextField15 = new javax.swing.JTextField();
        jLabel19 = new javax.swing.JLabel();
        jTextField16 = new javax.swing.JTextField();
        jLabel20 = new javax.swing.JLabel();
        jLabel21 = new javax.swing.JLabel();
        jTextField17 = new javax.swing.JTextField();
        jTextField18 = new javax.swing.JTextField();
        jButton12 = new javax.swing.JButton();
        jButton15 = new javax.swing.JButton();
        jPanel8 = new javax.swing.JPanel();
        jLabel22 = new javax.swing.JLabel();
        jTextField19 = new javax.swing.JTextField();
        jTextField21 = new javax.swing.JTextField();
        jLabel24 = new javax.swing.JLabel();
        jTextField22 = new javax.swing.JTextField();
        jLabel25 = new javax.swing.JLabel();
        jLabel26 = new javax.swing.JLabel();
        jLabel27 = new javax.swing.JLabel();
        jTextField23 = new javax.swing.JTextField();
        jTextField26 = new javax.swing.JTextField();
        jTextField27 = new javax.swing.JTextField();
        jButton10 = new javax.swing.JButton();
        jButton13 = new javax.swing.JButton();
        jButton16 = new javax.swing.JButton();

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        singleImagePanel1.setPreferredSize(new java.awt.Dimension(100, 100));
        singleImagePanel1.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                singleImagePanel1ComponentResized(evt);
            }
        });

        javax.swing.GroupLayout singleImagePanel1Layout = new javax.swing.GroupLayout(singleImagePanel1);
        singleImagePanel1.setLayout(singleImagePanel1Layout);
        singleImagePanel1Layout.setHorizontalGroup(
            singleImagePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        singleImagePanel1Layout.setVerticalGroup(
            singleImagePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        jPanel18.setBorder(javax.swing.BorderFactory.createTitledBorder("Tile Collection"));
        jPanel18.setAlignmentX(1.0F);

        jScrollPane10.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        jScrollPane10.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        jPanelIMageCollection2.setMinimumSize(new java.awt.Dimension(20, 20));
        jPanelIMageCollection2.setLayout(null);

        jPanel19.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        jPanel19.setPreferredSize(new java.awt.Dimension(52, 52));

        javax.swing.GroupLayout jPanel19Layout = new javax.swing.GroupLayout(jPanel19);
        jPanel19.setLayout(jPanel19Layout);
        jPanel19Layout.setHorizontalGroup(
            jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 50, Short.MAX_VALUE)
        );
        jPanel19Layout.setVerticalGroup(
            jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 50, Short.MAX_VALUE)
        );

        jPanelIMageCollection2.add(jPanel19);
        jPanel19.setBounds(5, 5, 52, 52);

        jScrollPane10.setViewportView(jPanelIMageCollection2);

        javax.swing.GroupLayout jPanel18Layout = new javax.swing.GroupLayout(jPanel18);
        jPanel18.setLayout(jPanel18Layout);
        jPanel18Layout.setHorizontalGroup(
            jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel18Layout.createSequentialGroup()
                .addComponent(jScrollPane10, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        jPanel18Layout.setVerticalGroup(
            jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane10)
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Tile Selection"));

        jButtonFileSelect1.setText("...");
        jButtonFileSelect1.setMargin(new java.awt.Insets(0, 1, 0, -1));
        jButtonFileSelect1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonFileSelect1ActionPerformed(evt);
            }
        });

        jTextFieldTileFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldTileFileActionPerformed(evt);
            }
        });
        jTextFieldTileFile.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextFieldTileFileFocusLost(evt);
            }
        });

        jLabel6.setText("Filename");

        jLabel7.setText("Class");

        jComboBoxTileKlasse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxTileKlasseActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 22, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jTextFieldTileFile)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonFileSelect1))
                    .addComponent(jComboBoxTileKlasse, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldTileFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(jButtonFileSelect1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jComboBoxTileKlasse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 211, Short.MAX_VALUE)
        );

        jLabel8.setText("Class");

        jLabel9.setText("Name");

        jComboBoxKlasse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxKlasseActionPerformed(evt);
            }
        });

        jComboBoxName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxNameActionPerformed(evt);
            }
        });

        jButtonDelete.setText("Delete");
        jButtonDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDeleteActionPerformed(evt);
            }
        });

        jButtonSaveAsNew.setText("Save as new");
        jButtonSaveAsNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSaveAsNewActionPerformed(evt);
            }
        });

        jButton6.setText("Reset to Image colors");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        jButtonSave.setText("Save");
        jButtonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSaveActionPerformed(evt);
            }
        });

        jButtonNew.setText("New");
        jButtonNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonNewActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel8)
                    .addComponent(jLabel9))
                .addGap(16, 16, 16)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jTextFieldKlasse)
                            .addComponent(jTextFieldName, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jComboBoxName, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(jPanel5Layout.createSequentialGroup()
                                .addComponent(jComboBoxKlasse, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE))))
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel5Layout.createSequentialGroup()
                                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jButtonSave)
                                    .addComponent(jButtonNew))
                                .addGap(66, 66, 66)
                                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jButtonDelete)
                                    .addComponent(jButtonSaveAsNew)))
                            .addComponent(jButton6))
                        .addGap(0, 0, Short.MAX_VALUE))))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel8)
                        .addComponent(jTextFieldKlasse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jComboBoxKlasse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9)
                    .addComponent(jTextFieldName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jComboBoxName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addComponent(jButtonDelete)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButtonSave)
                            .addComponent(jButtonSaveAsNew)))
                    .addComponent(jButtonNew))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton6)
                .addContainerGap(80, Short.MAX_VALUE))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jLabel2.setText("Image source");

        jTextFieldImageSource.setToolTipText("Image path Info");
        jTextFieldImageSource.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextFieldImageSourceFocusLost(evt);
            }
        });

        jButtonFileSelect.setText("...");
        jButtonFileSelect.setToolTipText("If multiple files are selected, an \"Add Series\" is done automatically for all images.");
        jButtonFileSelect.setMargin(new java.awt.Insets(0, 1, 0, -1));
        jButtonFileSelect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonFileSelectActionPerformed(evt);
            }
        });

        jTextField4.setText("1024");
        jTextField4.setEnabled(false);

        jLabel5.setText("x");

        jTextField3.setText("1024");
        jTextField3.setEnabled(false);

        jLabel1.setText("Size");

        jLabel4.setText("Reduce To");

        jTextField1.setText("16");

        jButton1.setText("Reduce by Octree");
        jButton1.setToolTipText("Octree implementation by: Jerry Huxtable");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTextField2.setEnabled(false);

        jLabel3.setText("Color Count");

        jCheckBoxScaled.setText("scaled");
        jCheckBoxScaled.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBoxScaledActionPerformed(evt);
            }
        });

        jButton2.setText("Reduce by Median Cut");
        jButton2.setToolTipText("Quantization from jiu: http://sourceforge.net/projects/jiu/");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Reduce by Popularity");
        jButton3.setToolTipText("Quantization from jiu: http://sourceforge.net/projects/jiu/");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Reduce by Octree2");
        jButton4.setToolTipText("Quantization from jiu: http://sourceforge.net/projects/jiu/");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setText("Reduce by Octree3");
        jButton5.setToolTipText("Octree implementation by: ImageMagic, see: http://www.java2s.com/Code/Java/2D-Graphics-GUI/Anefficientcolorquantizationalgorithm.htm");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jButton7.setText("Reset");
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });

        buttonGroup1.add(jRadioButton1);
        jRadioButton1.setText("Tile Size fixed");
        jRadioButton1.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING);
        jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton1ActionPerformed(evt);
            }
        });

        buttonGroup1.add(jRadioButton2);
        jRadioButton2.setSelected(true);
        jRadioButton2.setText("Tile Size by 1. Tile");
        jRadioButton2.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING);
        jRadioButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton2ActionPerformed(evt);
            }
        });

        jTextFieldTileX.setText("0");
        jTextFieldTileX.setToolTipText("");

        jTextFieldTileY.setText("0");

        jLabel10.setText("Background Color");

        jTextField5.setEditable(false);
        jTextField5.setToolTipText("Shift click on image to select a color!");

        jButtonBuildMap.setText("Build Rect Layer");
        jButtonBuildMap.setToolTipText("Map is created with fixed tile width/height settings to calculate tile positioning!");
        jButtonBuildMap.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBuildMapActionPerformed(evt);
            }
        });

        jButton8.setText("no BG");
        jButton8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton8ActionPerformed(evt);
            }
        });

        jCheckBoxUseNearest.setText("use nearest");
        jCheckBoxUseNearest.setToolTipText("If selected, all pixels are mapped to a tile with the nearest color.\n");
        jCheckBoxUseNearest.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBoxUseNearestActionPerformed(evt);
            }
        });

        jCheckBoxnNearestCanBeEmpty.setText("nearest may be empty");
        jCheckBoxnNearestCanBeEmpty.setToolTipText("<html>\nIf selected colors which have not tile settings are kept \"empty\" (Background).<BR>\nIf not selected along with \"use nearesr\" ALL colors will get a tile!\n</html>\n");

        jButtonBuildISO2.setText("Build ISO C");
        jButtonBuildISO2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBuildISO2ActionPerformed(evt);
            }
        });

        jButtonBuildISO1.setText("Build ISO B");
        jButtonBuildISO1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBuildISO1ActionPerformed(evt);
            }
        });

        jButtonBuildISO.setText("Build ISO A");
        jButtonBuildISO.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBuildISOActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jButton5)
                        .addGap(133, 133, 133)
                        .addComponent(jTextFieldTileX, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jTextFieldTileY, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel3)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel4))
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(jPanel3Layout.createSequentialGroup()
                                        .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jCheckBoxScaled)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel1))
                                    .addComponent(jLabel10))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel3Layout.createSequentialGroup()
                                        .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(2, 2, 2)
                                        .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(jPanel3Layout.createSequentialGroup()
                                        .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jButton8))))
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addGap(12, 12, 12)
                                .addComponent(jTextFieldImageSource)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButtonFileSelect))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jRadioButton2)
                            .addComponent(jRadioButton1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jCheckBoxUseNearest)
                            .addComponent(jCheckBoxnNearestCanBeEmpty))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButtonBuildISO2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButtonBuildMap, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButtonBuildISO1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButtonBuildISO, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldImageSource, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(jButtonFileSelect))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel1)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(jButton7)
                    .addComponent(jCheckBoxScaled)
                    .addComponent(jButtonBuildISO))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel10)
                    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton8)
                    .addComponent(jButtonBuildISO1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jRadioButton1)
                    .addComponent(jCheckBoxUseNearest)
                    .addComponent(jButtonBuildISO2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jButton4)
                                .addComponent(jButton3)
                                .addComponent(jRadioButton2))
                            .addComponent(jCheckBoxnNearestCanBeEmpty))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextFieldTileX, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton5)
                            .addComponent(jTextFieldTileY, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jButtonBuildMap, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(0, 34, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Image", jPanel3);

        jButtonHeroBuildImage.setText("Generate Image");
        jButtonHeroBuildImage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonHeroBuildImageActionPerformed(evt);
            }
        });

        jTextField6.setText("100");
        jTextField6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField6ActionPerformed(evt);
            }
        });

        jTextField7.setText("100");

        jLabel11.setText("Size");

        jLabel12.setText("x");

        jTextField8.setText("3");

        jLabel13.setText("Seed");

        jTextField9.setToolTipText("Seed which was used!");

        jButton11.setText("Origin ");
        jButton11.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton11ActionPerformed(evt);
            }
        });

        jTextField20.setText("0.2");
        jTextField20.setToolTipText("from 0.0 - 1.0");

        jLabel28.setText("Sea level");

        jTextField25.setText("0.5");
        jTextField25.setToolTipText("from 0.0 - 1.0");

        jLabel29.setText("Elevation");

        jLabel30.setText("Roughness");

        jTextField28.setText("5");
        jTextField28.setToolTipText("from 1-...");

        jLabel31.setText("Hemisphere");

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "North", "South", "Equator" }));

        jLabel32.setText("River humidty threshold");

        jTextField24.setText("0.125");
        jTextField24.setToolTipText("from 0.0 - 1.0, the higher, the less rivers");

        jButton14.setText("Build Layer");
        jButton14.setEnabled(false);

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel6Layout.createSequentialGroup()
                        .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel30)
                            .addComponent(jLabel29)
                            .addComponent(jLabel28))
                        .addGap(48, 48, 48)
                        .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jTextField25, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextField28, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextField20, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel32)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField24, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel6Layout.createSequentialGroup()
                        .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(jPanel6Layout.createSequentialGroup()
                                .addComponent(jLabel31)
                                .addGap(46, 46, 46)
                                .addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel6Layout.createSequentialGroup()
                                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel11)
                                    .addComponent(jLabel13))
                                .addGap(78, 78, 78)
                                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(jPanel6Layout.createSequentialGroup()
                                        .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField9, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 119, Short.MAX_VALUE)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton11, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButtonHeroBuildImage, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton14, javax.swing.GroupLayout.Alignment.TRAILING)))
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel6Layout.createSequentialGroup()
                        .addComponent(jLabel11)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel13)
                        .addGap(27, 138, Short.MAX_VALUE))
                    .addGroup(jPanel6Layout.createSequentialGroup()
                        .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel12))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextField9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
                        .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel31, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jComboBox1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextField28, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel30))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextField25, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel29))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextField20, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel28)
                            .addComponent(jTextField24, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel32))
                        .addGap(21, 21, 21))))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton14, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton11)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonHeroBuildImage)
                .addContainerGap())
        );

        jTabbedPane1.addTab("Hero Extant", jPanel6);

        jButton9.setText("Generate Image");
        jButton9.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton9ActionPerformed(evt);
            }
        });

        jLabel14.setText("Size");

        jTextField10.setText("100");

        jLabel15.setText("x");

        jTextField11.setText("100");
        jTextField11.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField11ActionPerformed(evt);
            }
        });

        jTextField12.setToolTipText("Seed which was used!");

        jTextField13.setText("26004");
        jTextField13.setToolTipText("");

        jLabel16.setText("Seed");

        jCheckBox1.setSelected(true);
        jCheckBox1.setText("Smooth colors");

        jCheckBox2.setSelected(true);
        jCheckBox2.setText("Noisy edges");

        jTextField14.setText("2000");

        jLabel17.setText("Points");

        jCheckBox3.setSelected(true);
        jCheckBox3.setText("build coastline");

        jLabel18.setText("Landmass Min");

        jTextField15.setText("0.3");
        jTextField15.setToolTipText("from 0.0 - 1.0");

        jLabel19.setText("Rivers");

        jTextField16.setText("0.15");
        jTextField16.setToolTipText("from 0.0 - 1.0");

        jLabel20.setText("Landmass Max");

        jLabel21.setText("Lakes");

        jTextField17.setText("0.3");
        jTextField17.setToolTipText("from 0.0 - 1.0");

        jTextField18.setText("0.7");
        jTextField18.setToolTipText("from 0.0 - 1.0");

        jButton12.setText("Origin ");
        jButton12.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton12ActionPerformed(evt);
            }
        });

        jButton15.setText("Build Layer");
        jButton15.setEnabled(false);

        javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
        jPanel7.setLayout(jPanel7Layout);
        jPanel7Layout.setHorizontalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel7Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButton9))
                    .addGroup(jPanel7Layout.createSequentialGroup()
                        .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel7Layout.createSequentialGroup()
                                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel18)
                                    .addComponent(jLabel19))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jTextField16, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
                                    .addComponent(jTextField15)))
                            .addGroup(jPanel7Layout.createSequentialGroup()
                                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel14)
                                    .addComponent(jLabel16)
                                    .addComponent(jLabel17))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 55, Short.MAX_VALUE)
                                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jTextField14, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jTextField13, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel7Layout.createSequentialGroup()
                                        .addComponent(jTextField10, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel15, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jTextField11, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel7Layout.createSequentialGroup()
                                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel20)
                                    .addComponent(jLabel21))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jTextField17)
                                    .addComponent(jTextField18, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(jPanel7Layout.createSequentialGroup()
                                .addComponent(jTextField12, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jCheckBox3)
                                    .addComponent(jCheckBox2)
                                    .addComponent(jCheckBox1))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 152, Short.MAX_VALUE)
                        .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButton12, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jButton15, javax.swing.GroupLayout.Alignment.TRAILING))))
                .addContainerGap())
        );
        jPanel7Layout.setVerticalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel7Layout.createSequentialGroup()
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel7Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel14)
                            .addComponent(jTextField10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextField11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel15)
                            .addComponent(jCheckBox3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextField13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel16)
                            .addComponent(jTextField12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jCheckBox1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextField14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel17)
                            .addComponent(jCheckBox2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextField15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel18))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextField16, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel19)))
                    .addGroup(jPanel7Layout.createSequentialGroup()
                        .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel7Layout.createSequentialGroup()
                                .addGap(90, 90, 90)
                                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jTextField18, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel20)))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel7Layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jButton15, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextField17, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel21)
                            .addComponent(jButton12))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton9)
                .addContainerGap(30, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("MapGen2", jPanel7);

        jLabel22.setText("Size");

        jTextField19.setText("100");

        jTextField21.setToolTipText("Seed which was used!");

        jLabel24.setText("Seed");

        jTextField22.setText("50");
        jTextField22.setToolTipText("");

        jLabel25.setText("Faults");

        jLabel26.setText("Percent water");

        jLabel27.setText("Percent ice");

        jTextField23.setText("10");
        jTextField23.setToolTipText("from 1-100");

        jTextField26.setText("60");
        jTextField26.setToolTipText("from 1-100");

        jTextField27.setText("1000");
        jTextField27.setToolTipText("about 500-20000");

        jButton10.setText("Generate Image");
        jButton10.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton10ActionPerformed(evt);
            }
        });

        jButton13.setText("Origin ");
        jButton13.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton13ActionPerformed(evt);
            }
        });

        jButton16.setText("Build Layer");
        jButton16.setEnabled(false);

        javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
        jPanel8.setLayout(jPanel8Layout);
        jPanel8Layout.setHorizontalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel8Layout.createSequentialGroup()
                .addContainerGap(598, Short.MAX_VALUE)
                .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton13, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton16, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
            .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel8Layout.createSequentialGroup()
                    .addGap(11, 11, 11)
                    .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel8Layout.createSequentialGroup()
                            .addGap(0, 0, Short.MAX_VALUE)
                            .addComponent(jButton10))
                        .addGroup(jPanel8Layout.createSequentialGroup()
                            .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addGroup(jPanel8Layout.createSequentialGroup()
                                    .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabel26)
                                        .addComponent(jLabel27))
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(jTextField23, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
                                        .addComponent(jTextField26)))
                                .addGroup(jPanel8Layout.createSequentialGroup()
                                    .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabel22)
                                        .addComponent(jLabel24)
                                        .addComponent(jLabel25))
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 54, Short.MAX_VALUE)
                                    .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jTextField27, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jTextField22, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel8Layout.createSequentialGroup()
                                            .addComponent(jTextField19, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addGap(73, 73, 73)))))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jTextField21, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(212, 212, 212)))
                    .addGap(12, 12, 12)))
        );
        jPanel8Layout.setVerticalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel8Layout.createSequentialGroup()
                .addContainerGap(82, Short.MAX_VALUE)
                .addComponent(jButton16, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton13)
                .addGap(45, 45, 45))
            .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel8Layout.createSequentialGroup()
                    .addGap(11, 11, 11)
                    .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel22)
                        .addComponent(jTextField19, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jTextField22, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel24)
                        .addComponent(jTextField21, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jTextField27, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel25))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jTextField26, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel26))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jTextField23, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel27))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
                    .addComponent(jButton10)
                    .addGap(12, 12, 12)))
        );

        jTabbedPane1.addTab("World Gen", null, jPanel8, "");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(singleImagePanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 699, Short.MAX_VALUE)
                    .addComponent(jTabbedPane1))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jPanel5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jPanel18, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel18, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addComponent(singleImagePanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 313, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jTextFieldImageSourceFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldImageSourceFocusLost
        if (jTextFieldImageSource.getText().trim().length()==0) return;
        setImage();
    }//GEN-LAST:event_jTextFieldImageSourceFocusLost

    private void jButtonFileSelectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonFileSelectActionPerformed

        InternalFrameFileChoser fc = new csa.gui.dialogs.InternalFrameFileChoser();
        fc.setMultiSelectionEnabled(false);
        fc.setCurrentDirectory(new java.io.File("."));
        fc.setCurrentDirectory(new java.io.File("images"));
        FileNameExtensionFilter  filter = new  FileNameExtensionFilter("Images", "jpg", "jpeg", "png", "bmp", "gif");
        fc.setFileFilter(filter);
        int r = fc.showOpenDialog(Configuration.getConfiguration().getMainFrame());
        if (r != InternalFrameFileChoser.APPROVE_OPTION) return;
        String fullPath = fc.getSelectedFile().getAbsolutePath();
        jTextFieldImageSource.setText(csa.util.Utility.makeRelative(fullPath));
        setImage();
        inSetting++;
        //singleImagePanel1.setScale(1);

        jTextField3.setText(""+singleImagePanel1.getSourceWidth());
        jTextField4.setText(""+singleImagePanel1.getSourceHeight());
        invalidate();
        validate();
        repaint();
        inSetting--;
    }//GEN-LAST:event_jButtonFileSelectActionPerformed

    // adds to the out24 image the alpha channels of the org image
    private BufferedImage addAlpha(BufferedImage orgImage, BufferedImage out24)
    {
        int width = orgImage.getWidth();
        int height = orgImage.getHeight();
        BufferedImage newImage = csa.util.UtilityImage.toAlpha(out24);

        for (int row = 0; row < height; row++) {
           for (int col = 0; col < width; col++)
           {
                int orgAlpha = (orgImage.getRGB(col, row) >> 24) & 0xFF;
                int rgba =newImage.getRGB(col, row);
                rgba = (rgba &0xffffff);

                rgba = rgba + ((orgAlpha& 0xFF) << 24);
                newImage.setRGB(col, row, rgba);
           }
        }
        return newImage;
    }


    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        if (orgImage==null) return;
        OctTreeQuantizer quant = new OctTreeQuantizer(csa.util.UtilityString.IntX(jTextField1.getText(), 2));
        int[] pixels = convertTo2DUsingGetRGB(orgImage);
        quant.addPixels(pixels, 0, pixels.length);
	int[] ctable = quant.buildColorTable();

        int width = orgImage.getWidth();
        int height = orgImage.getHeight();
        int[] newPixels = new int[height*width];
        int c = 0;
        for (int row = 0; row < height; row++) {
           for (int col = 0; col < width; col++)
           {
                int rgba =orgImage.getRGB(col, row);
                int orgAlpha = (rgba >> 24) & 0xFF;
                int color = ctable[quant.getIndexForColor(pixels[c])];
                // delete old Alpha
                color = (color &0xffffff);

                color = color + ((orgAlpha& 0xFF) << 24);

               newPixels[c] = color;
              c++;
           }
        }

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        WritableRaster wr = image.getRaster();
        wr.setDataElements(0, 0, width, height, newPixels);
        singleImagePanel1.setImage(image);
        if (jCheckBoxScaled.isSelected())
            singleImagePanel1.setScale(singleImagePanel1.getWidth(), singleImagePanel1.getHeight());
        else
            singleImagePanel1.setScale(1);

        showColorCount(image);
        invalidate();
        validate();
        repaint();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void singleImagePanel1ComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_singleImagePanel1ComponentResized
        if (jCheckBoxScaled.isSelected())
            singleImagePanel1.setScale(singleImagePanel1.getWidth(), singleImagePanel1.getHeight());
        invalidate();
        validate();
        repaint();
    }//GEN-LAST:event_singleImagePanel1ComponentResized

    private void jButtonFileSelect1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonFileSelect1ActionPerformed
        InternalFrameFileChoser fc = new csa.gui.dialogs.InternalFrameFileChoser();
        fc.setCurrentDirectory(new java.io.File("xml"+File.separator+"Tile"));
        FileNameExtensionFilter  filter = new  FileNameExtensionFilter("xml", "xml");
        fc.setFileFilter(filter);
        int r = fc.showOpenDialog(Configuration.getConfiguration().getMainFrame());
        if (r != InternalFrameFileChoser.APPROVE_OPTION) return;
        String name = fc.getSelectedFile().getName();
        jTextFieldTileFile.setText(csa.util.UtilityString.replace(name, ".xml",""));
        jTextFieldTileFileActionPerformed(null);
    }//GEN-LAST:event_jButtonFileSelect1ActionPerformed

    private void jTextFieldTileFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldTileFileActionPerformed
        loadTileCollection();
    }//GEN-LAST:event_jTextFieldTileFileActionPerformed
    public void loadTileCollection()
    {
        String file = jTextFieldTileFile.getText().trim();
        if (file.length() == 0) return;

        mTileDataPool = new TileDataPool("Tile"+File.separator+file+".xml");
        if (mTileDataPool == null) return;
        String _class = "";
        if (jComboBoxTileKlasse.getSelectedIndex() !=-1)
             _class = jComboBoxTileKlasse.getSelectedItem().toString().trim();
        resetTileConfigPool(true, _class, "");
    }

    // Config Pool for TileMap
    private void resetTileConfigPool(boolean select, String klasseToSet, String tileToSet) /* allneeded*/
    {
        mClassSetting++;
        jComboBoxTileKlasse.removeAllItems();
        mClassSetting--;

        if (mTileDataPool == null) return;

        mClassSetting++;
        Collection<String> collectionKlasse = mTileDataPool.getKlassenHashMap().values();
        Iterator<String> iterKlasse = collectionKlasse.iterator();
        int i = 0;
        String klasse = "";

        while (iterKlasse.hasNext())
        {
            String item = iterKlasse.next();
            jComboBoxTileKlasse.addItem(item);
            if (select)
            {
                if (klasseToSet.length()==0)
                {
                    if (i==0)
                    {
                        jComboBoxTileKlasse.setSelectedIndex(i);
                        klasse = item;
                    }
                }
                else
                {
                    if (klasseToSet.equalsIgnoreCase(item))
                    {
                        jComboBoxTileKlasse.setSelectedIndex(i);
                        klasse = item;
                    }
                }
            }
            i++;
        }
        if ((select) && (klasse.length()==0))
        {
            if (jComboBoxTileKlasse.getItemCount()>0)
            {
                jComboBoxTileKlasse.setSelectedIndex(0);
                klasse = jComboBoxTileKlasse.getSelectedItem().toString();
            }
        }
        if (!select)  jComboBoxTileKlasse.setSelectedIndex(-1);

        mClassSetting--;

        resetTileList(tileToSet);
    }
    String getTileClass()
    {
        String _class  = "";
        if (jComboBoxTileKlasse.getSelectedIndex()!=-1)
            _class  = jComboBoxTileKlasse.getSelectedItem().toString();
        return _class;
    }

    ImageSequenceData getImageSequenceDataForTile(TileData tileData)
    {
        if (tileData.getImageDataFile().trim().length()==0) return null;

        String imageFilename = "Graphics"+File.separator+tileData.getImageDataFile()+".xml";
        ImageSequenceDataPool imagePool = new ImageSequenceDataPool(imageFilename);
        if (imagePool == null) return null;
        String nameToSet = tileData.getImageDataName();

        return imagePool.get(nameToSet);
    }
    void resetTileList(String selectName)
    {
        mAllTilesInClass = new Vector <TileData>();

        String _class = getTileClass();

        if (mTileDataPool == null) return;

        Collection<TileData> colDk = mTileDataPool.getMapForKlasse(_class).values();
        Iterator<TileData> iterDk = colDk.iterator();
        /** Sorting */  Vector<String> names = new Vector<String>();
        while (iterDk.hasNext())
        {
            TileData deck = iterDk.next();
            mAllTilesInClass.addElement(deck);
            names.addElement(deck.mName);

        }
        Collections.sort(names, new Comparator<String>() {@Override
                public int compare(String s1, String s2) { return s1.compareTo(s2); } });
        Collections.sort(mAllTilesInClass, new Comparator<TileData>() {@Override
            public int compare(TileData s1, TileData s2) { return s1.mName.compareTo(s2.mName); } });
        setAllTiles(selectName);
    }
    void setAllTiles(String selectName)
    {
        jPanelIMageCollection2.removeAll();

        int selected = 0;
        for (int t = 0; t < mAllTilesInClass.size(); t++)
        {
            TileData tileData = mAllTilesInClass.elementAt(t);
            if (tileData.mName.equals(selectName))
            {
                selected = t;
                break;
            }
        }
        int x = 5;
        int y = 5;
        for (int t = 0; t < mAllTilesInClass.size(); t++)
        {
            TileData tileData = mAllTilesInClass.elementAt(t);
            // jPanelIMageCollection1

            ImageSequenceData iSData = getImageSequenceDataForTile(tileData);
            String name = tileData.mName;

            JPanel ipanel = new JPanel();

            ipanel.setName(""+name);
            ipanel.setPreferredSize(new java.awt.Dimension(52, 52));
            ipanel.setLayout(new BorderLayout());

            ImageComponent mip = new ImageComponent();
            ipanel.add(mip, BorderLayout.CENTER);


            mip.addMouseListener(new java.awt.event.MouseAdapter() {
                @Override
                public void mousePressed(java.awt.event.MouseEvent evt) {
                    notDragged = true;
                }
                public void mouseReleased(java.awt.event.MouseEvent evt) {
                }
            });
                /////////////////
            class MyTransferHandler extends TransferHandler
            {
                JPanel me;
                public MyTransferHandler(JPanel c)
                {
                    me = c;
                }
                public int getSourceActions(JComponent c)
                {
                    return TransferHandler.MOVE;
                }
                public  Transferable createTransferable(JComponent c)
                {
                    return new StringSelection(me.getName());
                }
                public void exportDone(JComponent source, Transferable data, int action)
                {

                }
            }

            mip.setTransferHandler(new MyTransferHandler(ipanel));
            mip.addMouseMotionListener(new MouseMotionListener(){
                @Override
                public void mouseDragged(MouseEvent e)
                {
                    notDragged = false;
                    e.consume();
                    JComponent c =(JComponent) e.getSource();
                    TransferHandler handler = c.getTransferHandler();
                    handler.exportAsDrag(c,e,TransferHandler.MOVE);
                    System.out.println("Draging?");
                }
                @Override public void mouseMoved(MouseEvent e) { }
            });

            ipanel.setBounds(x, y, 52, 52);
            jPanelIMageCollection2.add(ipanel);
            if (iSData != null)
            {
                Vector <BaseImageData> data = BaseImageData.toBase(iSData);
                if (data.size()>0)
                {
                    Vector<Image> images = new Vector<Image>();
                    for (int i = 0; i < data.size(); i++)
                    {
                        BaseImageData baseImageData = data.elementAt(i);
                        images.addElement(baseImageData.image);
                    }
                    mip.setSequence(new ImageSequence(iSData));
                    mip.setDelay(iSData.getDelay());
                }
            }
            y += 52;
            y += 5;
            mip.setScaled(true, 52, 52);
            mip.setVisible(true);
        }

        jPanelIMageCollection2.setBounds(0,0,62,y);
        jPanelIMageCollection2.setPreferredSize(new Dimension(62,y));
        jPanelIMageCollection2.invalidate();
        jPanelIMageCollection2.validate();
        jPanelIMageCollection2.repaint();


        repaint();
        // TODO
    }
    private void jTextFieldTileFileFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldTileFileFocusLost
        // if enabled, switching to another tab also loses focus
        //jTextFieldTileFileActionPerformed(null);
    }//GEN-LAST:event_jTextFieldTileFileFocusLost

    private void jComboBoxTileKlasseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxTileKlasseActionPerformed
        if (mClassSetting >0 ) return;
        mClassSetting++;
        String selected = jComboBoxTileKlasse.getSelectedItem().toString();
        resetTileConfigPool(true, selected, "");
        mClassSetting--;
    }//GEN-LAST:event_jComboBoxTileKlasseActionPerformed

    private void jCheckBoxScaledActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxScaledActionPerformed
        if (jCheckBoxScaled.isSelected())
            singleImagePanel1.setScale(singleImagePanel1.getWidth(), singleImagePanel1.getHeight());
        else
            singleImagePanel1.setScale(1);
        invalidate();
        validate();
        repaint();
    }//GEN-LAST:event_jCheckBoxScaledActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        BufferedRGB24Image image = new BufferedRGB24Image(orgImage);
        BufferedImage out = new BufferedImage(orgImage.getWidth(), orgImage.getHeight(), BufferedImage.TYPE_INT_RGB);
        BufferedRGB24Image out24 = new BufferedRGB24Image(out);

        MedianCutQuantizer quantizer = new MedianCutQuantizer();
        quantizer.setInputImage(image);
        quantizer.setPaletteSize(csa.util.UtilityString.IntX(jTextField1.getText(), 2));
        try
        {
            quantizer.process();
            quantizer.mapImage(image, out24);

            BufferedImage outAlpha = addAlpha(orgImage, out);

            singleImagePanel1.setImage(outAlpha);
            if (jCheckBoxScaled.isSelected())
                singleImagePanel1.setScale(singleImagePanel1.getWidth(), singleImagePanel1.getHeight());
            else
                singleImagePanel1.setScale(1);

            showColorCount(out);
            invalidate();
            validate();
            repaint();
        }
        catch (Throwable e)
        {
            e.printStackTrace();
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        BufferedRGB24Image image = new BufferedRGB24Image(orgImage);

        PopularityQuantizer  quantizer = new PopularityQuantizer ();
        quantizer.setInputImage(image);
        quantizer.setPaletteSize(csa.util.UtilityString.IntX(jTextField1.getText(), 2));
        try
        {
            quantizer.process();
            BufferedImage newImage = new BufferedImage(orgImage.getWidth(), orgImage.getHeight(), BufferedImage.TYPE_INT_ARGB);


            int width = orgImage.getWidth();
            int height = orgImage.getHeight();

            int[] mapIn = new int[3];
            int[] mapOut = new int[3];
            for (int row = 0; row < height; row++) {
               for (int col = 0; col < width; col++)
               {
                    int rgba=orgImage.getRGB(col, row);
                    int orgAlpha = (rgba >> 24) & 0xFF;
                    int rgb = (rgba &0xffffff);

                    mapIn[0] = rgba & 0xff;
                    mapIn[1] = (rgba >>8)& 0xff;
                    mapIn[2] = (rgba >>16)& 0xff;

                    quantizer.map(mapIn, mapOut);
                    rgba =  (mapOut[0]);
                    rgba += (mapOut[1]<<8);
                    rgba += (mapOut[2]<<16);
                    rgba += ((orgAlpha& 0xFF) << 24);
                    newImage.setRGB(col, row, rgba);
               }
            }

            singleImagePanel1.setImage(newImage);
            if (jCheckBoxScaled.isSelected())
                singleImagePanel1.setScale(singleImagePanel1.getWidth(), singleImagePanel1.getHeight());
            else
                singleImagePanel1.setScale(1);

            showColorCount(newImage);
            invalidate();
            validate();
            repaint();
        }
        catch (Throwable e)
        {
            e.printStackTrace();
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        BufferedRGB24Image image = new BufferedRGB24Image(orgImage);

        OctreeColorQuantizer  quantizer = new OctreeColorQuantizer ();
        quantizer.setInputImage(image);
        quantizer.setPaletteSize(csa.util.UtilityString.IntX(jTextField1.getText(), 2));
        try
        {
            quantizer.process();
            BufferedImage newImage = new BufferedImage(orgImage.getWidth(), orgImage.getHeight(), BufferedImage.TYPE_INT_ARGB);


            int width = orgImage.getWidth();
            int height = orgImage.getHeight();

            int[] mapIn = new int[3];
            int[] mapOut = new int[3];
            for (int row = 0; row < height; row++) {
               for (int col = 0; col < width; col++)
               {
                    int rgba=orgImage.getRGB(col, row);
                    int orgAlpha = (rgba >> 24) & 0xFF;
                    int rgb = (rgba &0xffffff);

                    mapIn[0] = rgba & 0xff;
                    mapIn[1] = (rgba >>8)& 0xff;
                    mapIn[2] = (rgba >>16)& 0xff;

                    quantizer.map(mapIn, mapOut);
                    rgba =  (mapOut[0]);
                    rgba += (mapOut[1]<<8);
                    rgba += (mapOut[2]<<16);
                    rgba += ((orgAlpha& 0xFF) << 24);
                    newImage.setRGB(col, row, rgba);
               }
            }

            singleImagePanel1.setImage(newImage);
            if (jCheckBoxScaled.isSelected())
                singleImagePanel1.setScale(singleImagePanel1.getWidth(), singleImagePanel1.getHeight());
            else
                singleImagePanel1.setScale(1);

            showColorCount(newImage);
            invalidate();
            validate();
            repaint();
        }
        catch (Throwable e)
        {
            e.printStackTrace();
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        if (orgImage==null) return;

        //int width = image.getWidth();
        //int height = image.getHeight();
        //int[][] result = new int[width][height];
        int[][] pixels = convertTo2DUsingGetRGB_2(orgImage);
        int colors[];
        colors = ImageMagicQuantasize.quantizeImage(pixels, csa.util.UtilityString.IntX(jTextField1.getText(),2));


        int width = orgImage.getWidth();
        int height = orgImage.getHeight();

        for (int row = 0; row < height; row++) {
           for (int col = 0; col < width; col++)
           {
                int rgba =orgImage.getRGB(col, row);
                int orgAlpha = (rgba >> 24) & 0xFF;
                int newRGB = colors[pixels[col][row]];

                // delete old Alpha
                newRGB = (newRGB &0xffffff);
                newRGB = newRGB + ((orgAlpha& 0xFF) << 24);

                pixels[col][row] = newRGB;
           }
        }

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        WritableRaster wr = image.getRaster();
        wr.setDataElements(0, 0, width, height, toSingleArray(pixels));
        singleImagePanel1.setImage(image);
        if (jCheckBoxScaled.isSelected())
            singleImagePanel1.setScale(singleImagePanel1.getWidth(), singleImagePanel1.getHeight());
        else
            singleImagePanel1.setScale(1);

        showColorCount(image);
        invalidate();
        validate();
        repaint();


    }//GEN-LAST:event_jButton5ActionPerformed

    private void jComboBoxKlasseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxKlasseActionPerformed
        if (mClassSetting >0 ) return;
        mClassSetting++;;

        String selected = jComboBoxKlasse.getSelectedItem().toString();
        clearAll();
        resetConfigPool(true, selected);
        jTextFieldKlasse.setText(jComboBoxKlasse.getSelectedItem().toString());
        String key = jComboBoxName.getSelectedItem().toString();
        currentColorTileMap = mColorTileMapPool.get(key);
        setAllFromCurrent();
        mClassSetting--;
    }//GEN-LAST:event_jComboBoxKlasseActionPerformed

    private void jComboBoxNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxNameActionPerformed
        if (mClassSetting > 0 ) return;
        String key = jComboBoxName.getSelectedItem().toString();
        currentColorTileMap = mColorTileMapPool.get(key);
        setAllFromCurrent();
    }//GEN-LAST:event_jComboBoxNameActionPerformed

    private void jButtonNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNewActionPerformed
        mClassSetting++;
        currentColorTileMap = new ColorTileMap();
        clearAll();
        resetConfigPool(false, "");
        mClassSetting--;
    }//GEN-LAST:event_jButtonNewActionPerformed

    private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSaveActionPerformed

        readAllToCurrent();
        mColorTileMapPool.put(currentColorTileMap);
        mColorTileMapPool.save();
        mClassSetting++;
        String klasse = jTextFieldKlasse.getText();
        resetConfigPool(true, klasse);
        jComboBoxName.setSelectedItem(currentColorTileMap.mName);
        mClassSetting--;
    }//GEN-LAST:event_jButtonSaveActionPerformed

    private void jButtonDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDeleteActionPerformed
        readAllToCurrent();
        mColorTileMapPool.remove(currentColorTileMap);
        mColorTileMapPool.save();
        mClassSetting++;
        String klasse = jTextFieldKlasse.getText();
        resetConfigPool(true,klasse);

        if (jComboBoxName.getSelectedIndex() == -1)
        {
            clearAll();
            return;
        }

        String key = jComboBoxName.getSelectedItem().toString();
        currentColorTileMap = mColorTileMapPool.get(key);
        setAllFromCurrent();

        mClassSetting--;
    }//GEN-LAST:event_jButtonDeleteActionPerformed

    private void jButtonSaveAsNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSaveAsNewActionPerformed
        currentColorTileMap = new ColorTileMap();
        readAllToCurrent();
        mColorTileMapPool.putAsNew(currentColorTileMap);
        mColorTileMapPool.save();
        mClassSetting++;
        String klasse = jTextFieldKlasse.getText();
        resetConfigPool(true,klasse);
        jComboBoxName.setSelectedItem(currentColorTileMap.mName);
        mClassSetting--;
    }//GEN-LAST:event_jButtonSaveAsNewActionPerformed

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
        if (orgImage != null)
            setImage(orgImage);
    }//GEN-LAST:event_jButton7ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        showColorCount(singleImagePanel1.getImage());
    }//GEN-LAST:event_jButton6ActionPerformed

    
    HashMap<String, TileDataPool> poolCash = new HashMap<String, TileDataPool>();

    TileDataPool getPool(String name)
    {
        TileDataPool pool = poolCash.get(name);
        if (pool == null)
        {
            pool = new TileDataPool(name);
            poolCash.put(name, pool);

        }
        return pool;
    }

    
    TileData getTile(String filename, String name)
    {
        TileData data = tileCache.get(filename+name);
        if ( data != null)
        {
            if ((data.getVariantNames().size()==0)  || (data.getVariantPercent()==0)) 
                return data;
        }
        TileDataPool localTileDataPool = getPool("Tile"+File.separator+filename+".xml");
        if (localTileDataPool == null) return null;

        if (data == null)
            data = localTileDataPool.get(name);
        
        if (data.getVariantNames().size()>0) 
        {
            int r = csa.Global.getRand().nextInt(100); // percent
            if (r<data.getVariantPercent())
            {
                int t = csa.Global.getRand().nextInt(data.getVariantNames().size()); // percent

                name = data.getVariantNames().elementAt(t);
                TileData data2 = tileCache.get(filename+name);
                if (data2 == null)
                    data2 = localTileDataPool.get(data.getVariantNames().elementAt(t));
                data = data2;
            }
        }
                
        tileCache.put(filename+name, data);
        return  data;
    }

    //tileCache = new HashMap<String, TileData>();
    private TileData getNearestRGBTile(int rgb, ColorTileMap actualColorTileMap)
    {
        int background = -1;
        if (currentBackground != null)
            background = currentBackground.getRGB()& 0xffffff;
        double colorDistance = Double.MAX_VALUE;
        TileData data = null;
        int b = (rgb    ) & 0xff;
        int g = (rgb>> 8) & 0xff;
        int r = (rgb>>16) & 0xff;
        int index = -1;

        for (int i = 0; i < actualColorTileMap.mColor.size(); i++)
        {
            int tileRGB =  actualColorTileMap.mColor.elementAt(i) & 0xffffff;

            int tb = (tileRGB    ) & 0xff;
            int tg = (tileRGB>> 8) & 0xff;
            int tr = (tileRGB>>16) & 0xff;

            double dist = Math.sqrt( Math.pow((tr-r),2) + Math.pow((tg-g),2) + Math.pow((tb-b),2) );
            if (dist<colorDistance)
            {
                colorDistance = dist;
                index = i;
            }
        }

        if (index != -1)
        {
            int tileRGB = actualColorTileMap.mColor.elementAt(index)& 0xffffff;

            // backkround
            if (tileRGB == background) return null;
            if (rgb == background) return null;

            if ((actualColorTileMap.mTileFile.elementAt(index) == null) || (actualColorTileMap.mTileFile.elementAt(index).trim().length())==0)
            {
                return null;
            }
            else
                data = getTile(actualColorTileMap.mTileFile.elementAt(index), actualColorTileMap.mTileName.elementAt(index));
        }
        return data;
    }

    private TileData getRGBTile(int rgb, ColorTileMap actualColorTileMap)
    {
        int background = -1;
        if (currentBackground != null)
            background = currentBackground.getRGB()& 0xffffff;
        TileData data = null;
        int b = (rgb    ) & 0xff;
        int g = (rgb>> 8) & 0xff;
        int r = (rgb>>16) & 0xff;
        int index = -1;

        for (int i = 0; i < actualColorTileMap.mColor.size(); i++)
        {
            int tileRGB =  actualColorTileMap.mColor.elementAt(i) & 0xffffff;

            int tb = (tileRGB    ) & 0xff;
            int tg = (tileRGB>> 8) & 0xff;
            int tr = (tileRGB>>16) & 0xff;

            if ((r==tr) && (g==tg) && (b==tb))
            {
                index = i;
                break;
            }
        }

        if (index != -1)
        {
            int tileRGB = actualColorTileMap.mColor.elementAt(index)& 0xffffff;

            // backkround
            if (tileRGB == background) return null;
            if (rgb == background) return null;

            data = getTile(actualColorTileMap.mTileFile.elementAt(index), actualColorTileMap.mTileName.elementAt(index));
        }
        return data;
    }
    private void jButtonBuildMapActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBuildMapActionPerformed
        if (orgImage==null) return;

        poolCash = new HashMap<String, TileDataPool>();
        
        
        // width / height used to calc tile positioning in new layer
        int tileWidth = 0;
        int tileHeight = 0;
        boolean allSame = true;
        if (jRadioButton1.isSelected())
        {
            tileWidth = csa.util.UtilityString.Int0(jTextFieldTileX.getText());
            tileHeight = csa.util.UtilityString.Int0(jTextFieldTileY.getText());
        }
        else
        {
            jRadioButton2ActionPerformed(null);
            tileWidth = csa.util.UtilityString.Int0(jTextFieldTileX.getText());
            tileHeight = csa.util.UtilityString.Int0(jTextFieldTileY.getText());
        }

        if ((tileWidth == 0) || (tileHeight==0)) return;

        // only color mappings, which realy have a tile associated
        ColorTileMap actualColorTileMap = new ColorTileMap();
        for (int i = 0; i < currentColorTileMap.mTileFile.size(); i++)
        {
            String fullName = (currentColorTileMap.mTileFile.elementAt(i)+currentColorTileMap.mTileName.elementAt(i)).trim();
            if ( fullName.length() == 0) continue;
            actualColorTileMap.mColor.addElement(currentColorTileMap.mColor.elementAt(i));
            actualColorTileMap.mTileFile.addElement(currentColorTileMap.mTileFile.elementAt(i));
            actualColorTileMap.mTileName.addElement(currentColorTileMap.mTileName.elementAt(i));
        }

        //private ColorTileMap currentColorTileMap =null;
        BufferedImage image = singleImagePanel1.getImage();
        tileCache = new HashMap<String, TileData>();

        int mapY=0;
        boolean complete = true;
        for (int y = 0; y < image.getHeight(); y++)
        {
            int mapX=0;
            for (int x = 0; x < image.getWidth(); x++)
            {
                int rgb = image.getRGB(x, y) & 0xffffff; // no alpha!

                TileData data = null;
                if (jCheckBoxUseNearest.isSelected())
                {
                    if (!jCheckBoxnNearestCanBeEmpty.isSelected())
                        data = getNearestRGBTile(rgb, actualColorTileMap);
                    else
                        data = getNearestRGBTile(rgb, currentColorTileMap);
                }
                else
                {
                    data = getRGBTile(rgb, actualColorTileMap);
                }

                if (data == null)
                {
                    mapX+=tileWidth;
                    complete = false;
                    continue;
                }
                else
                {
                    if (tileWidth != data.getWidth()) allSame = false;
                    if (tileHeight != data.getHeight()) allSame = false;
                }
                
                mLayer.addTile(data, mapX, mapY , true, null, false, false);
                
                mapX+=tileWidth;

            }
            mapY+=tileHeight;
        }
        mLayer.orderTiles();
        mLayer.getData().misLayerCompleteOrdered = complete;
        mLayer.getData().misAllTilesSameSize = allSame;
        mLayer.getData().misRegularGrid = allSame;
        mSuccessfull = true;
        mMPParent.buildAlgorythmLayerDone(this, mLayer);

        
        mLayer = new Layer();
        lcount++;
        String name ="Algorythm layer_"+lcount;
        mLayer.getData().mLayerName = name;
        mLayer.getData().mName = name;

    }//GEN-LAST:event_jButtonBuildMapActionPerformed
    int lcount=0;
    
    private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed

    }//GEN-LAST:event_jRadioButton1ActionPerformed

    private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton2ActionPerformed
        if (jRadioButton2.isSelected())
        {
            int tileWidth = 0;
            int tileHeight = 0;

            ColorTileMap actualColorTileMap = new ColorTileMap();
            for (int i = 0; i < currentColorTileMap.mTileFile.size(); i++)
            {
                String fullName = (currentColorTileMap.mTileFile.elementAt(i)+currentColorTileMap.mTileName.elementAt(i)).trim();
                if ( fullName.length() == 0) continue;
                actualColorTileMap.mColor.addElement(currentColorTileMap.mColor.elementAt(i));
                actualColorTileMap.mTileFile.addElement(currentColorTileMap.mTileFile.elementAt(i));
                actualColorTileMap.mTileName.addElement(currentColorTileMap.mTileName.elementAt(i));

                if ((jRadioButton2.isSelected()) && (tileWidth == 0))
                {
                    TileData tData = getTile(currentColorTileMap.mTileFile.elementAt(i), currentColorTileMap.mTileName.elementAt(i));
                    if (tData != null)
                    {
                        tileWidth = tData. getWidth();
                        tileHeight = tData. getHeight();
                        break;
                    }
                }
            }
            jTextFieldTileX.setText(""+tileWidth);
            jTextFieldTileY.setText(""+tileHeight);
        }

    }//GEN-LAST:event_jRadioButton2ActionPerformed

    private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
        jTextField5.setBackground(textBack);
        jTextField5.setText("");
        jTextField5.setToolTipText("");
        currentBackground = null;
    }//GEN-LAST:event_jButton8ActionPerformed

    private void jButtonHeroBuildImageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonHeroBuildImageActionPerformed
        inSetting++;
        jTextFieldImageSource.setText("");
        inSetting--;

        final int w = csa.util.UtilityString.IntX(jTextField7.getText(), 800);
        final int h = csa.util.UtilityString.IntX(jTextField6.getText(), 600);

        Hemisphere sphere = Hemisphere.North;
        if (jComboBox1.getSelectedIndex() == 1)
            sphere = Hemisphere.South;
        else if (jComboBox1.getSelectedIndex() == 2)
            sphere = Hemisphere.Equator;

        WorldGenerator.SEA_LEVEL = csa.util.UtilityString.FloatX(jTextField20.getText(), (float) 0.33);
        WorldGenerator.RIVER_DENSITY = csa.util.UtilityString.FloatX(jTextField24.getText(), (float) 0.125);


        final csa.tiletools.worldgen.heroextant.maptoolkit.data.MapData<Double> elevation = new DenseMapData<Double>("Elevation", w, h);
        final csa.tiletools.worldgen.heroextant.maptoolkit.data.MapData<Double> temperature = new DenseMapData<Double>("Temperature", w, h);
        final csa.tiletools.worldgen.heroextant.maptoolkit.data.MapData<Double> windz = new DenseMapData<Double>("Wind", w, h);
        final csa.tiletools.worldgen.heroextant.maptoolkit.data.MapData<Double> rainfall = new DenseMapData<Double>("Rainfall", w, h);
        final csa.tiletools.worldgen.heroextant.maptoolkit.data.MapData<TileType> tiles = new DenseMapData<TileType>("TileType", w, h);
        final csa.tiletools.worldgen.heroextant.maptoolkit.data.MapData<Integer> waterSaturation = new DenseMapData<Integer>("Water Saturation", w, h);

        long seed = csa.util.UtilityString.LongX(jTextField8.getText(),0);

        csa.tiletools.worldgen.heroextant.maptoolkit.util.Random ran = new csa.tiletools.worldgen.heroextant.maptoolkit.util.Random();
        if (seed != 0)
            ran = new csa.tiletools.worldgen.heroextant.maptoolkit.util.Random(seed);

        long seedUsed = ran.getCurrentSeed();
        jTextField9.setText(""+seedUsed);
        final WorldGenerator world = new WorldGenerator(w, h, sphere, ran,
                elevation, temperature, windz, rainfall, tiles, waterSaturation);

        ElevationGenerationPhase.roughnessD = csa.util.UtilityString.FloatX(jTextField28.getText(), (float) 5);
        ElevationGenerationPhase.elevationD = csa.util.UtilityString.FloatX(jTextField25.getText(), (float) 0.5);


        world.execute();

        orgImage = world.renderWorldToImage();

        singleImagePanel1.setImage(orgImage);
        if (jCheckBoxScaled.isSelected())
            singleImagePanel1.setScale(singleImagePanel1.getWidth(), singleImagePanel1.getHeight());
        else
            singleImagePanel1.setScale(1);

        showColorCount(orgImage);

        inSetting++;
        jTextField3.setText(""+singleImagePanel1.getSourceWidth());
        jTextField4.setText(""+singleImagePanel1.getSourceHeight());
        invalidate();
        validate();
        repaint();
        inSetting--;

    }//GEN-LAST:event_jButtonHeroBuildImageActionPerformed

    private void jTextField6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField6ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField6ActionPerformed

    private void jTextField11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField11ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField11ActionPerformed

    private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed


        inSetting++;
        jTextFieldImageSource.setText("");
        inSetting--;

        final int w = csa.util.UtilityString.IntX(jTextField10.getText(), 800);
        final int h = csa.util.UtilityString.IntX(jTextField11.getText(), 600);


        long seed = csa.util.UtilityString.LongX(jTextField13.getText(),0);

        if (seed==0)
        {
            Random r = new Random();
            seed=r.nextLong();
        }

        try
        {
            MapGen.reset();
            MapGen MG = MapGen.MG;
            MG.height=h;
            MG.width=w;

            MG.smoothColors = jCheckBox1.isSelected();
            MG.createNoisyEdges = jCheckBox2.isSelected();
            MG.seed = seed;
            MG.pointsToGenerate = csa.util.UtilityString.IntX(jTextField14.getText(), 2000);
            MG.coastline = jCheckBox3.isSelected();

            MG.landMassFractionMin = csa.util.UtilityString.FloatX(jTextField15.getText(), (float) 0.3);
            MG.landMassFractionMax = csa.util.UtilityString.FloatX(jTextField18.getText(), (float) 0.7);
            MG.riversFraction = csa.util.UtilityString.FloatX(jTextField16.getText(), (float) 0.15);
            MG.lakeThreshold = csa.util.UtilityString.FloatX(jTextField17.getText(), (float) 0.3);




            boolean ok = MG.doGenerate();
            if (!ok)
            {
                // ERROR!
                // TODO:
                return;
            }
            orgImage = MG.getMapImage();
            jTextField12.setText(""+MG.getSeed());
        }
        catch (Throwable e)
        {
            e.printStackTrace();
        }


        singleImagePanel1.setImage(orgImage);
        if (jCheckBoxScaled.isSelected())
            singleImagePanel1.setScale(singleImagePanel1.getWidth(), singleImagePanel1.getHeight());
        else
            singleImagePanel1.setScale(1);

        showColorCount(orgImage);

        inSetting++;
        jTextField3.setText(""+singleImagePanel1.getSourceWidth());
        jTextField4.setText(""+singleImagePanel1.getSourceHeight());
        invalidate();
        validate();
        repaint();
        inSetting--;

    }//GEN-LAST:event_jButton9ActionPerformed

    private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
        // TODO add your handling code here:

        inSetting++;
        jTextFieldImageSource.setText("");
        inSetting--;

        final int w = csa.util.UtilityString.IntX(jTextField19.getText(), 800);
        final int h = csa.util.UtilityString.IntX(jTextField19.getText(), 600);


        long seed = csa.util.UtilityString.LongX(jTextField22.getText(),0);

        if (seed==0)
        {
            Random r = new Random();
            seed=r.nextLong();
        }

        try
        {
            WorldGen wg = new WorldGen();
            wg.XRange = w;
            wg.YRange = h;
            wg.Seed = seed;
            wg.NumberOfFaults = csa.util.UtilityString.IntX(jTextField27.getText(), 800);
            wg.PercentWater = csa.util.UtilityString.IntX(jTextField26.getText(), 50);
            wg.PercentIce = csa.util.UtilityString.IntX(jTextField23.getText(), 10);





            wg.generate();
            orgImage = wg.getImage();

            jTextField21.setText(""+seed);
        }
        catch (Throwable e)
        {
            e.printStackTrace();
        }


        singleImagePanel1.setImage(orgImage);
        if (jCheckBoxScaled.isSelected())
            singleImagePanel1.setScale(singleImagePanel1.getWidth(), singleImagePanel1.getHeight());
        else
            singleImagePanel1.setScale(1);

        showColorCount(orgImage);

        inSetting++;
        jTextField3.setText(""+singleImagePanel1.getSourceWidth());
        jTextField4.setText(""+singleImagePanel1.getSourceHeight());
        invalidate();
        validate();
        repaint();
        inSetting--;
    }//GEN-LAST:event_jButton10ActionPerformed

    private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton11ActionPerformed
        String t="<html>";
        t+="World Generator taken from Hero Extant.<BR>";
        t+="Hero Extant<BR>Copyright (C) 2010 Ben Golightly (golightly.ben@googlemail.com)<BR>Licensed under GNU General Public License v3 (http://www.gnu.org/licenses/)<BR>";
        t+="See also:<BR> http://www.tophatstuff.co.uk/archive.php?p=99<BR> and <BR>https://github.com/avh4/hero-extant<BR>";

        t+="</html>";

        OriginJPanel.showOrigin(t, false);
    }//GEN-LAST:event_jButton11ActionPerformed

    private void jButton12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton12ActionPerformed
        String t="<html>";
        t+="MapGen.<BR>";
        t+="Procedural Map Generation, see Blog from Amit Patel,<BR>http://www.redblobgames.com/<BR>The original source is under the MIT license (http://opensource.org/licenses/mit-license.php) and available at: <BR>https://github.com/amitp/mapgen2<BR>";

        t+="<BR>The port to Java I used was done by Christophe Guebert, see: <BR> http://www.openprocessing.org/sketch/30809<BR><BR>";

        t+="</html>";

        OriginJPanel.showOrigin(t, false);
    }//GEN-LAST:event_jButton12ActionPerformed

    private void jButton13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton13ActionPerformed
        String t="<html>";
        t+="Fractal Worldmap Generator Version 2.1.<BR>Creator: John Olsson<BR>see: http://www.lysator.liu.se/~johol/fwmg/fwmg.html<BR>";
        t+="GNU General Public License v2 (http://www.gnu.org/licenses/)<BR><BR>";

        t+="<BR>I used the MSDOS port and transfered the code to java.<BR>";

        t+="</html>";

        OriginJPanel.showOrigin(t, false);
    }//GEN-LAST:event_jButton13ActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
       
        if ( SwingUtilities.isRightMouseButton( evt ))
        {
            Point p = evt.getPoint();
 
            // get the row index that contains that coordinate
            int rowNumber = jTable1.rowAtPoint( p );
            currentColorTileMap.mTileFile.insertElementAt("", rowNumber);            
            currentColorTileMap.mTileFile.removeElementAt(rowNumber+1);
            
            currentColorTileMap.mTileName.insertElementAt("", rowNumber);            
            currentColorTileMap.mTileName.removeElementAt(rowNumber+1);

            currentColorTileMap.mImages.insertElementAt(null, rowNumber);            
            currentColorTileMap.mImages.removeElementAt(rowNumber+1);

            jTable1.tableChanged(null);
            jTable1.setRowHeight(30);
            jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            jTable1.getColumnModel().getColumn(0).setPreferredWidth(80);
            jTable1.getColumnModel().getColumn(1).setPreferredWidth(40);
        }     
    }//GEN-LAST:event_jTable1MouseClicked

    private void jCheckBoxUseNearestActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxUseNearestActionPerformed
        jCheckBoxnNearestCanBeEmpty.setEnabled(jCheckBoxUseNearest.isSelected());
        
    }//GEN-LAST:event_jCheckBoxUseNearestActionPerformed

    private void jButtonBuildISOActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBuildISOActionPerformed
        
        // thought is
        // 
        
        if (orgImage==null) return;

        poolCash = new HashMap<String, TileDataPool>();
        
        
        // width / height used to calc tile positioning in new layer
        int tileWidth = 0;
        int tileHeight = 0;
        boolean allSame = true;
        if (jRadioButton1.isSelected())
        {
            tileWidth = csa.util.UtilityString.Int0(jTextFieldTileX.getText());
            tileHeight = csa.util.UtilityString.Int0(jTextFieldTileY.getText());
        }
        else
        {
            jRadioButton2ActionPerformed(null);
            tileWidth = csa.util.UtilityString.Int0(jTextFieldTileX.getText());
            tileHeight = csa.util.UtilityString.Int0(jTextFieldTileY.getText());
        }

        if ((tileWidth == 0) || (tileHeight==0)) return;

        // only color mappings, which realy have a tile associated
        ColorTileMap actualColorTileMap = new ColorTileMap();
        for (int i = 0; i < currentColorTileMap.mTileFile.size(); i++)
        {
            String fullName = (currentColorTileMap.mTileFile.elementAt(i)+currentColorTileMap.mTileName.elementAt(i)).trim();
            if ( fullName.length() == 0) continue;
            actualColorTileMap.mColor.addElement(currentColorTileMap.mColor.elementAt(i));
            actualColorTileMap.mTileFile.addElement(currentColorTileMap.mTileFile.elementAt(i));
            actualColorTileMap.mTileName.addElement(currentColorTileMap.mTileName.elementAt(i));
        }

        //private ColorTileMap currentColorTileMap =null;
        BufferedImage image = singleImagePanel1.getImage();
        tileCache = new HashMap<String, TileData>();

        int mapY=0;
        int mapX=0;
        boolean complete = true;
        boolean halfLine = false;
        
        for (int y = 0; y < image.getHeight(); y++)
        {
            if (halfLine)
            {
                mapX=tileWidth/2;
            }
            else
            {
                mapX=0;
            }
            
            for (int x = 0; x < image.getWidth(); x++)
            {
                int rgb = image.getRGB(x, y) & 0xffffff; // no alpha!
                
                TileData data = null;
                if (jCheckBoxUseNearest.isSelected())
                {
                    if (!jCheckBoxnNearestCanBeEmpty.isSelected())
                        data = getNearestRGBTile(rgb, actualColorTileMap);
                    else
                        data = getNearestRGBTile(rgb, currentColorTileMap);
                }
                else
                {
                    data = getRGBTile(rgb, actualColorTileMap);
                }

                if (data == null)
                {
                    mapX+=tileWidth;
                    complete = false;
                    continue;
                }
                else
                {
                    if (tileWidth != data.getWidth()) allSame = false;
                    if (tileHeight != data.getHeight()) allSame = false;
                }
                
                mLayer.addTile(data, mapX, mapY , true, null, false, false);
                
                mapX+=tileWidth;

            }
            halfLine = !halfLine;
            mapY+=tileHeight/2;
        }
        mLayer.orderTiles();
        mLayer.getData().misLayerCompleteOrdered = complete;
        mLayer.getData().misAllTilesSameSize = allSame;
        mLayer.getData().misRegularGrid = allSame;
        mSuccessfull = true;
        mMPParent.buildAlgorythmLayerDone(this, mLayer);

        mLayer = new Layer();
        lcount++;
        String name ="Algorythm layer_"+lcount;
        mLayer.getData().mLayerName = name;
        mLayer.getData().mName = name;
        
    }//GEN-LAST:event_jButtonBuildISOActionPerformed

    private void jButtonBuildISO1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBuildISO1ActionPerformed

        // thought is
        // 
        
        if (orgImage==null) return;

        poolCash = new HashMap<String, TileDataPool>();
        
        
        // width / height used to calc tile positioning in new layer
        int tileWidth = 0;
        int tileHeight = 0;
        boolean allSame = true;
        if (jRadioButton1.isSelected())
        {
            tileWidth = csa.util.UtilityString.Int0(jTextFieldTileX.getText());
            tileHeight = csa.util.UtilityString.Int0(jTextFieldTileY.getText());
        }
        else
        {
            jRadioButton2ActionPerformed(null);
            tileWidth = csa.util.UtilityString.Int0(jTextFieldTileX.getText());
            tileHeight = csa.util.UtilityString.Int0(jTextFieldTileY.getText());
        }

        if ((tileWidth == 0) || (tileHeight==0)) return;

        // only color mappings, which realy have a tile associated
        ColorTileMap actualColorTileMap = new ColorTileMap();
        for (int i = 0; i < currentColorTileMap.mTileFile.size(); i++)
        {
            String fullName = (currentColorTileMap.mTileFile.elementAt(i)+currentColorTileMap.mTileName.elementAt(i)).trim();
            if ( fullName.length() == 0) continue;
            actualColorTileMap.mColor.addElement(currentColorTileMap.mColor.elementAt(i));
            actualColorTileMap.mTileFile.addElement(currentColorTileMap.mTileFile.elementAt(i));
            actualColorTileMap.mTileName.addElement(currentColorTileMap.mTileName.elementAt(i));
        }

        //private ColorTileMap currentColorTileMap =null;
        BufferedImage image = singleImagePanel1.getImage();
        tileCache = new HashMap<String, TileData>();

        int mapY=0;
        int mapX=0;
        boolean complete = true;
        boolean halfLine = false;
        boolean halfColumn = false;
        for (int y = 0; y < image.getHeight(); y++)
        {
            if (halfLine)
            {
                mapX=0;//tileWidth/2;
            }
            else
            {
                mapX=0;
            }
            halfColumn = false;
            for (int x = 0; x < image.getWidth(); x++)
            {
                int rgb = image.getRGB(x, y) & 0xffffff; // no alpha!
                
                TileData data = null;
                if (jCheckBoxUseNearest.isSelected())
                {
                    if (!jCheckBoxnNearestCanBeEmpty.isSelected())
                        data = getNearestRGBTile(rgb, actualColorTileMap);
                    else
                        data = getNearestRGBTile(rgb, currentColorTileMap);
                }
                else
                {
                    data = getRGBTile(rgb, actualColorTileMap);
                }

                if (data == null)
                {
                    mapX+=tileWidth/2;
                    halfColumn = !halfColumn;
                    complete = false;
                    continue;
                }
                else
                {
                    if (tileWidth != data.getWidth()) allSame = false;
                    if (tileHeight != data.getHeight()) allSame = false;
                }
                if (!halfColumn)
                    mLayer.addTile(data, mapX, mapY , true, null, false, false);
                else
                    mLayer.addTile(data, mapX, mapY+tileHeight/2 , true, null, false, false);
                    
                mapX+=tileWidth/2;
                halfColumn = !halfColumn;

            }
            halfLine = !halfLine;
            mapY+=tileHeight;
        }
        mLayer.orderTiles();
        mLayer.getData().misLayerCompleteOrdered = complete;
        mLayer.getData().misAllTilesSameSize = allSame;
        mLayer.getData().misRegularGrid = allSame;
        mSuccessfull = true;
        mMPParent.buildAlgorythmLayerDone(this, mLayer);
        mLayer = new Layer();
        lcount++;
        String name ="Algorythm layer_"+lcount;
        mLayer.getData().mLayerName = name;
        mLayer.getData().mName = name;
        
    }//GEN-LAST:event_jButtonBuildISO1ActionPerformed

    private void jButtonBuildISO2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBuildISO2ActionPerformed
       
        // thought is
        // 
        
        if (orgImage==null) return;

        poolCash = new HashMap<String, TileDataPool>();
        
        
        // width / height used to calc tile positioning in new layer
        int tileWidth = 0;
        int tileHeight = 0;
        boolean allSame = true;
        if (jRadioButton1.isSelected())
        {
            tileWidth = csa.util.UtilityString.Int0(jTextFieldTileX.getText());
            tileHeight = csa.util.UtilityString.Int0(jTextFieldTileY.getText());
        }
        else
        {
            jRadioButton2ActionPerformed(null);
            tileWidth = csa.util.UtilityString.Int0(jTextFieldTileX.getText());
            tileHeight = csa.util.UtilityString.Int0(jTextFieldTileY.getText());
        }

        if ((tileWidth == 0) || (tileHeight==0)) return;

        // only color mappings, which realy have a tile associated
        ColorTileMap actualColorTileMap = new ColorTileMap();
        for (int i = 0; i < currentColorTileMap.mTileFile.size(); i++)
        {
            String fullName = (currentColorTileMap.mTileFile.elementAt(i)+currentColorTileMap.mTileName.elementAt(i)).trim();
            if ( fullName.length() == 0) continue;
            actualColorTileMap.mColor.addElement(currentColorTileMap.mColor.elementAt(i));
            actualColorTileMap.mTileFile.addElement(currentColorTileMap.mTileFile.elementAt(i));
            actualColorTileMap.mTileName.addElement(currentColorTileMap.mTileName.elementAt(i));
        }

        //private ColorTileMap currentColorTileMap =null;
        BufferedImage image = singleImagePanel1.getImage();
        tileCache = new HashMap<String, TileData>();

        int mapY=0;
        int mapX=0;
        boolean complete = true;
        int yPos = 0;
        for (int y = 0; y < image.getHeight(); y++)
        {
            mapX=0-(tileWidth/2)*yPos;
            mapY=0+(tileHeight/2)*yPos;
            for (int x = 0; x < image.getWidth(); x++)
            {
                int rgb = image.getRGB(x, y) & 0xffffff; // no alpha!
                
                TileData data = null;
                if (jCheckBoxUseNearest.isSelected())
                {
                    if (!jCheckBoxnNearestCanBeEmpty.isSelected())
                        data = getNearestRGBTile(rgb, actualColorTileMap);
                    else
                        data = getNearestRGBTile(rgb, currentColorTileMap);
                }
                else
                {
                    data = getRGBTile(rgb, actualColorTileMap);
                }

                if (data == null)
                {
                    mapX+=tileWidth/2;
                    mapY+=tileHeight/2;
                    complete = false;
                    continue;
                }
                else
                {
                    if (tileWidth != data.getWidth()) allSame = false;
                    if (tileHeight != data.getHeight()) allSame = false;
                }
                mLayer.addTile(data, mapX, mapY , true, null, false, false);
                    
                mapX+=tileWidth/2;
                mapY+=tileHeight/2;
            }
            yPos++;
        }
        mLayer.orderTiles();
        mLayer.getData().misLayerCompleteOrdered = complete;
        mLayer.getData().misAllTilesSameSize = allSame;
        mLayer.getData().misRegularGrid = allSame;
        mSuccessfull = true;
        mMPParent.buildAlgorythmLayerDone(this, mLayer);

        mLayer = new Layer();
        lcount++;
        String name ="Algorythm layer_"+lcount;
        mLayer.getData().mLayerName = name;
        mLayer.getData().mName = name;

                
        
    }//GEN-LAST:event_jButtonBuildISO2ActionPerformed

   javax.swing.table.TableModel getTableModel()
    {

        AbstractTableModel model = new
         AbstractTableModel() {
            @Override public String getColumnName(int col)
            {
                if (col==0) return "Color";
                if (col==1) return "Tile";
                return "";
            }
             @Override
            public int getRowCount()
            {
                if (currentColorTileMap == null) return 0;
                return currentColorTileMap.mColor.size();
            }
             @Override
            public int getColumnCount() { return 2;}
             @Override
            public Object getValueAt(int row, int col)
            {
                if (currentColorTileMap == null) return "";

                int color = currentColorTileMap.mColor.elementAt(row);
                if (col==0)
                {
                    Color c = new Color(color);
                    return c;
                    // return ""+c.getRed()+", "+c.getGreen()+", "+ c.getBlue();
                }
                BufferedImage tile = currentColorTileMap.mImages.elementAt(row);
                if (tile != null)
                {
                    if (displayAsImages)
                        if (col==1) return tile;
                    else
                        if (col==1) return currentColorTileMap.mTileFile.elementAt(row) +"->"+currentColorTileMap.mTileName.elementAt(row);
                }
                else
                    if (displayAsImages)
                        if (col==1) return null;
                return "";
            }
            @Override public boolean isCellEditable(int row, int col)
            {
                return false;
            }
            @Override public Class getColumnClass(int col)
            {
                if (col == 0) return Color.class;
                if (displayAsImages)
                    if (col == 1)
                        return BufferedImage.class;
                return String.class;
            }
        };
        return model;
    }
    int showColorCount(BufferedImage image)
    {
        return showColorCount(image, true);
    }
    int showColorCount(BufferedImage image, boolean vectorToMap)
    {
        if (image == null) return 0;
        int width = image.getWidth();
        int height = image.getHeight();
        HashMap<Integer, TileImageData> colors = new HashMap<Integer, TileImageData>();
        int[] pixels = convertTo2DUsingGetRGB(image);
        int c = 0;
        for (int row = 0; row < height; row++) {
           for (int col = 0; col < width; col++)
           {
              colors.put(pixels[c], null);
              c++;
           }
        }
        if (vectorToMap)
            currentColorTileMap = new ColorTileMap();

        Set entries = colors.entrySet();
        Iterator it = entries.iterator();
        while (it.hasNext())
        {
                Map.Entry entry = (Map.Entry) it.next();
                int key = (Integer) entry.getKey();

                currentColorTileMap.mColor.addElement(key);
                currentColorTileMap.mTileFile.addElement("");
                currentColorTileMap.mTileName.addElement("");
                currentColorTileMap.mImages.addElement(null);
        }

        mClassSetting++;
        jTextFieldKlasse.setText("");
        jTextFieldName.setText("");
        jComboBoxKlasse.setSelectedIndex(-1);
        jComboBoxName.setSelectedIndex(-1);
        mClassSetting--;

        jTextField2.setText(""+colors.size());
        jTable1.tableChanged(null);
        jTable1.setRowHeight(30);
        jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(80);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(40);
        return colors.size();
    }

    private static int[] convertTo2DUsingGetRGB(BufferedImage image)
    {
      int width = image.getWidth();
      int height = image.getHeight();
      int[] result = new int[height*width];

      int c = 0;
      for (int row = 0; row < height; row++) {
         for (int col = 0; col < width; col++) {
            result[c++] = image.getRGB(col, row);
         }
      }
      return result;
    }
    private static int[][] convertTo2DUsingGetRGB_2(BufferedImage image)
    {
      int width = image.getWidth();
      int height = image.getHeight();
      int[][] result = new int[width][height];

      for (int row = 0; row < height; row++) {
         for (int col = 0; col < width; col++) {
            result[col][row] = image.getRGB(col, row);
         }
      }
      return result;
    }

    private static int[] toSingleArray(int[][] pixels)
    {
        int width = pixels.length;
        int height = pixels[0].length;
        int[] result = new int[height*width];

        int c = 0;
        for (int row = 0; row < height; row++) {
           for (int col = 0; col < width; col++) {
              result[c++] = pixels[col][row];
           }
        }
        return result;
    }

    void setImage()
    {
        singleImagePanel1.setImage(jTextFieldImageSource.getText());
        orgImage = singleImagePanel1.getImage();
        if (jCheckBoxScaled.isSelected())
            singleImagePanel1.setScale(singleImagePanel1.getWidth(), singleImagePanel1.getHeight());
        else
            singleImagePanel1.setScale(1);

        showColorCount(orgImage);

        invalidate();
        validate();
        repaint();
    }
    void setImage(BufferedImage image)
    {
        inSetting++;
        jTextFieldImageSource.setText("");
        inSetting--;
        singleImagePanel1.setImage(image);
        orgImage = image;
        if (jCheckBoxScaled.isSelected())
            singleImagePanel1.setScale(singleImagePanel1.getWidth(), singleImagePanel1.getHeight());
        else
            singleImagePanel1.setScale(1);

        showColorCount(orgImage);

        invalidate();
        validate();
        repaint();
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton10;
    private javax.swing.JButton jButton11;
    private javax.swing.JButton jButton12;
    private javax.swing.JButton jButton13;
    private javax.swing.JButton jButton14;
    private javax.swing.JButton jButton15;
    private javax.swing.JButton jButton16;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JButton jButton8;
    private javax.swing.JButton jButton9;
    private javax.swing.JButton jButtonBuildISO;
    private javax.swing.JButton jButtonBuildISO1;
    private javax.swing.JButton jButtonBuildISO2;
    private javax.swing.JButton jButtonBuildMap;
    private javax.swing.JButton jButtonDelete;
    private javax.swing.JButton jButtonFileSelect;
    private javax.swing.JButton jButtonFileSelect1;
    private javax.swing.JButton jButtonHeroBuildImage;
    private javax.swing.JButton jButtonNew;
    private javax.swing.JButton jButtonSave;
    private javax.swing.JButton jButtonSaveAsNew;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JCheckBox jCheckBox2;
    private javax.swing.JCheckBox jCheckBox3;
    private javax.swing.JCheckBox jCheckBoxScaled;
    private javax.swing.JCheckBox jCheckBoxUseNearest;
    private javax.swing.JCheckBox jCheckBoxnNearestCanBeEmpty;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBoxKlasse;
    private javax.swing.JComboBox jComboBoxName;
    private javax.swing.JComboBox jComboBoxTileKlasse;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel21;
    private javax.swing.JLabel jLabel22;
    private javax.swing.JLabel jLabel24;
    private javax.swing.JLabel jLabel25;
    private javax.swing.JLabel jLabel26;
    private javax.swing.JLabel jLabel27;
    private javax.swing.JLabel jLabel28;
    private javax.swing.JLabel jLabel29;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel30;
    private javax.swing.JLabel jLabel31;
    private javax.swing.JLabel jLabel32;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel18;
    private javax.swing.JPanel jPanel19;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanelIMageCollection2;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane10;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField10;
    private javax.swing.JTextField jTextField11;
    private javax.swing.JTextField jTextField12;
    private javax.swing.JTextField jTextField13;
    private javax.swing.JTextField jTextField14;
    private javax.swing.JTextField jTextField15;
    private javax.swing.JTextField jTextField16;
    private javax.swing.JTextField jTextField17;
    private javax.swing.JTextField jTextField18;
    private javax.swing.JTextField jTextField19;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField20;
    private javax.swing.JTextField jTextField21;
    private javax.swing.JTextField jTextField22;
    private javax.swing.JTextField jTextField23;
    private javax.swing.JTextField jTextField24;
    private javax.swing.JTextField jTextField25;
    private javax.swing.JTextField jTextField26;
    private javax.swing.JTextField jTextField27;
    private javax.swing.JTextField jTextField28;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField6;
    private javax.swing.JTextField jTextField7;
    private javax.swing.JTextField jTextField8;
    private javax.swing.JTextField jTextField9;
    private javax.swing.JTextField jTextFieldImageSource;
    private javax.swing.JTextField jTextFieldKlasse;
    private javax.swing.JTextField jTextFieldName;
    private javax.swing.JTextField jTextFieldTileFile;
    private javax.swing.JTextField jTextFieldTileX;
    private javax.swing.JTextField jTextFieldTileY;
    private csa.tiletools.graphics.SingleImagePanel singleImagePanel1;
    // End of variables declaration//GEN-END:variables
}
