package main;

import java.awt.GraphicsEnvironment;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.FileOutputStream;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.Iterator;
import java.awt.geom.Point2D;
import java.util.Random;
import java.awt.image.ImageObserver;
import java.awt.Image;
import java.awt.Color;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.Shape;
import collision.Bound;
import java.awt.geom.Rectangle2D;
import utils.DynamicImage;
import gamegui.Button;
import gamegui.Align;
import gamegui.Member;
import gamegui.Label;
import java.awt.image.BufferStrategy;
import java.awt.GraphicsConfiguration;
import utils.Utils;
import java.awt.GraphicsDevice;
import java.awt.Point;
import java.util.ArrayList;
import java.util.HashMap;
import java.awt.Font;
import gamegui.Textbox;
import gamegui.ScrollBar;
import gamegui.Window;
import java.awt.Frame;
import java.awt.image.BufferedImage;
import java.awt.Graphics;
import java.awt.event.MouseListener;
import java.awt.event.KeyListener;

public class MapEditor implements KeyListener, MouseListener
{
    public static final int RES_X = 1024;
    public static final int RES_Y = 768;
    public static final int MAP_OFFSET_X = 204;
    public static final int MAP_OFFSET_Y = 148;
    private static final boolean RUNNING_FROM_JAR = false;
    public State state;
    public AuxState auxState;
    boolean started;
    boolean done;
    boolean showFps;
    int frameCount;
    int lastFrameCount;
    long lastFpsUpdate;
    Graphics g;
    BufferedImage mapBuffer;
    Graphics mapG;
    public static Frame frmMain;
    public static Map map;
    Window wndMain;
    Window wndEdit;
    Window wndEditPalette;
    Window wndEditOptions;
    Window wndDiagnostics;
    Window wndLoadMap;
    ScrollBar horBar;
    ScrollBar verBar;
    Window wndMessage;
    Textbox selectedText;
    Font font11;
    Font font12;
    Font font14;
    Font font24;
    Font fontTT;
    static final int LEVEL_ARROWS_OFFSET = 0;
    static final int SET_ARROWS_OFFSET = 50;
    HashMap<Integer, Tile> imageMap;
    HashMap<Integer, Creature> crMap;
    HashMap<Integer, GroundType[]> tileBreakdowns;
    ArrayList<Tile>[] tileByBreakdown;
    ArrayList<ArrayList<Tile>> imgSets;
    ArrayList<Tile> activeSet;
    int setIndex;
    Tile curTile;
    int curLevel;
    Tile selectedObject;
    Creature selectedCreature;
    String mapName;
    ArrayList<Creature> crSet;
    Creature curCr;
    boolean bounds;
    boolean passable;
    boolean showCr;
    boolean highLevelPlacement;
    Point playerLoc;
    Point start;
    
    public MapEditor(final GraphicsDevice device) {
        this.started = false;
        this.start = null;
        try {
            GraphicsConfiguration gc = device.getDefaultConfiguration();
            gc = device.getDefaultConfiguration();
            (MapEditor.frmMain = new Frame(gc)).setUndecorated(true);
            MapEditor.frmMain.setIgnoreRepaint(true);
            device.setFullScreenWindow(MapEditor.frmMain);
            if (device.isDisplayChangeSupported()) {
                Utils.chooseBestDisplayMode(device, 1024, 768);
            }
            MapEditor.frmMain.addMouseListener(this);
            MapEditor.frmMain.addKeyListener(this);
            MapEditor.frmMain.createBufferStrategy(2);
            final BufferStrategy bufferStrategy = MapEditor.frmMain.getBufferStrategy();
            this.g = bufferStrategy.getDrawGraphics();
            this.mapBuffer = gc.createCompatibleImage(800, 600);
            this.mapG = this.mapBuffer.getGraphics();
            Utils.init(gc, false);
            this.state = State.Main;
            this.auxState = AuxState.None;
            this.done = false;
            this.showFps = false;
            this.frameCount = 0;
            this.lastFrameCount = 0;
            this.lastFpsUpdate = System.nanoTime();
            this.setIndex = 0;
            this.curTile = null;
            this.curLevel = 0;
            this.selectedObject = null;
            this.selectedCreature = null;
            this.curCr = null;
            this.bounds = true;
            this.passable = false;
            this.showCr = false;
            this.highLevelPlacement = false;
            this.loadMap();
            this.loadCreatures();
            this.loadGUI();
            this.started = true;
            while (!this.done) {
                this.g = bufferStrategy.getDrawGraphics();
                this.handleEvents();
                this.render(this.g);
                this.g.dispose();
                bufferStrategy.show();
                ++this.frameCount;
                if (System.nanoTime() - 1000000000L >= this.lastFpsUpdate) {
                    this.lastFpsUpdate = System.nanoTime();
                    this.lastFrameCount = this.frameCount;
                    this.frameCount = 0;
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            return;
        }
        finally {
            device.setFullScreenWindow(null);
        }
        device.setFullScreenWindow(null);
    }
    
    private void loadGUI() {
        this.font11 = new Font("Arial", 0, 11);
        this.font12 = new Font("Arial", 0, 12);
        this.font24 = new Font("Arial", 0, 24);
        this.fontTT = new Font("Courier New", 0, 11);
        (this.wndMain = new Window("main", 0, 0, 1024, 768, true)).add(new Label("title", 256, 0, 512, 95, "Lost Haven Map Editor", this.font24));
        this.wndMain.add(new Button("new map", 668, 140, 200, 40, "New Map", this.font12, Align.Center));
        this.wndMain.add(new Button("load map", 668, 240, 200, 40, "Load Map", this.font12, Align.Center));
        this.wndMain.add(new Button("quit", 668, 340, 200, 40, "Quit", this.font12, Align.Center));
        this.wndEdit = new Window("edit", 0, 0, 1024, 768, true);
        (this.wndEditPalette = new Window("editPalette", 0, 0, 203, 767, false)).add(new Label("selected", 62, 10, 80, 20, "Selected Tile:", this.font12));
        this.wndEditPalette.add(new Label("level", 62, 125, 80, 20, "Level " + this.curLevel, this.font12));
        this.wndEditPalette.add(new Label("switch", 62, 175, 80, 20, "Switch", this.font12));
        this.wndEdit.add(this.wndEditPalette);
        (this.wndEditOptions = new Window("editOptions", 203, 0, 820, 147, false)).add(new Textbox("name", 65, 25, 160, 20, "Name:", this.font12, false));
        this.wndEditOptions.add(new Textbox("x", 65, 65, 80, 20, "Width:", this.font12, false));
        this.wndEditOptions.add(new Textbox("y", 65, 105, 80, 20, "Height:", this.font12, false));
        this.wndEditOptions.add(new Button("new", 400, 108, 80, 20, "New", this.font12));
        this.wndEditOptions.add(new Button("save", 500, 108, 80, 20, "Save", this.font12));
        this.wndEditOptions.add(new Button("load", 600, 108, 80, 20, "Load", this.font12));
        this.wndEditOptions.add(new Button("back", 700, 108, 80, 20, "Back", this.font12));
        this.wndEdit.add(this.wndEditOptions);
        this.horBar = new ScrollBar("horScroll", 204, 748, 800, 19, 8, true);
        this.verBar = new ScrollBar("verScroll", 1004, 147, 19, 601, 8, false);
        this.wndEdit.add(this.horBar);
        this.wndEdit.add(this.verBar);
        (this.wndMessage = new Window("message", 402, 202, 220, 160)).add(new Label("label", 20, 15, 180, 12, "none", this.font12));
        this.wndMessage.add(new Button("button", 70, 115, 80, 30, "OK", this.font12));
        (this.wndLoadMap = new Window("load map", 402, 202, 220, 160)).add(new Textbox("map_name", 80, 15, 120, 20, "Map Name:", this.font12, false));
        this.wndLoadMap.add(new Button("load", 20, 115, 80, 30, "Load", this.font12, Align.Center));
        this.wndLoadMap.add(new Button("back", 120, 115, 80, 30, "Back", this.font12, Align.Center));
        this.wndDiagnostics = new Window("diagnostics", 0, 0, 80, 40, true);
    }
    
    private void loadMap() {
        this.imageMap = new HashMap<Integer, Tile>();
        this.crMap = new HashMap<Integer, Creature>();
        this.tileBreakdowns = new HashMap<Integer, GroundType[]>();
        this.tileByBreakdown = (ArrayList<Tile>[])new ArrayList[81];
        (this.imgSets = new ArrayList<ArrayList<Tile>>()).add(new ArrayList<Tile>());
        this.imgSets.add(new ArrayList<Tile>());
        this.imgSets.add(new ArrayList<Tile>());
        this.imgSets.add(new ArrayList<Tile>());
        this.imgSets.add(new ArrayList<Tile>());
        this.imgSets.add(new ArrayList<Tile>());
        this.imgSets.add(new ArrayList<Tile>());
        for (int x = 0; x < 16; ++x) {
            this.imgSets.get(0).add(new Tile(new MapImage(new DynamicImage("tiles/ground" + (x + 1) + ".png"), MapType.Ground)));
            this.imageMap.put(MapImage.lastKey, this.imgSets.get(0).get(x));
        }
        for (int x = 0; x < 12; ++x) {
            this.imgSets.get(1).add(new Tile(new MapImage(new DynamicImage("tiles/cliff" + (x + 1) + ".png"), MapType.Ground)));
            this.imageMap.put(MapImage.lastKey, this.imgSets.get(1).get(x));
        }
        int last = 15;
        this.imageMap.get(last + 1).getImg().setDrawOffset(-40, 0);
        this.imageMap.get(last + 3).getImg().setDrawOffset(-40, 0);
        this.imageMap.get(last + 5).getImg().setDrawOffset(0, -40);
        this.imageMap.get(last + 6).getImg().setDrawOffset(0, -40);
        this.imageMap.get(last + 7).getImg().setDrawOffset(-40, -40);
        this.imageMap.get(last + 8).getImg().setDrawOffset(0, -40);
        this.imageMap.get(last + 9).getImg().setDrawOffset(-40, 0);
        this.imageMap.get(last + 1).getImg().setSortOffset(-18, 0);
        this.imageMap.get(last + 2).getImg().setSortOffset(62, 0);
        this.imageMap.get(last + 3).getImg().setSortOffset(-18, 0);
        this.imageMap.get(last + 4).getImg().setSortOffset(62, 0);
        this.imageMap.get(last + 5).getImg().setSortOffset(0, 32);
        this.imageMap.get(last + 6).getImg().setSortOffset(0, 32);
        this.imageMap.get(last + 7).getImg().setSortOffset(-18, 32);
        this.imageMap.get(last + 8).getImg().setSortOffset(62, 32);
        this.imageMap.get(last + 9).getImg().setSortOffset(-18, 75);
        this.imageMap.get(last + 10).getImg().setSortOffset(62, 75);
        this.imageMap.get(last + 11).getImg().setSortOffset(0, 75);
        this.imageMap.get(last + 12).getImg().setSortOffset(0, 75);
        this.imageMap.get(last + 1).setBound(new Bound(new Rectangle2D.Double(20.0, 0.0, 15.0, 40.0)));
        this.imageMap.get(last + 2).setBound(new Bound(new Rectangle2D.Double(45.0, 0.0, 21.0, 40.0)));
        this.imageMap.get(last + 3).setBound(new Bound(new Rectangle2D.Double(20.0, 0.0, 15.0, 40.0)));
        this.imageMap.get(last + 4).setBound(new Bound(new Rectangle2D.Double(45.0, 0.0, 21.0, 40.0)));
        this.imageMap.get(last + 5).setBound(new Bound(new Rectangle2D.Double(0.0, 20.0, 40.0, 15.0)));
        this.imageMap.get(last + 6).setBound(new Bound(new Rectangle2D.Double(0.0, 20.0, 40.0, 15.0)));
        this.imageMap.get(last + 11).setBound(new Bound(new Rectangle2D.Double(0.0, 45.0, 40.0, 27.0)));
        this.imageMap.get(last + 12).setBound(new Bound(new Rectangle2D.Double(0.0, 45.0, 40.0, 27.0)));
        Bound b1 = new Bound(new Ellipse2D.Double(20.0, -48.0, 120.0, 120.0));
        b1.intersect(new Bound(new Rectangle2D.Double(20.0, 12.0, 60.0, 60.0)));
        b1.add(new Bound(new Rectangle2D.Double(20.0, 0.0, 15.0, 12.0)));
        b1.subtract(new Bound(new Ellipse2D.Double(35.0, -21.0, 66.0, 66.0)));
        b1.subtract(new Bound(new Rectangle2D.Double(68.0, 35.0, 12.0, 10.0)));
        final Bound b2 = new Bound(new Ellipse2D.Double(-66.0, -60.0, 132.0, 132.0));
        b2.intersect(new Bound(new Rectangle2D.Double(0.0, 6.0, 66.0, 66.0)));
        b2.add(new Bound(new Rectangle2D.Double(45.0, 0.0, 21.0, 6.0)));
        b2.subtract(new Bound(new Ellipse2D.Double(-45.0, -45.0, 90.0, 90.0)));
        final Bound b3 = new Bound(new Ellipse2D.Double(-54.0, 20.0, 120.0, 120.0));
        b3.intersect(new Bound(new Rectangle2D.Double(6.0, 20.0, 60.0, 60.0)));
        b3.add(new Bound(new Rectangle2D.Double(0.0, 20.0, 6.0, 15.0)));
        b3.subtract(new Bound(new Ellipse2D.Double(-33.0, 35.0, 78.0, 78.0)));
        b3.subtract(new Bound(new Rectangle2D.Double(39.0, 74.0, 6.0, 6.0)));
        final Bound b4 = new Bound(new Ellipse2D.Double(20.0, 20.0, 120.0, 120.0));
        b4.intersect(new Bound(new Rectangle2D.Double(20.0, 20.0, 60.0, 60.0)));
        b4.subtract(new Bound(new Ellipse2D.Double(35.0, 35.0, 90.0, 90.0)));
        this.imageMap.get(last + 7).setBound(b4);
        this.imageMap.get(last + 8).setBound(b3);
        this.imageMap.get(last + 9).setBound(b1);
        this.imageMap.get(last + 10).setBound(b2);
        this.imageMap.get(last + 7).getImg().setNeedsBase(true);
        this.imageMap.get(last + 8).getImg().setNeedsBase(true);
        for (int x2 = 0; x2 < 6; ++x2) {
            this.imgSets.get(2).add(new Tile(new MapImage(new DynamicImage("tiles/rock" + (x2 + 1) + ".png"), MapType.Ground)));
            this.imageMap.put(MapImage.lastKey, this.imgSets.get(2).get(x2));
        }
        last = 33;
        this.imgSets.get(3).add(new Tile(new MapImage(new DynamicImage("objects/rock1.png"), MapType.Object)));
        this.imageMap.put(MapImage.lastKey, this.imgSets.get(3).get(0));
        this.imgSets.get(3).add(new Tile(new MapImage(new DynamicImage("objects/rock2.png"), MapType.Object)));
        this.imageMap.put(MapImage.lastKey, this.imgSets.get(3).get(1));
        this.imgSets.get(3).add(new Tile(new MapImage(new DynamicImage("objects/tree1.png"), MapType.Object)));
        this.imageMap.put(MapImage.lastKey, this.imgSets.get(3).get(2));
        this.imgSets.get(3).add(new Tile(new MapImage(new DynamicImage("objects/tree2.png"), MapType.Object)));
        this.imageMap.put(MapImage.lastKey, this.imgSets.get(3).get(3));
        this.imageMap.get(last + 1).getImg().setDrawOffset(-22, -28);
        this.imageMap.get(last + 2).getImg().setDrawOffset(-16, -50);
        this.imageMap.get(last + 3).getImg().setDrawOffset(-36, -100);
        this.imageMap.get(last + 4).getImg().setDrawOffset(-58, -83);
        this.imageMap.get(last + 1).setBound(new Bound(new Ellipse2D.Double(-6.0, -6.0, 12.0, 12.0)));
        this.imageMap.get(last + 2).setBound(new Bound(new Ellipse2D.Double(-6.0, -6.0, 12.0, 12.0)));
        this.imageMap.get(last + 3).setBound(new Bound(new Ellipse2D.Double(-16.0, -16.0, 32.0, 32.0)));
        this.imageMap.get(last + 4).setBound(new Bound(new Ellipse2D.Double(-30.0, -30.0, 60.0, 60.0)));
        for (int x2 = 0; x2 < 19; ++x2) {
            this.imgSets.get(4).add(new Tile(new MapImage(new DynamicImage("tiles/pave" + (x2 + 1) + ".png"), MapType.Ground)));
            this.imageMap.put(MapImage.lastKey, this.imgSets.get(4).get(x2));
        }
        for (int x2 = 0; x2 < 13; ++x2) {
            this.imgSets.get(5).add(new Tile(new MapImage(new DynamicImage("tiles/fence" + (x2 + 1) + ".png"), MapType.Structure)));
            this.imageMap.put(MapImage.lastKey, this.imgSets.get(5).get(x2));
        }
        last = 56;
        this.imageMap.get(last + 1).getImg().setDrawOffset(-19, -85);
        this.imageMap.get(last + 2).getImg().setDrawOffset(-20, -85);
        this.imageMap.get(last + 3).getImg().setDrawOffset(-20, -97);
        this.imageMap.get(last + 4).getImg().setDrawOffset(-16, -72);
        this.imageMap.get(last + 5).getImg().setDrawOffset(-20, -81);
        this.imageMap.get(last + 6).getImg().setDrawOffset(-13, -45);
        this.imageMap.get(last + 7).getImg().setDrawOffset(-20, -67);
        this.imageMap.get(last + 8).getImg().setDrawOffset(-13, -51);
        this.imageMap.get(last + 9).getImg().setDrawOffset(-17, -95);
        this.imageMap.get(last + 10).getImg().setDrawOffset(-22, -95);
        this.imageMap.get(last + 11).getImg().setDrawOffset(-19, -86);
        this.imageMap.get(last + 12).getImg().setDrawOffset(-20, -67);
        this.imageMap.get(last + 13).getImg().setDrawOffset(-20, -84);
        b1 = new Bound(new Rectangle2D.Double(-14.0, -40.0, 34.0, 40.0));
        b1.add(new Bound(new Rectangle2D.Double(-20.0, -25.0, 6.0, 25.0)));
        this.imageMap.get(last + 1).setBound(new Bound(new Rectangle2D.Double(-14.0, -25.0, 34.0, 25.0)));
        this.imageMap.get(last + 2).setBound(new Bound(new Rectangle2D.Double(-20.0, -25.0, 40.0, 25.0)));
        this.imageMap.get(last + 3).setBound(new Bound(new Rectangle2D.Double(-20.0, -25.0, 40.0, 25.0)));
        this.imageMap.get(last + 5).setBound(b1);
        this.imageMap.get(last + 6).setBound(new Bound(new Rectangle2D.Double(-14.0, -40.0, 34.0, 40.0)));
        this.imageMap.get(last + 7).setBound(new Bound(new Rectangle2D.Double(-20.0, -25.0, 40.0, 25.0)));
        this.imageMap.get(last + 8).setBound(new Bound(new Rectangle2D.Double(-14.0, -40.0, 34.0, 40.0)));
        this.imageMap.get(last + 9).setBound(new Bound(new Rectangle2D.Double(-20.0, -25.0, 40.0, 25.0)));
        this.imageMap.get(last + 10).setBound(new Bound(new Rectangle2D.Double(-20.0, -25.0, 40.0, 25.0)));
        this.imageMap.get(last + 11).setBound(new Bound(new Rectangle2D.Double(-14.0, -40.0, 34.0, 40.0)));
        this.imageMap.get(last + 12).setBound(new Bound(new Rectangle2D.Double(-20.0, -25.0, 40.0, 25.0)));
        this.imgSets.get(6).add(this.imgSets.get(0).get(0));
        this.imgSets.get(6).add(this.imgSets.get(0).get(9));
        this.imgSets.get(6).add(this.imgSets.get(4).get(0));
        this.setBreakdown(this.imgSets.get(0).get(0), GroundType.Grass, GroundType.Grass, GroundType.Grass, GroundType.Grass);
        this.setBreakdown(this.imgSets.get(0).get(1), GroundType.Dirt, GroundType.Dirt, GroundType.Dirt, GroundType.Grass);
        this.setBreakdown(this.imgSets.get(0).get(2), GroundType.Dirt, GroundType.Dirt, GroundType.Grass, GroundType.Dirt);
        this.setBreakdown(this.imgSets.get(0).get(3), GroundType.Dirt, GroundType.Grass, GroundType.Grass, GroundType.Grass);
        this.setBreakdown(this.imgSets.get(0).get(4), GroundType.Dirt, GroundType.Dirt, GroundType.Grass, GroundType.Grass);
        this.setBreakdown(this.imgSets.get(0).get(5), GroundType.Grass, GroundType.Dirt, GroundType.Grass, GroundType.Grass);
        this.setBreakdown(this.imgSets.get(0).get(6), GroundType.Dirt, GroundType.Grass, GroundType.Dirt, GroundType.Dirt);
        this.setBreakdown(this.imgSets.get(0).get(7), GroundType.Grass, GroundType.Dirt, GroundType.Dirt, GroundType.Dirt);
        this.setBreakdown(this.imgSets.get(0).get(8), GroundType.Dirt, GroundType.Grass, GroundType.Dirt, GroundType.Grass);
        this.setBreakdown(this.imgSets.get(0).get(9), GroundType.Dirt, GroundType.Dirt, GroundType.Dirt, GroundType.Dirt);
        this.setBreakdown(this.imgSets.get(0).get(10), GroundType.Grass, GroundType.Dirt, GroundType.Grass, GroundType.Dirt);
        this.setBreakdown(this.imgSets.get(0).get(11), GroundType.Grass, GroundType.Grass, GroundType.Dirt, GroundType.Grass);
        this.setBreakdown(this.imgSets.get(0).get(12), GroundType.Grass, GroundType.Grass, GroundType.Dirt, GroundType.Dirt);
        this.setBreakdown(this.imgSets.get(0).get(13), GroundType.Grass, GroundType.Grass, GroundType.Grass, GroundType.Dirt);
        this.setBreakdown(this.imgSets.get(0).get(14), GroundType.Dirt, GroundType.Grass, GroundType.Grass, GroundType.Dirt);
        this.setBreakdown(this.imgSets.get(0).get(15), GroundType.Grass, GroundType.Dirt, GroundType.Dirt, GroundType.Grass);
        this.setBreakdown(this.imgSets.get(4).get(0), GroundType.Stone, GroundType.Stone, GroundType.Stone, GroundType.Stone);
        this.setBreakdown(this.imgSets.get(4).get(1), GroundType.Stone, GroundType.Stone, GroundType.Stone, GroundType.Stone);
        this.setBreakdown(this.imgSets.get(4).get(2), GroundType.Stone, GroundType.Stone, GroundType.Stone, GroundType.Stone);
        this.setBreakdown(this.imgSets.get(4).get(3), GroundType.Stone, GroundType.Stone, GroundType.Stone, GroundType.Stone);
        this.setBreakdown(this.imgSets.get(4).get(4), GroundType.Dirt, GroundType.Dirt, GroundType.Dirt, GroundType.Stone);
        this.setBreakdown(this.imgSets.get(4).get(5), GroundType.Dirt, GroundType.Dirt, GroundType.Stone, GroundType.Stone);
        this.setBreakdown(this.imgSets.get(4).get(6), GroundType.Dirt, GroundType.Dirt, GroundType.Stone, GroundType.Dirt);
        this.setBreakdown(this.imgSets.get(4).get(7), GroundType.Dirt, GroundType.Stone, GroundType.Stone, GroundType.Stone);
        this.setBreakdown(this.imgSets.get(4).get(8), GroundType.Stone, GroundType.Dirt, GroundType.Stone, GroundType.Stone);
        this.setBreakdown(this.imgSets.get(4).get(9), GroundType.Dirt, GroundType.Stone, GroundType.Dirt, GroundType.Stone);
        this.setBreakdown(this.imgSets.get(4).get(10), GroundType.Stone, GroundType.Stone, GroundType.Stone, GroundType.Stone);
        this.setBreakdown(this.imgSets.get(4).get(11), GroundType.Stone, GroundType.Dirt, GroundType.Stone, GroundType.Dirt);
        this.setBreakdown(this.imgSets.get(4).get(12), GroundType.Stone, GroundType.Stone, GroundType.Dirt, GroundType.Stone);
        this.setBreakdown(this.imgSets.get(4).get(13), GroundType.Stone, GroundType.Stone, GroundType.Stone, GroundType.Dirt);
        this.setBreakdown(this.imgSets.get(4).get(14), GroundType.Dirt, GroundType.Stone, GroundType.Dirt, GroundType.Dirt);
        this.setBreakdown(this.imgSets.get(4).get(15), GroundType.Stone, GroundType.Stone, GroundType.Dirt, GroundType.Dirt);
        this.setBreakdown(this.imgSets.get(4).get(16), GroundType.Stone, GroundType.Dirt, GroundType.Dirt, GroundType.Dirt);
        this.setBreakdown(this.imgSets.get(4).get(17), GroundType.Dirt, GroundType.Stone, GroundType.Stone, GroundType.Dirt);
        this.setBreakdown(this.imgSets.get(4).get(18), GroundType.Stone, GroundType.Dirt, GroundType.Dirt, GroundType.Stone);
        this.setIndex = 0;
        this.activeSet = this.imgSets.get(this.setIndex);
        this.curTile = this.activeSet.get(0);
    }
    
    private void loadCreatures() {
        this.crSet = new ArrayList<Creature>();
        Utils.loadCreatures(this.crMap, this.crSet);
        this.curCr = this.crSet.get(0);
    }
    
    private boolean createNewMap() {
        final String name = ((Textbox)this.wndEditOptions.getMember("name")).getText();
        final String strX = ((Textbox)this.wndEditOptions.getMember("x")).getText();
        final String strY = ((Textbox)this.wndEditOptions.getMember("y")).getText();
        boolean passed = false;
        if (name.equals("")) {
            this.showMessage("You didn't enter a name for the map");
        }
        else if (strX.equals("")) {
            this.showMessage("You didn't enter a width");
        }
        else if (strY.equals("")) {
            this.showMessage("You didn't enter a height");
        }
        else {
            int x = 0;
            int y = 0;
            passed = true;
            try {
                x = Integer.parseInt(strX);
                if (x <= 0) {
                    passed = false;
                    this.showMessage("The width must be positive");
                }
            }
            catch (NumberFormatException nfe) {
                passed = false;
                this.showMessage("Your width is not a valid integer");
            }
            try {
                y = Integer.parseInt(strY);
                if (y <= 0) {
                    passed = false;
                    this.showMessage("The height must be positive");
                }
            }
            catch (NumberFormatException nfe) {
                passed = false;
                this.showMessage("Your height is not a valid integer");
            }
            if (passed) {
                this.playerLoc = new Point(400, 300);
                MapEditor.map = new Map(x, y, this.imgSets.get(0).get(0), this.imgSets.get(0).get(9));
                this.mapName = name;
                this.horBar.setSize(800 * this.horBar.getMaxSize() / (MapEditor.map.getWidth() * 40 + 800));
                this.verBar.setSize(600 * this.verBar.getMaxSize() / (MapEditor.map.getHeight() * 40 + 600));
                this.horBar.setPosition(this.horBar.getMaxSize() * this.playerLoc.x / (40 * MapEditor.map.getWidth() + 800));
                this.verBar.setPosition(this.verBar.getMaxSize() * this.playerLoc.y / (40 * MapEditor.map.getHeight() + 600));
                this.showMessage(MapEditor.map.message);
            }
        }
        return passed;
    }
    
    private ArrayList<Tile> getTilesByBreakdown(final GroundType[] t) {
        return this.tileByBreakdown[t[0].ordinal() * 27 + t[1].ordinal() * 9 + t[2].ordinal() * 3 + t[3].ordinal()];
    }
    
    private GroundType[] getBreakdown(final Tile t) {
        return this.tileBreakdowns.get(t.getImg().key);
    }
    
    private void setBreakdown(final Tile t, final GroundType t1, final GroundType t2, final GroundType t3, final GroundType t4) {
        final GroundType[] type = { t1, t2, t3, t4 };
        this.tileBreakdowns.put(t.getImg().key, type);
        final int index = t1.ordinal() * 27 + t2.ordinal() * 9 + t3.ordinal() * 3 + t4.ordinal();
        if (this.tileByBreakdown[index] == null) {
            this.tileByBreakdown[index] = new ArrayList<Tile>();
        }
        this.tileByBreakdown[index].add(t);
    }
    
    private synchronized void handleEvents() {
        switch (this.state) {
        }
    }
    
    private synchronized void render(final Graphics g) {
        g.setColor(Color.black);
        g.fillRect(0, 0, 1024, 768);
        this.mapG.setColor(Color.black);
        this.mapG.fillRect(0, 0, 800, 600);
        switch (this.state) {
            case Main: {
                this.wndMain.draw(g);
                break;
            }
            case Edit: {
                this.wndEdit.draw(g);
                this.drawPalette(g);
                MapEditor.map.draw(this.mapG, this.playerLoc, this.bounds, this.passable);
                g.drawImage(this.mapBuffer, 204, 148, null);
                if (this.selectedObject != null) {
                    g.setColor(Color.blue);
                    final int selectedX = 400 - this.playerLoc.x + 204 + this.selectedObject.loc.x;
                    final int selectedY = 300 - this.playerLoc.y + 148 + this.selectedObject.loc.y;
                    g.drawOval(selectedX - 25, selectedY - 33, 50, 50);
                }
                if (this.selectedCreature != null) {
                    g.setColor(Color.blue);
                    final int selectedX = 400 - this.playerLoc.x + 204 + this.selectedCreature.loc.x;
                    final int selectedY = 300 - this.playerLoc.y + 148 + this.selectedCreature.loc.y;
                    g.drawOval(selectedX - 25, selectedY - 33, 50, 50);
                    break;
                }
                break;
            }
        }
        switch (this.auxState) {
            case MsgBox: {
                this.wndMessage.draw(g);
                break;
            }
            case LoadMap: {
                this.wndLoadMap.draw(g);
                break;
            }
        }
        if (this.showFps) {
            this.drawDiagnostics(g);
        }
    }
    
    private void drawPalette(final Graphics g) {
        if (this.showCr) {
            final DynamicImage curImg = this.curCr.getModel().getAnimation(Direction.South, Action.Standing).frames.get(0);
            curImg.draw(g, (204 - curImg.getWidth()) / 2, 40);
            int yOffset = 215;
            for (int x = 0; x < this.crSet.size(); x += 2) {
                final DynamicImage img1 = this.crSet.get(x).getModel().getAnimation(Direction.South, Action.Standing).frames.get(0);
                img1.draw(g, 97 - img1.getWidth(), yOffset);
                if (this.crSet.size() != x + 1) {
                    final DynamicImage img2 = this.crSet.get(x + 1).getModel().getAnimation(Direction.South, Action.Standing).frames.get(0);
                    img2.draw(g, 107, yOffset);
                    yOffset += Math.max(img1.getHeight(), img2.getHeight()) + 10;
                }
            }
            this.drawArrows(g, 0, this.curLevel, 5);
            this.drawArrows(g, 50, this.imgSets.size(), this.imgSets.size() - 1);
            return;
        }
        this.curTile.getImg().drawNoOffset(g, (204 - this.curTile.getImg().getWidth()) / 2, 40);
        int yOffset2 = 215;
        for (int x2 = 0; x2 < this.activeSet.size(); x2 += 2) {
            this.activeSet.get(x2).getImg().drawNoOffset(g, 97 - this.activeSet.get(x2).getImg().getWidth(), yOffset2);
            if (this.activeSet.size() != x2 + 1) {
                this.activeSet.get(x2 + 1).getImg().drawNoOffset(g, 107, yOffset2);
                yOffset2 += Math.max(this.activeSet.get(x2).getImg().getHeight(), this.activeSet.get(x2 + 1).getImg().getHeight()) + 10;
            }
        }
        this.drawArrows(g, 0, this.curLevel, 5);
        this.drawArrows(g, 50, this.setIndex, this.imgSets.size() - 1);
    }
    
    private void drawArrows(final Graphics g, final int arrowShift, final int curIndex, final int maxIndex) {
        if (curIndex > 0) {
            g.setColor(Color.yellow);
        }
        else {
            g.setColor(new Color(127, 127, 0));
        }
        g.drawLine(67, 146 + arrowShift, 87, 146 + arrowShift);
        g.drawLine(67, 152 + arrowShift, 87, 152 + arrowShift);
        g.drawLine(87, 146 + arrowShift, 87, 152 + arrowShift);
        g.drawLine(60, 149 + arrowShift, 67, 142 + arrowShift);
        g.drawLine(67, 142 + arrowShift, 67, 146 + arrowShift);
        g.drawLine(60, 149 + arrowShift, 67, 156 + arrowShift);
        g.drawLine(67, 156 + arrowShift, 67, 152 + arrowShift);
        if (curIndex < maxIndex) {
            g.setColor(Color.yellow);
        }
        else {
            g.setColor(new Color(127, 127, 0));
        }
        g.drawLine(117, 146 + arrowShift, 137, 146 + arrowShift);
        g.drawLine(117, 152 + arrowShift, 137, 152 + arrowShift);
        g.drawLine(117, 146 + arrowShift, 117, 152 + arrowShift);
        g.drawLine(144, 149 + arrowShift, 137, 142 + arrowShift);
        g.drawLine(137, 142 + arrowShift, 137, 146 + arrowShift);
        g.drawLine(144, 149 + arrowShift, 137, 156 + arrowShift);
        g.drawLine(137, 156 + arrowShift, 137, 152 + arrowShift);
    }
    
    private void drawDiagnostics(final Graphics g) {
        this.wndDiagnostics.draw(g);
        g.setColor(Color.green);
        g.setFont(this.fontTT);
        g.drawString("FPS: " + this.lastFrameCount, 0, 15);
    }
    
    private boolean changeLevel(final int x, final int y) {
        if (142 < y && y < 156) {
            if (60 <= x && x <= 87) {
                if (this.curLevel > 0) {
                    --this.curLevel;
                    ((Label)this.wndEditPalette.getMember("level")).setText("Level " + this.curLevel);
                }
                return true;
            }
            if (117 <= x && x <= 144) {
                if (this.curLevel < 5) {
                    ++this.curLevel;
                    ((Label)this.wndEditPalette.getMember("level")).setText("Level " + this.curLevel);
                }
                return true;
            }
        }
        return false;
    }
    
    private boolean changeSet(final int x, final int y) {
        if (192 < y && y < 206) {
            if (60 <= x && x <= 87) {
                if (this.setIndex > 0) {
                    --this.setIndex;
                    this.activeSet = this.imgSets.get(this.setIndex);
                    this.showCr = false;
                }
                return true;
            }
            if (117 <= x && x <= 144) {
                if (this.setIndex < this.imgSets.size() - 1) {
                    ++this.setIndex;
                    this.activeSet = this.imgSets.get(this.setIndex);
                }
                else if (this.setIndex == this.imgSets.size() - 1) {
                    ++this.setIndex;
                    this.showCr = true;
                }
                return true;
            }
        }
        return false;
    }
    
    private boolean selectNewImage(final int x, final int y) {
        boolean foundImage = false;
        int index = 0;
        int yOffset = 215;
        if (this.showCr) {
            DynamicImage img2 = null;
            while (index < this.crSet.size() && !foundImage) {
                final DynamicImage img3 = this.crSet.get(index).getModel().getAnimation(Direction.South, Action.Standing).frames.get(0);
                int rowHeight;
                if (this.crSet.size() == index + 1) {
                    rowHeight = img3.getHeight();
                }
                else {
                    img2 = this.crSet.get(index + 1).getModel().getAnimation(Direction.South, Action.Standing).frames.get(0);
                    rowHeight = Math.max(img3.getHeight(), img2.getHeight());
                }
                if (yOffset <= y && y < yOffset + rowHeight) {
                    if (97 - img3.getWidth() <= x && x < 97) {
                        if (y < yOffset + img3.getHeight()) {
                            foundImage = true;
                        }
                    }
                    else if (107 <= x && this.crSet.size() > index + 1 && x < 107 + img2.getWidth() && y < yOffset + img2.getHeight()) {
                        foundImage = true;
                        ++index;
                    }
                }
                else {
                    yOffset += rowHeight + 10;
                }
                if (!foundImage) {
                    index += 2;
                }
            }
            if (foundImage) {
                this.curCr = this.crSet.get(index);
            }
            return foundImage;
        }
        while (index < this.activeSet.size() && !foundImage) {
            int rowHeight;
            if (this.activeSet.size() == index + 1) {
                rowHeight = this.activeSet.get(index).getImg().getHeight();
            }
            else {
                rowHeight = Math.max(this.activeSet.get(index).getImg().getHeight(), this.activeSet.get(index + 1).getImg().getHeight());
            }
            if (yOffset <= y && y < yOffset + rowHeight) {
                if (97 - this.activeSet.get(index).getImg().getWidth() <= x && x < 97) {
                    if (y < yOffset + this.activeSet.get(index).getImg().getHeight()) {
                        foundImage = true;
                    }
                }
                else if (107 <= x && this.activeSet.size() > index + 1 && x < 107 + this.activeSet.get(index + 1).getImg().getWidth() && y < yOffset + this.activeSet.get(index + 1).getImg().getHeight()) {
                    foundImage = true;
                    ++index;
                }
            }
            else {
                yOffset += rowHeight + 10;
            }
            if (!foundImage) {
                index += 2;
            }
        }
        if (foundImage) {
            this.curTile = this.activeSet.get(index);
        }
        this.highLevelPlacement = (this.activeSet == this.imgSets.get(6));
        return foundImage;
    }
    
    private void placeTile(int x, int y) {
        x -= 204;
        y -= 148;
        if (x >= 0 && x < 800 && y >= 0 && y < 600) {
            x += this.playerLoc.x - 400;
            y += this.playerLoc.y - 300;
            if (x >= 0 && x < 40 * MapEditor.map.getWidth() && y >= 0 && y < 40 * MapEditor.map.getHeight()) {
                if (this.showCr) {
                    MapEditor.map.addCreature(x / 40, y / 40, this.curCr.copy(new Point(x, y)));
                }
                else if (this.curTile.getImg().getType() == MapType.Ground) {
                    if (this.highLevelPlacement) {
                        this.placeGroup(this.curTile, x, y);
                    }
                    else {
                        MapEditor.map.setGround(x / 40, y / 40, new Tile(this.curTile, x - x % 40, y - y % 40, this.curLevel));
                    }
                }
                else if (this.curTile.getImg().getType() == MapType.Object) {
                    MapEditor.map.addObject(x / 40, y / 40, new Tile(this.curTile, x, y, this.curLevel));
                    System.out.println("place at (" + x / 40 + ", " + y / 40 + ")");
                }
                else if (this.curTile.getImg().getType() == MapType.Structure) {
                    MapEditor.map.addObject(x / 40, y / 40, new Tile(this.curTile, x - x % 40 + 20, y - y % 40 + 39, this.curLevel));
                }
            }
        }
    }
    
    private boolean containsGroundType(final GroundType[] arr, final GroundType t) {
        return arr[0] == t || arr[1] == t || arr[2] == t || arr[3] == t;
    }
    
    private void placeGroup(final Tile tile, final int x, final int y) {
        final int xMap = x / 40;
        final int yMap = y / 40;
        final ArrayList<Tile>[] tiles = new ArrayList[9];
        final GroundType[] middle = this.getBreakdown(tile);
        final GroundType[] breakdown = new GroundType[4];
        if (this.containsGroundType(middle, GroundType.Stone)) {
            if (xMap > 0 && yMap > 0 && this.containsGroundType(this.getBreakdown(MapEditor.map.getLoc(xMap - 1, yMap - 1).getGround()), GroundType.Grass)) {
                this.placeGroup(this.imgSets.get(6).get(1), x - 40, y - 40);
            }
            if (yMap > 0 && this.containsGroundType(this.getBreakdown(MapEditor.map.getLoc(xMap, yMap - 1).getGround()), GroundType.Grass)) {
                this.placeGroup(this.imgSets.get(6).get(1), x, y - 40);
            }
            if (xMap < MapEditor.map.getWidth() - 1 && yMap > 0 && this.containsGroundType(this.getBreakdown(MapEditor.map.getLoc(xMap + 1, yMap - 1).getGround()), GroundType.Grass)) {
                this.placeGroup(this.imgSets.get(6).get(1), x + 40, y - 40);
            }
            if (xMap < MapEditor.map.getWidth() - 1 && this.containsGroundType(this.getBreakdown(MapEditor.map.getLoc(xMap + 1, yMap).getGround()), GroundType.Grass)) {
                this.placeGroup(this.imgSets.get(6).get(1), x + 40, y);
            }
            if (xMap < MapEditor.map.getWidth() - 1 && yMap < MapEditor.map.getHeight() - 1 && this.containsGroundType(this.getBreakdown(MapEditor.map.getLoc(xMap + 1, yMap + 1).getGround()), GroundType.Grass)) {
                this.placeGroup(this.imgSets.get(6).get(1), x + 40, y + 40);
            }
            if (yMap < MapEditor.map.getHeight() - 1 && this.containsGroundType(this.getBreakdown(MapEditor.map.getLoc(xMap, yMap + 1).getGround()), GroundType.Grass)) {
                this.placeGroup(this.imgSets.get(6).get(1), x, y + 40);
            }
            if (xMap > 0 && yMap < MapEditor.map.getHeight() - 1 && this.containsGroundType(this.getBreakdown(MapEditor.map.getLoc(xMap - 1, yMap + 1).getGround()), GroundType.Grass)) {
                this.placeGroup(this.imgSets.get(6).get(1), x - 40, y + 40);
            }
            if (xMap > 0 && this.containsGroundType(this.getBreakdown(MapEditor.map.getLoc(xMap - 1, yMap).getGround()), GroundType.Grass)) {
                this.placeGroup(this.imgSets.get(6).get(1), x - 40, y);
            }
        }
        else if (this.containsGroundType(middle, GroundType.Grass)) {
            if (xMap > 0 && yMap > 0 && this.containsGroundType(this.getBreakdown(MapEditor.map.getLoc(xMap - 1, yMap - 1).getGround()), GroundType.Stone)) {
                this.placeGroup(this.imgSets.get(6).get(1), x - 40, y - 40);
            }
            if (yMap > 0 && this.containsGroundType(this.getBreakdown(MapEditor.map.getLoc(xMap, yMap - 1).getGround()), GroundType.Stone)) {
                this.placeGroup(this.imgSets.get(6).get(1), x, y - 40);
            }
            if (xMap < MapEditor.map.getWidth() - 1 && yMap > 0 && this.containsGroundType(this.getBreakdown(MapEditor.map.getLoc(xMap + 1, yMap - 1).getGround()), GroundType.Stone)) {
                this.placeGroup(this.imgSets.get(6).get(1), x + 40, y - 40);
            }
            if (xMap < MapEditor.map.getWidth() - 1 && this.containsGroundType(this.getBreakdown(MapEditor.map.getLoc(xMap + 1, yMap).getGround()), GroundType.Stone)) {
                this.placeGroup(this.imgSets.get(6).get(1), x + 40, y);
            }
            if (xMap < MapEditor.map.getWidth() - 1 && yMap < MapEditor.map.getHeight() - 1 && this.containsGroundType(this.getBreakdown(MapEditor.map.getLoc(xMap + 1, yMap + 1).getGround()), GroundType.Stone)) {
                this.placeGroup(this.imgSets.get(6).get(1), x + 40, y + 40);
            }
            if (yMap < MapEditor.map.getHeight() - 1 && this.containsGroundType(this.getBreakdown(MapEditor.map.getLoc(xMap, yMap + 1).getGround()), GroundType.Stone)) {
                this.placeGroup(this.imgSets.get(6).get(1), x, y + 40);
            }
            if (xMap > 0 && yMap < MapEditor.map.getHeight() - 1 && this.containsGroundType(this.getBreakdown(MapEditor.map.getLoc(xMap - 1, yMap + 1).getGround()), GroundType.Stone)) {
                this.placeGroup(this.imgSets.get(6).get(1), x - 40, y + 40);
            }
            if (xMap > 0 && this.containsGroundType(this.getBreakdown(MapEditor.map.getLoc(xMap - 1, yMap).getGround()), GroundType.Stone)) {
                this.placeGroup(this.imgSets.get(6).get(1), x - 40, y);
            }
        }
        tiles[4] = this.getTilesByBreakdown(middle);
        if (xMap > 0 && yMap > 0) {
            final GroundType[] old = this.getBreakdown(MapEditor.map.getLoc(xMap - 1, yMap - 1).getGround());
            System.arraycopy(old, 0, breakdown, 0, 4);
            breakdown[3] = middle[0];
            tiles[0] = this.getTilesByBreakdown(breakdown);
            this.addTile(x - 40, y - 40, tiles[0].get(new Random().nextInt(tiles[0].size())));
        }
        if (yMap > 0) {
            final GroundType[] old = this.getBreakdown(MapEditor.map.getLoc(xMap, yMap - 1).getGround());
            System.arraycopy(old, 0, breakdown, 0, 4);
            breakdown[2] = middle[0];
            breakdown[3] = middle[1];
            tiles[1] = this.getTilesByBreakdown(breakdown);
            this.addTile(x, y - 40, tiles[1].get(new Random().nextInt(tiles[1].size())));
        }
        if (xMap < MapEditor.map.getWidth() - 1 && yMap > 0) {
            final GroundType[] old = this.getBreakdown(MapEditor.map.getLoc(xMap + 1, yMap - 1).getGround());
            System.arraycopy(old, 0, breakdown, 0, 4);
            breakdown[2] = middle[1];
            tiles[2] = this.getTilesByBreakdown(breakdown);
            this.addTile(x + 40, y - 40, tiles[2].get(new Random().nextInt(tiles[2].size())));
        }
        if (xMap < MapEditor.map.getWidth() - 1) {
            final GroundType[] old = this.getBreakdown(MapEditor.map.getLoc(xMap + 1, yMap).getGround());
            System.arraycopy(old, 0, breakdown, 0, 4);
            breakdown[0] = middle[1];
            breakdown[2] = middle[3];
            tiles[5] = this.getTilesByBreakdown(breakdown);
            this.addTile(x + 40, y, tiles[5].get(new Random().nextInt(tiles[5].size())));
        }
        if (xMap < MapEditor.map.getWidth() - 1 && yMap < MapEditor.map.getHeight() - 1) {
            final GroundType[] old = this.getBreakdown(MapEditor.map.getLoc(xMap + 1, yMap + 1).getGround());
            System.arraycopy(old, 0, breakdown, 0, 4);
            breakdown[0] = middle[3];
            tiles[8] = this.getTilesByBreakdown(breakdown);
            this.addTile(x + 40, y + 40, tiles[8].get(new Random().nextInt(tiles[8].size())));
        }
        if (yMap < MapEditor.map.getHeight() - 1) {
            final GroundType[] old = this.getBreakdown(MapEditor.map.getLoc(xMap, yMap + 1).getGround());
            System.arraycopy(old, 0, breakdown, 0, 4);
            breakdown[0] = middle[2];
            breakdown[1] = middle[3];
            tiles[7] = this.getTilesByBreakdown(breakdown);
            this.addTile(x, y + 40, tiles[7].get(new Random().nextInt(tiles[7].size())));
        }
        if (xMap > 0 && yMap < MapEditor.map.getHeight() - 1) {
            final GroundType[] old = this.getBreakdown(MapEditor.map.getLoc(xMap - 1, yMap + 1).getGround());
            System.arraycopy(old, 0, breakdown, 0, 4);
            breakdown[1] = middle[2];
            tiles[6] = this.getTilesByBreakdown(breakdown);
            this.addTile(x - 40, y + 40, tiles[6].get(new Random().nextInt(tiles[6].size())));
        }
        if (xMap > 0) {
            final GroundType[] old = this.getBreakdown(MapEditor.map.getLoc(xMap - 1, yMap).getGround());
            System.arraycopy(old, 0, breakdown, 0, 4);
            breakdown[1] = middle[0];
            breakdown[3] = middle[2];
            tiles[3] = this.getTilesByBreakdown(breakdown);
            this.addTile(x - 40, y, tiles[3].get(new Random().nextInt(tiles[3].size())));
        }
        this.addTile(x, y, tiles[4].get(new Random().nextInt(tiles[4].size())));
    }
    
    private void addTile(final int x, final int y, final Tile t) {
        MapEditor.map.setGround(x / 40, y / 40, new Tile(t, x - x % 40, y - y % 40, this.curLevel));
    }
    
    private void selectObject(int x, int y) {
        x -= 204;
        y -= 148;
        if (x >= 0 && x < 800 && y >= 0 && y < 600) {
            x += this.playerLoc.x - 400;
            y += this.playerLoc.y - 300;
            final Iterator<Tile> iter = MapEditor.map.getLoc(x / 40, y / 40).getObjects().iterator();
            Tile closest = null;
            final Point curPoint = new Point(x, y);
            if (!iter.hasNext()) {
                this.selectedObject = null;
                return;
            }
            closest = iter.next();
            while (iter.hasNext()) {
                final Tile cur = iter.next();
                if (cur.loc.distance(curPoint) < closest.loc.distance(curPoint)) {
                    closest = cur;
                }
            }
            this.selectedObject = closest;
        }
        else {
            this.selectedObject = null;
        }
    }
    
    private void selectCreature(int x, int y) {
        x -= 204;
        y -= 148;
        if (x >= 0 && x < 800 && y >= 0 && y < 600) {
            x += this.playerLoc.x - 400;
            y += this.playerLoc.y - 300;
            final Iterator<Creature> iter = MapEditor.map.getLoc(x / 40, y / 40).getCreatures().iterator();
            Creature closest = null;
            final Point curPoint = new Point(x, y);
            if (!iter.hasNext()) {
                this.selectedCreature = null;
                return;
            }
            closest = iter.next();
            while (iter.hasNext()) {
                final Creature cur = iter.next();
                if (cur.loc.distance(curPoint) < closest.loc.distance(curPoint)) {
                    closest = cur;
                }
            }
            if (this.selectedObject == null || closest.loc.distance(curPoint) < this.selectedObject.loc.distance(curPoint)) {
                this.selectedCreature = closest;
            }
        }
        else {
            this.selectedCreature = null;
        }
    }
    
    public void showMessage(final String text) {
        this.auxState = AuxState.MsgBox;
        ((Label)this.wndMessage.getMember("label")).setText(text);
    }
    
    private void selectText(final Textbox text) {
        if (this.selectedText != null) {
            this.selectedText.setSelected(false);
        }
        if ((this.selectedText = text) != null) {
            text.setSelected(true);
        }
    }
    
    private synchronized void handleMouseInput(final MouseEvent e) {
        if (!this.started) {
            return;
        }
        this.selectText(null);
        switch (this.auxState) {
            case None: {
                switch (this.state) {
                    case Main: {
                        if (this.wndMain.getMember("new map").isClicked(e.getX(), e.getY())) {
                            MapEditor.map = new Map(40, 40, this.activeSet.get(0));
                            this.playerLoc = new Point(400, 300);
                            this.mapName = "mapSave.txt";
                            this.horBar.setSize(800 * this.horBar.getMaxSize() / (MapEditor.map.getWidth() * 40 + 800));
                            this.verBar.setSize(600 * this.verBar.getMaxSize() / (MapEditor.map.getHeight() * 40 + 600));
                            this.horBar.setPosition(this.horBar.getMaxSize() * this.playerLoc.x / (40 * MapEditor.map.getWidth() + 800));
                            this.verBar.setPosition(this.verBar.getMaxSize() * this.playerLoc.y / (40 * MapEditor.map.getHeight() + 600));
                            this.state = State.Edit;
                            break;
                        }
                        if (this.wndMain.getMember("load map").isClicked(e.getX(), e.getY())) {
                            this.auxState = AuxState.LoadMap;
                            ((Textbox)this.wndLoadMap.getMember("map_name")).setText("mapSave.txt");
                            break;
                        }
                        if (this.wndMain.getMember("quit").isClicked(e.getX(), e.getY())) {
                            this.done = true;
                            break;
                        }
                        break;
                    }
                    case Edit: {
                        if (this.wndEditOptions.getMember("name").isClicked(e.getX(), e.getY())) {
                            this.selectText((Textbox)this.wndEditOptions.getMember("name"));
                            break;
                        }
                        if (this.wndEditOptions.getMember("x").isClicked(e.getX(), e.getY())) {
                            this.selectText((Textbox)this.wndEditOptions.getMember("x"));
                            break;
                        }
                        if (this.wndEditOptions.getMember("y").isClicked(e.getX(), e.getY())) {
                            this.selectText((Textbox)this.wndEditOptions.getMember("y"));
                            break;
                        }
                        if (this.wndEditOptions.getMember("new").isClicked(e.getX(), e.getY())) {
                            this.createNewMap();
                            break;
                        }
                        if (this.wndEditOptions.getMember("save").isClicked(e.getX(), e.getY())) {
                            MapEditor.map.save(this.mapName);
                            this.showMessage(MapEditor.map.message);
                            break;
                        }
                        if (this.wndEditOptions.getMember("load").isClicked(e.getX(), e.getY())) {
                            this.auxState = AuxState.LoadMap;
                            ((Textbox)this.wndLoadMap.getMember("map_name")).setText("mapSave.txt");
                            break;
                        }
                        if (this.wndEditOptions.getMember("back").isClicked(e.getX(), e.getY())) {
                            this.state = State.Main;
                            break;
                        }
                        if (this.wndEdit.handleEvent(e)) {
                            this.playerLoc.x = (MapEditor.map.getWidth() * 40 + 800) * this.horBar.getPosition() / this.horBar.getMaxSize();
                            this.playerLoc.y = (MapEditor.map.getHeight() * 40 + 600) * this.verBar.getPosition() / this.verBar.getMaxSize();
                            break;
                        }
                        if (this.selectNewImage(e.getX(), e.getY()) || this.changeSet(e.getX(), e.getY()) || this.changeLevel(e.getX(), e.getY())) {
                            break;
                        }
                        if (e.isShiftDown()) {
                            this.selectObject(e.getX(), e.getY());
                            this.selectCreature(e.getX(), e.getY());
                            break;
                        }
                        this.placeTile(e.getX(), e.getY());
                        break;
                    }
                }
                break;
            }
            case MsgBox: {
                if (this.wndMessage.getMember("button").isClicked(e.getX(), e.getY())) {
                    this.auxState = AuxState.None;
                    break;
                }
                break;
            }
            case LoadMap: {
                if (this.wndLoadMap.getMember("map_name").isClicked(e.getX(), e.getY())) {
                    this.selectText((Textbox)this.wndLoadMap.getMember("map_name"));
                    break;
                }
                if (this.wndLoadMap.getMember("load").isClicked(e.getX(), e.getY())) {
                    final String strName = ((Textbox)this.wndLoadMap.getMember("map_name")).getText();
                    MapEditor.map = null;
                    final Map newMap = Map.load(strName, MapEditor.map, this.imageMap, this.crMap);
                    if (newMap.valid) {
                        MapEditor.map = newMap;
                        this.playerLoc = new Point(400, 300);
                        this.mapName = strName;
                        this.horBar.setSize(800 * this.horBar.getMaxSize() / (MapEditor.map.getWidth() * 40 + 800));
                        this.verBar.setSize(600 * this.verBar.getMaxSize() / (MapEditor.map.getHeight() * 40 + 600));
                        this.horBar.setPosition(this.horBar.getMaxSize() * this.playerLoc.x / (40 * MapEditor.map.getWidth() + 800));
                        this.verBar.setPosition(this.verBar.getMaxSize() * this.playerLoc.y / (40 * MapEditor.map.getHeight() + 600));
                        this.state = State.Edit;
                    }
                    this.showMessage(newMap.message);
                    break;
                }
                if (this.wndLoadMap.getMember("back").isClicked(e.getX(), e.getY())) {
                    this.auxState = AuxState.None;
                    break;
                }
                break;
            }
        }
    }
    
    public void handleKeyboardInput(final KeyEvent e) {
        if (this.selectedText != null) {
            this.selectedText.handleEvent(e);
        }
        else if (e.getKeyCode() == 83) {
            this.showFps = !this.showFps;
        }
        else if (e.getKeyCode() == 27) {
            if (this.state == State.Edit) {
                this.state = State.Main;
            }
            else {
                this.done = true;
            }
        }
        else if (e.getKeyCode() == 127) {
            if (this.state == State.Edit && this.selectedObject != null) {
                MapEditor.map.removeObject(this.selectedObject.getMapX(), this.selectedObject.getMapY(), this.selectedObject);
                this.selectedObject = null;
            }
            if (this.state == State.Edit && this.selectedCreature != null) {
                MapEditor.map.removeCreature(this.selectedCreature.getMapX(), this.selectedCreature.getMapY(), this.selectedCreature);
                this.selectedCreature = null;
            }
        }
        else if (e.getKeyCode() == 90 && this.state == State.Edit) {
            this.bounds = !this.bounds;
        }
        else if (e.getKeyCode() == 88 && this.state == State.Edit) {
            this.passable = !this.passable;
        }
    }
    
    @Override
    public void mousePressed(final MouseEvent e) {
        this.handleMouseInput(e);
    }
    
    @Override
    public void mouseReleased(final MouseEvent e) {
    }
    
    @Override
    public void mouseEntered(final MouseEvent e) {
    }
    
    @Override
    public void mouseExited(final MouseEvent e) {
    }
    
    @Override
    public void mouseClicked(final MouseEvent e) {
    }
    
    @Override
    public void keyTyped(final KeyEvent e) {
    }
    
    @Override
    public void keyPressed(final KeyEvent e) {
        this.handleKeyboardInput(e);
    }
    
    @Override
    public void keyReleased(final KeyEvent e) {
    }
    
    public static void main(final String[] args) {
        try {
            final PrintStream st = new PrintStream(new FileOutputStream("errMapEditor.txt", true));
            System.setErr(st);
            System.setOut(st);
            System.out.println("-----[ Session started on " + Utils.dateString() + " ]-----");
            final GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
            final GraphicsDevice device = env.getDefaultScreenDevice();
            new MapEditor(device);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        System.exit(0);
    }
    
    public enum AuxState
    {
        None("None", 0), 
        MsgBox("MsgBox", 1), 
        LoadMap("LoadMap", 2);
        
        private AuxState(final String s, final int n) {
        }
    }
    
    private enum GroundType
    {
        Grass("Grass", 0), 
        Dirt("Dirt", 1), 
        Stone("Stone", 2);
        
        private GroundType(final String s, final int n) {
        }
    }
    
    public enum State
    {
        Main("Main", 0), 
        Edit("Edit", 1);
        
        private State(final String s, final int n) {
        }
    }
}
