public class Authentication {
    private final Console console;
    private final Set<User> userDatabase = new HashSet<>();
    private final Kernel kernel;
    private boolean authenticated;
    private String clientToken = UUID.randomUUID().toString();
    private User selectedAccount;
    private final String authenticatePath ,refreshPath;
    private final String mojangDomain = "authserver.mojang.com";
    private final String krothiumDomain = "mc.krothium.com";

    public Authentication(Kernel k) {
        kernel = k;
        console = k.getConsole();
        authenticatePath = "/authenticate";
        refreshPath = "/refresh";
    }

    /**
     * Adds a user to the database
     * @param u The user to be added
     */
    private void addUser(User u) {
        if (userDatabase.contains(u)) {
            userDatabase.remove(u);
            userDatabase.add(u);
            console.print("User " + u.getUserID() + " updated.");
        } else {
            userDatabase.add(u);
            console.print("User " + u.getUserID() + " loaded.");
        }

    }

    /**
     * Removes a user for the database
     * @param u The User to be removed
     */
    public void removeUser(User u) {
        if (userDatabase.contains(u)) {
            console.print("User " + u.getUserID() + " deleted.");
            userDatabase.remove(u);
            if (u.equals(selectedAccount)) {
                setSelectedUser(null);
            }
        } else {
            console.print("userID " + u.getUserID() + " is not registered.");
        }
    }

    /**
     * Returns the selected user. Might be null
     * @return The selected user or null if no user is selected.
     */
    public final User getSelectedUser() {
        return selectedAccount;
    }

    /**
     * Sets the selected user
     * @param user The user to be selected
     */
    public void setSelectedUser(User user) {
        if (user != null) {
            console.print("User " + user.getUserID() + " is now selected.");
        } else if (selectedAccount != null) {
            console.print(selectedAccount.getUserID() + " is not longer selected.");
        }
        selectedAccount = user;
    }

    /**
     * Performs an authenticate request to the server
     * @param username The username
     * @param password The password
     * @throws AuthenticationException If authentication failed
     */
    public final void authenticate(String username, String password) throws AuthenticationException {
        JSONObject request = new JSONObject();
        JSONObject agent = new JSONObject();
        UserType type;
        agent.put("name", "Minecraft");
        agent.put("version", 1);
        request.put("agent", agent);
        String tmpUser;
        if (username.startsWith("krothium://")) {
            type = UserType.KROTHIUM;
            tmpUser = username.replace("krothium://", "");
        } else {
            type = UserType.MOJANG;
            tmpUser = username;
        }
        request.put("username", tmpUser);
        request.put("password", password);
        if (clientToken != null) {
            request.put("clientToken", clientToken);
        }
        request.put("requestUser", true);
        Map<String, String> postParams = new HashMap<>();
        postParams.put("Content-Type", "application/json; charset=utf-8");
        postParams.put("Content-Length", String.valueOf(request.toString().length()));
        String response;
        String authURL;
        if (type == UserType.MOJANG) {
            authURL = "https://" + mojangDomain + authenticatePath;
        } else {
            authURL = "https://" + krothiumDomain + authenticatePath;
        }
        try {
            response = Utils.sendPost(authURL, request.toString().getBytes(Charset.forName("UTF-8")), postParams);
        } catch (IOException ex) {
            console.print("Failed to send request to authentication server");
            ex.printStackTrace(console.getWriter());
            throw new AuthenticationException("Failed to send request to authentication server");
        }
        if (response.isEmpty()) {
            throw new AuthenticationException("Authentication server does not respond.");
        }
        JSONObject r;
        try {
            r = new JSONObject(response);
        } catch (JSONException ex) {
            throw new AuthenticationException("Failed to read authentication response.");
        }
        if (!r.has("error")) {
            try {
                String accessToken = r.getString("accessToken");
                String selectedProfile = r.getJSONObject("selectedProfile").getString("id");
                String userID = r.getJSONObject("user").getString("id");
                clientToken = r.getString("clientToken");
                ArrayList<UserProfile> userProfiles = new ArrayList<>();
                JSONArray uprofs = r.getJSONArray("availableProfiles");
                for (int i = 0; i < uprofs.length(); i++){
                    JSONObject prof = uprofs.getJSONObject(i);
                    UserProfile up = new UserProfile(prof.getString("id"), prof.getString("name"));
                    userProfiles.add(up);
                }
                User u = new User(userID, accessToken, username, type, userProfiles, selectedProfile);
                selectedAccount = u;
                authenticated = true;
                addUser(u);
            } catch (JSONException ex) {
                ex.printStackTrace(console.getWriter());
                throw new AuthenticationException("Authentication server replied wrongly.");
            }
        } else {
            authenticated = false;
            throwError(r);
        }
    }

    /**
     * Performs a refresh request to the server
     * @throws AuthenticationException If the refresh failed
     */
    public final void refresh() throws AuthenticationException, JSONException{
        if (selectedAccount == null) {
            throw new AuthenticationException("No user is selected.");
        }
        JSONObject request = new JSONObject();
        JSONObject agent = new JSONObject();
        User u = selectedAccount;
        agent.put("name", "Minecraft");
        agent.put("version", 1);
        request.put("agent", agent);
        request.put("accessToken", u.getAccessToken());
        request.put("clientToken", clientToken);
        request.put("requestUser", true);
        Map<String, String> postParams = new HashMap<>();
        postParams.put("Content-Type", "application/json; charset=utf-8");
        postParams.put("Content-Length", String.valueOf(request.toString().length()));
        String response;
        String refreshURL;
        if (u.getType() == UserType.MOJANG) {
            refreshURL = "https://" + mojangDomain + refreshPath;
        } else {
            refreshURL = "https://" + krothiumDomain + refreshPath;
        }
        try {
            response = Utils.sendPost(refreshURL, request.toString().getBytes(Charset.forName("UTF-8")), postParams);
        } catch (IOException ex) {
            Kernel.USE_LOCAL = true;
            authenticated = true;
            console.print("Authenticated locally.");
            return;
        }
        if (response.isEmpty()) {
            throw new AuthenticationException("Authentication server does not respond.");
        }
        JSONObject r;
        try {
            r = new JSONObject(response);
        } catch (JSONException ex) {
            throw new AuthenticationException("Failed to read authentication response.");
        }
        if (!r.has("error")) {
            try {
                clientToken = r.getString("clientToken");
                u.setAccessToken(r.getString("accessToken"));
                String selectedProfile = r.getJSONObject("selectedProfile").getString("id");
                u.setSelectedProfile(selectedProfile);
                authenticated = true;
            } catch (JSONException ex) {
                ex.printStackTrace(console.getWriter());
                throw new AuthenticationException("Authentication server replied wrongly.");
            }
        } else {
            authenticated = false;
            removeUser(selectedAccount);
            throwError(r);
        }
    }

    private void throwError(JSONObject message) throws AuthenticationException{
        if (message.has("errorMessage")) {
            throw new AuthenticationException(message.getString("errorMessage"));
        } else if (message.has("cause")) {
            throw new AuthenticationException(message.getString("error") + " caused by " + message.getString("cause"));
        } else {
            throw new AuthenticationException(message.getString("error"));
        }
    }

    /**
     * Checks if someone is authenticated
     * @return A boolean that indicates if is authenticated
     */
    public final boolean isAuthenticated() {
        return authenticated;
    }

    /**
     * Returns the client token
     * @return The client token
     */
    public final String getClientToken() {
        return clientToken;
    }

    /**
     * Loads the users from launcher_profile.json
     */
    public final void fetchUsers() {
        console.print("Loading user data.");
        JSONObject root = kernel.getLauncherProfiles();
        if (root != null) {
            String selectedUser = null;
            String selectedProfile = null;
            if (root.has("clientToken")) {
                clientToken = root.getString("clientToken");
            }
            if (root.has("selectedUser")) {
                Object selected = root.get("selectedUser");
                if (selected instanceof JSONObject) {
                    JSONObject s = (JSONObject)selected;
                    if (s.has("account")) {
                        selectedUser = s.getString("account");
                    }
                    if (s.has("profile")) {
                        selectedProfile = s.getString("profile");
                    }
                } else {
                    console.print("Legacy launcher_profiles.json found");
                }
            }
            if (root.has("authenticationDatabase")) {
                JSONObject users = root.getJSONObject("authenticationDatabase");
                Set s = users.keySet();
                for (Object value : s) {
                    String userID = value.toString();
                    JSONObject user = users.getJSONObject(userID);
                    if (user.has("accessToken") && user.has("username") && user.has("profiles")) {
                        String username = user.getString("username");
                        UserType userType = username.startsWith("krothium://") ? UserType.KROTHIUM : UserType.MOJANG;
                        JSONObject profiles = user.getJSONObject("profiles");
                        Set profileSet = profiles.keySet();
                        if (profileSet.size() > 0) {
                            ArrayList<UserProfile> userProfiles = new ArrayList<>();
                            for (Object o : profileSet) {
                                String profileUUID = o.toString();
                                JSONObject profile = profiles.getJSONObject(profileUUID);
                                if (profile.has("displayName")) {
                                    UserProfile up = new UserProfile(profileUUID, profile.getString("displayName"));
                                    userProfiles.add(up);
                                }
                            }
                            User u;
                            if (userID.equalsIgnoreCase(selectedUser)) {
                                u = new User(userID, user.getString("accessToken"), username, userType, userProfiles, selectedProfile);
                                addUser(u);
                                setSelectedUser(u);
                            } else {
                                u = new User(userID, user.getString("accessToken"), username, userType, userProfiles, null);
                                addUser(u);
                            }
                        }
                    }
                }
            }
        } else {
            console.print("No users to be loaded.");
        }
    }

    /**
     * Returns the user database
     * @return The user database
     */
    public final Set<User> getUsers() {
        return userDatabase;
    }

    /**
     * Converts the user database to JSON
     * @return The user database in json format
     */
    public final JSONObject toJSON() {
        JSONObject o = new JSONObject();
        o.put("clientToken", clientToken);
        if (!userDatabase.isEmpty()) {
            JSONObject db = new JSONObject();
            for (User u : userDatabase) {
                JSONObject user = new JSONObject();
                user.put("accessToken", u.getAccessToken());
                user.put("username", u.getUsername());
                JSONObject profile = new JSONObject();
                for (UserProfile up : u.getProfiles()) {
                    JSONObject profileInfo = new JSONObject();
                    profileInfo.put("displayName", u.getDisplayName());
                    profile.put(up.getId(), profileInfo);
                }
                user.put("profiles", profile);
                db.put(u.getUserID(), user);
            }
            o.put("authenticationDatabase", db);
            JSONObject selectedUser = new JSONObject();
            if (selectedAccount != null) {
                selectedUser.put("account", selectedAccount.getUserID());
                selectedUser.put("profile", selectedAccount.getSelectedProfile());
            }
            o.put("selectedUser", selectedUser);
        }
        return o;
    }
} public class GameLauncher {

    private final Console console;
    private final Kernel kernel;
    private Process process;
    private OutputFX output;
    private Stage outputGUI;

    public GameLauncher(Kernel k) {
        kernel = k;
        console = k.getConsole();
    }

    /**
     * Prepares and launcher the game
     * @throws GameLauncherException If an error has been thrown
     */
    public final void launch(final MainFX mainFX) throws GameLauncherException {
        console.print("Game launch work has started.");
        Profile p = kernel.getProfiles().getSelectedProfile();
        if (isRunning()) {
            throw new GameLauncherException("Game is already started!");
        }
        Versions versions = kernel.getVersions();
        VersionMeta verID;
        switch (p.getType()) {
            case CUSTOM:
                verID = p.hasVersion() ? p.getVersionID() : versions.getLatestRelease();
                break;
            case RELEASE:
                verID = versions.getLatestRelease();
                break;
            default:
                verID = versions.getLatestSnapshot();
                break;
        }
        if (verID == null) {
            throw new GameLauncherException("Version ID is null.");
        }
        Version ver = versions.getVersion(verID);
        if (ver == null) {
            throw new GameLauncherException("Version info could not be obtained.");
        }
        File workingDir = Kernel.APPLICATION_WORKING_DIR;
        console.print("Deleting old natives.");
        File nativesRoot = new File(workingDir + File.separator + "versions" + File.separator + ver.getID());
        if (nativesRoot.isDirectory()) {
            File[] files = nativesRoot.listFiles();
            if (files != null) {
                for (File f : files) {
                    if (f.isDirectory() && f.getName().contains("natives")) {
                        Utils.deleteDirectory(f);
                    }
                }
            }
        }
        final File nativesDir = new File(workingDir, "versions" + File.separator + ver.getID() + File.separator + ver.getID() + "-natives-" + System.nanoTime());
        if (!nativesDir.isDirectory()) {
            nativesDir.mkdirs();
        }
        console.print("Launching Minecraft " + ver.getID() + " on " + workingDir.getAbsolutePath());
        console.print("Using natives dir: " + nativesDir);
        console.print("Extracting natives.");
        List<String> gameArgs = new ArrayList<>();
        if (p.hasJavaDir()) {
            gameArgs.add(p.getJavaDir().getAbsolutePath());
        } else {
            gameArgs.add(Utils.getJavaDir());
        }
        if (!p.hasJavaArgs()) {
            if (Utils.getOSArch() == OSArch.OLD) {
                gameArgs.add("-Xmx1G");
                gameArgs.add("-Xss1M");
            } else {
                gameArgs.add("-Xmx2G");
            }
            gameArgs.add("-Xmn128M");
        } else {
            String javaArgs = p.getJavaArgs();
            String[] args = javaArgs.split(" ");
            Collections.addAll(gameArgs, args);
        }
        gameArgs.add("-Djava.library.path=" + nativesDir.getAbsolutePath());
        gameArgs.add("-cp");
        StringBuilder libraries = new StringBuilder();
        List<Library> libs = ver.getLibraries();
        String separator = System.getProperty("path.separator");
        Authentication a = kernel.getAuthentication();
        User u = a.getSelectedUser();
        if (u.getType() == UserType.KROTHIUM) {
            try {
                File launchPath = new File(GameLauncher.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
                libraries.append(launchPath.getAbsolutePath()).append(separator);
            } catch (URISyntaxException ex) {
                console.print("Failed to load GameStarter.");
            }
        }
        for (Library lib : libs) {
            if (!lib.isCompatible()) {
                continue;
            }
            if (lib.isNative()) {
                try {
                    File completePath = new File(Kernel.APPLICATION_WORKING_DIR + File.separator + lib.getRelativeNativePath());
                    FileInputStream input = new FileInputStream(completePath);
                    Utils.decompressZIP(input, nativesDir, lib.getExtractExclusions());
                } catch (IOException ex) {
                    console.print("Failed to extract native: " + lib.getName());
                    ex.printStackTrace(console.getWriter());
                }
            } else {
                File completePath = new File(Kernel.APPLICATION_WORKING_DIR + File.separator + lib.getRelativePath());
                libraries.append(completePath.getAbsolutePath()).append(separator);
            }
        }
        console.print("Preparing game args.");
        File verPath = new File(Kernel.APPLICATION_WORKING_DIR + File.separator + ver.getRelativeJar());
        libraries.append(verPath.getAbsolutePath());
        File assetsDir;
        AssetIndex index = ver.getAssetIndex();
        File assetsRoot = new File(workingDir, "assets");
        if ("legacy".equals(index.getID())) {
            assetsDir = new File(assetsRoot, "virtual" + File.separator + "legacy");
            if (!assetsDir.isDirectory()) {
                assetsDir.mkdirs();
            }
            console.print("Building virtual asset folder.");
            File indexJSON = new File(assetsRoot, "indexes" + File.separator + index.getID() + ".json");
            try {
                JSONObject o = new JSONObject(new String(Files.readAllBytes(indexJSON.toPath()), "ISO-8859-1"));
                JSONObject objects = o.getJSONObject("objects");
                Set s = objects.keySet();
                for (Object value : s) {
                    String name = value.toString();
                    File assetFile = new File(assetsDir, name);
                    JSONObject asset = objects.getJSONObject(name);
                    String sha = asset.getString("hash");
                    if (!Utils.verifyChecksum(assetFile, sha, "SHA-1")) {
                        File objectFile = new File(assetsRoot, "objects" + File.separator + sha.substring(0, 2) + File.separator + sha);
                        if (assetFile.getParentFile() != null) {
                            assetFile.getParentFile().mkdirs();
                        }
                        Files.copy(objectFile.toPath(), assetFile.toPath());
                    }
                }
            } catch (Exception ex) {
                console.print("Failed to create virtual asset folder.");
                ex.printStackTrace(console.getWriter());
            }
        } else {
            assetsDir = assetsRoot;
        }
        gameArgs.add(libraries.toString());
        if (u.getType() == UserType.KROTHIUM) {
            gameArgs.add("kml.game.GameStarter");
        }
        gameArgs.add(ver.getMainClass());
        console.print("Full game launcher parameters: ");
        String[] versionArgs = ver.getMinecraftArguments().split(" ");
        for (int i = 0; i < versionArgs.length; i++) {
            if (versionArgs[i].startsWith("$")) {
                switch (versionArgs[i]) {
                    case "${auth_player_name}":
                        versionArgs[i] = versionArgs[i].replace("${auth_player_name}", u.getDisplayName());
                        break;
                    case "${version_name}":
                        versionArgs[i] = versionArgs[i].replace("${version_name}", ver.getID());
                        break;
                    case "${game_directory}":
                        if (p.hasGameDir()) {
                            File gameDir = p.getGameDir();
                            if (!gameDir.isDirectory()) {
                                gameDir.mkdirs();
                            }
                            versionArgs[i] = versionArgs[i].replace("${game_directory}", gameDir.getAbsolutePath());
                        } else {
                            versionArgs[i] = versionArgs[i].replace("${game_directory}", workingDir.getAbsolutePath());
                        }
                        break;
                    case "${assets_root}":
                        versionArgs[i] = versionArgs[i].replace("${assets_root}", assetsDir.getAbsolutePath());
                        break;
                    case "${game_assets}":
                        versionArgs[i] = versionArgs[i].replace("${game_assets}", assetsDir.getAbsolutePath());
                        break;
                    case "${assets_index_name}":
                        versionArgs[i] = versionArgs[i].replace("${assets_index_name}", index.getID());
                        break;
                    case "${auth_uuid}":
                        versionArgs[i] = versionArgs[i].replace("${auth_uuid}", u.getSelectedProfile());
                        break;
                    case "${auth_access_token}":
                        versionArgs[i] = versionArgs[i].replace("${auth_access_token}", u.getAccessToken());
                        break;
                    case "${version_type}":
                        versionArgs[i] = versionArgs[i].replace("${version_type}", ver.getType().name());
                        break;
                    case "${user_properties}":
                        versionArgs[i] = versionArgs[i].replace("${user_properties}", "{}");
                        break;
                    case "${user_type}":
                        versionArgs[i] = versionArgs[i].replace("${user_type}", "mojang");
                        break;
                    case "${auth_session}":
                        versionArgs[i] = versionArgs[i].replace("${auth_session}", "token:" + u.getAccessToken() + ':' + u.getSelectedProfile().replace("-", ""));
                        break;
                }
            }
        }
        Collections.addAll(gameArgs, versionArgs);
        if (p.hasResolution()) {
            gameArgs.add("--width");
            gameArgs.add(String.valueOf(p.getResolutionWidth()));
            gameArgs.add("--height");
            gameArgs.add(String.valueOf(p.getResolutionHeight()));
        }
        for (String arg : gameArgs) {
            console.print(arg);
        }
        ProcessBuilder pb = new ProcessBuilder(gameArgs);
        pb.directory(workingDir);
        try {
            process = pb.start();
            if (kernel.getSettings().getShowGameLog()) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        FXMLLoader loader = new FXMLLoader();
                        loader.setLocation(GameLauncher.this.getClass().getResource("/kml/gui/fxml/Output.fxml"));
                        Parent parent;
                        try {
                            parent = loader.load();
                        } catch (IOException e) {
                            parent = null;
                            console.print("Failed to initialize Output GUI!");
                            e.printStackTrace(console.getWriter());
                        }
                        Stage stage = new Stage();
                        stage.getIcons().add(Kernel.APPLICATION_ICON);
                        stage.setTitle("Krothium Minecraft Launcher - " + Language.get(69));
                        stage.setScene(new Scene(parent));
                        stage.setResizable(true);
                        stage.setMaximized(false);
                        stage.show();
                        output = loader.getController();
                        outputGUI = stage;
                    }
                });
            }
            Thread log_info = new Thread(new Runnable() {
                @Override
                public void run() {
                    GameLauncher.this.pipeOutput(process.getInputStream());
                }
            });
            log_info.start();
            Thread log_error = new Thread(new Runnable() {
                @Override
                public void run() {
                    GameLauncher.this.pipeOutput(process.getErrorStream());
                }
            });
            log_error.start();
            final Timer timer = new Timer();
            TimerTask process_status = new TimerTask() {
                @Override
                public void run() {
                    if (!GameLauncher.this.isRunning()) {
                        boolean error;
                        if (GameLauncher.this.process.exitValue() != 0) {
                            error = true;
                            GameLauncher.this.console.print("Game stopped unexpectedly.");
                        } else {
                            error = false;
                        }
                        GameLauncher.this.console.print("Deleteting natives dir.");
                        Utils.deleteDirectory(nativesDir);
                        timer.cancel();
                        timer.purge();
                        mainFX.gameEnded(error);
                    }
                }
            };
            timer.schedule(process_status, 0, 25);
        } catch (IOException ex) {
            ex.printStackTrace(console.getWriter());
            throw new GameLauncherException("Game returned an error code.");
        }
    }

    private void pipeOutput(InputStream in) {
        try (InputStreamReader isr = new InputStreamReader(in, StandardCharsets.ISO_8859_1);
             BufferedReader br = new BufferedReader(isr)){
            String lineRead;
            while ((lineRead = br.readLine()) != null) {
                if (kernel.getSettings().getShowGameLog() && outputGUI.isShowing()) {
                    output.pushString(lineRead);
                }
                console.print(lineRead);
            }
        } catch (IOException ex) {
            console.print("Failed to read stream.");
            ex.printStackTrace(console.getWriter());
        }
    }

    /**
     * Checks if the game process is running
     * @return A boolean with the current state
     */
    public boolean isRunning() {
        return process != null && process.isAlive();
    }

} public class Downloader {
    private final Console console;
    private final Kernel kernel;
    private double downloaded, validated, total;
    private boolean downloading;
    private String currentFile = "";
    private final int DOWNLOAD_TRIES = 5;

    public Downloader(Kernel k) {
        kernel = k;
        console = k.getConsole();
    }

    /**
     * Downloads all requires game files
     * @throws DownloaderException If the download fails
     */
    public final void download() throws DownloaderException {
        //Initial values
        downloading = true;
        downloaded = 0;
        validated = 0;
        total = 0;
        int tries;

        console.print("Download work has started.");
        if (Kernel.USE_LOCAL) {
            console.print("You are in offline mode.");
            downloading = false;
            return;
        }

        //Fetch version used by profile
        Profile p = kernel.getProfiles().getSelectedProfile();
        Versions versions = kernel.getVersions();
        VersionMeta verID;
        switch (p.getType()) {
            case CUSTOM:
                verID = p.hasVersion() ? p.getVersionID() : versions.getLatestRelease();
                break;
            case RELEASE:
                verID = versions.getLatestRelease();
                break;
            default:
                verID = versions.getLatestSnapshot();
                break;
        }
        if (verID == null) {
            downloading = false;
            throw new DownloaderException("Version ID is null.");
        }
        console.print("Using version ID: " + verID);
        Version v = versions.getVersion(verID);
        if (v == null) {
            downloading = false;
            throw new DownloaderException("Version info could not be obtained.");
        }

        //Get required files to be downloaded
        Set<Downloadable> urls = new HashSet<>();

        //Fetch assets
        console.print("Fetching asset urls..");
        AssetIndex index = v.getAssetIndex();
        File indexJSON = new File(Kernel.APPLICATION_WORKING_DIR, "assets" + File.separator + "indexes" + File.separator + index.getID() + ".json");
        tries = 0;
        if (!Utils.verifyChecksum(indexJSON, index.getSHA1(), "SHA-1")) {
            while (tries < DOWNLOAD_TRIES) {
                try {
                    Utils.downloadFile(index.getURL(), indexJSON);
                    break;
                } catch (IOException ex) {
                    console.print("Failed to download file " + indexJSON.getName() + " (try " + tries + ')');
                    ex.printStackTrace(console.getWriter());
                    tries++;
                }
            }
        }
        if (tries == DOWNLOAD_TRIES) {
            console.print("Failed to download asset index for version " + index.getID());
        } else {
            //Load assets
            try {
                JSONObject root;
                try {
                    root = new JSONObject(new String(Files.readAllBytes(indexJSON.toPath()), StandardCharsets.UTF_8));
                } catch (JSONException | IOException ex) {
                    downloading = false;
                    throw new DownloaderException("Failed to read asset index json file.");
                }
                JSONObject objects = root.getJSONObject("objects");
                Set<String> keys = objects.keySet();
                Collection<String> processedHashes = new ArrayList<>();
                File objectsRoot = new File("assets" + File.separator + "objects");
                for (String key : keys) {
                    JSONObject o = objects.getJSONObject(key);
                    String hash = o.getString("hash");
                    long size = o.getLong("size");
                    String downloadURL = "http://resources.download.minecraft.net/" + hash.substring(0, 2) + '/' + hash;
                    File relPath = new File(objectsRoot, hash.substring(0, 2) + File.separator + hash);
                    File fullPath = new File(Kernel.APPLICATION_WORKING_DIR + File.separator + relPath);
                    if (!processedHashes.contains(hash)) {
                        total += size;
                        processedHashes.add(hash);
                        if (!Utils.verifyChecksum(fullPath, hash, "SHA-1")) {
                            Downloadable d = new Downloadable(downloadURL, size, relPath, hash, key);
                            urls.add(d);
                        } else {
                            validated += size;
                        }
                    }
                }
            } catch (JSONException ex) {
                console.print("Failed to parse asset index.");
            }
        }

        //Fetch version
        console.print("Fetching version urls..");
        Map<String, Downloadable> downloads = v.getDownloads();
        if (downloads.containsKey("client")) {
            Downloadable d = downloads.get("client");
            if (d.hasURL()) {
                long jarSize = d.getSize();
                String jarSHA1 = d.getHash();
                total += d.getSize();
                File destPath = new File(Kernel.APPLICATION_WORKING_DIR + File.separator + v.getRelativeJar());
                File jsonFile = new File(Kernel.APPLICATION_WORKING_DIR + File.separator + v.getRelativeJSON());
                tries = 0;
                while (tries < DOWNLOAD_TRIES) {
                    try {
                        Utils.downloadFile(v.getJSONURL(), jsonFile);
                        break;
                    } catch (IOException ex) {
                        console.print("Failed to download file " + jsonFile.getName() + " (try " + tries + ')');
                        ex.printStackTrace(console.getWriter());
                        tries++;
                    }
                }
                if (tries == DOWNLOAD_TRIES) {
                    console.print("Failed to download version index " + destPath.getName());
                }
                if (!Utils.verifyChecksum(destPath, jarSHA1, "SHA-1")) {
                    urls.add(d);
                } else {
                    validated += jarSize;
                }
            } else {
                console.print("Incompatible version downloadable.");
            }
        } else if (v.hasJar()) {
            String jar = v.getJar();
            File relPath = v.getRelativeJar();
            console.print("Found legacy version " + jar);
            if (!relPath.exists()) {
                Downloadable d = new Downloadable("https://s3.amazonaws.com/Minecraft.Download/versions/" + jar + "/" + jar + ".jar", -1, v.getRelativeJar(), null, null);
                urls.add(d);
            } else {
                console.print("Legacy version file found. Assuming is valid.");
            }
        } else {
            console.print("Version file from " + v.getID() + " has no compatible downloadable objects.");
        }


        //Fetch libraries and natives
        console.print("Fetching library and native urls..");
        List<Library> libs = v.getLibraries();
        for (Library lib : libs) {
            if (lib.isCompatible()) {
                //Standard download
                if (lib.hasArtifactDownload()) {
                    Downloadable a = lib.getArtifactDownload();
                    File completePath = new File(Kernel.APPLICATION_WORKING_DIR + File.separator + a.getRelativePath());
                    if (completePath.isFile() && a.getHash() == null) {
                        console.print("File " + completePath + " has no hash. So let's assume the local one is valid.");
                    } else {
                        total += a.getSize();
                        if (Utils.verifyChecksum(completePath, a.getHash(), "SHA-1")) {
                            validated += a.getSize();
                        } else {
                            urls.add(a);
                        }
                    }
                }
                //Native download
                if (lib.hasClassifierDownload()) {
                    Downloadable c = lib.getClassifierDownload();
                    File completePath = new File(Kernel.APPLICATION_WORKING_DIR + File.separator + c.getRelativePath());
                    total += c.getSize();
                    if (completePath.isFile() && c.getHash() == null) {
                        console.print("File " + completePath + " has no hash. So let's assume the local one is valid.");
                    } else {
                        if (Utils.verifyChecksum(completePath, c.getHash(), "SHA-1")) {
                            validated += c.getSize();
                        } else {
                            urls.add(c);
                        }
                    }
                }
            }
        }
        console.print("Downloading required game files...");
        if (urls.isEmpty()) {
            console.print("Nothing to download.");
        } else {
            //Download required files
            downloadFiles(urls);
        }
        downloading = false;
    }

    /**
     * Performs the download of a Downloadable
     * @param dw The target Downloadable
     */
    private void downloadFile(Downloadable dw) {
        File path = dw.getRelativePath();
        File fullPath = new File(Kernel.APPLICATION_WORKING_DIR + File.separator + path);
        if (fullPath.getParentFile() != null) {
            fullPath.getParentFile().mkdirs();
        }
        if (dw.hasURL()) {
            try {
                URL url = new URL(dw.getURL());
                int tries = 0;
                if (dw.hasFakePath()) {
                    currentFile = dw.getFakePath();
                } else {
                    currentFile = path.toString();
                }
                console.print("Downloading " + currentFile + " from " + url);
                if (dw.getSize() == 0) {
                    console.print(dw.getURL() + " has no expected size.");
                    try {
                        URLConnection con = url.openConnection();
                        long length = con.getContentLength();
                        total += length;
                    } catch (IOException ex) {
                        console.print("Failed to determine size from " + dw.getURL());
                    }
                }
                while (tries < DOWNLOAD_TRIES) {
                    int totalRead = 0;
                    try (InputStream in = url.openStream();
                         OutputStream out = new FileOutputStream(fullPath)){
                        byte[] buffer = new byte[8192];
                        int read;
                        while ((read = in.read(buffer)) != -1) {
                            out.write(buffer, 0, read);
                            downloaded += read;
                            totalRead += read;
                        }
                        break;
                    } catch (IOException ex) {
                        console.print("Failed to download file " + currentFile + " (try " + tries + ')');
                        ex.printStackTrace(console.getWriter());
                        downloaded -= totalRead;
                        tries++;
                    }
                }
                if (tries == DOWNLOAD_TRIES) {
                    console.print("Failed to download file " + path.getName() + " from " + url);
                }
            } catch (MalformedURLException e) {
                console.print("Invalid URL " + dw.getURL());
                e.printStackTrace(console.getWriter());
            }
        }
    }

    /**
     * Downloads an entire set of Downloadables
     * @param list The set of Downloadables
     */
    private void downloadFiles(Set<Downloadable> list) {
        for (Downloadable d : list) {
            downloadFile(d);
        }
    }

    /**
     * Returns the current download progress
     * @return The download progress
     */
    public final double getProgress() {
        if (!downloading) {
            return 0;
        }
        return (downloaded + validated) / total;
    }

    /**
     * Checks if the download task still running
     * @return A boolean with the current status
     */
    public final boolean isDownloading() {
        return downloading;
    }

    /**
     * Gets the latest file that has been pushed to the download queue
     * @return The current file name
     */
    public final String getCurrentFile() {
        return currentFile;
    }
} public class Profiles {
    private final TreeSet<Profile> profiles = new TreeSet<>();
    private final Console console;
    private final Kernel kernel;
    private Profile selected, releaseProfile, snapshotProfile;

    public Profiles(Kernel k) {
        kernel = k;
        console = k.getConsole();
    }

    /**
     * Returns the profile database
     * @return The profile database
     */
    public final Iterable<Profile> getProfiles() {
        return profiles;
    }

    /**
     * Adds a profile to the database
     * @param p The profile to be added
     */
    public void addProfile(Profile p) {
        if (!profiles.contains(p)) {
            profiles.add(p);
            console.print("Profile " + p + " added");
            return;
        }
        console.print("Profile " + p + " already exists!");
    }

    /**
     * Deletes a profile from the database
     * @param p The profile to be deleted
     * @return A boolean that indicates if the profile has been deleted
     */
    public final boolean deleteProfile(Profile p) {
        if (profiles.contains(p)) {
            if (selected != null && selected.equals(p)) {
                console.print("Profile " + p + " is selected and is going to be removed.");
                profiles.remove(p);
                console.print("Profile " + p + " deleted.");
                if (!profiles.isEmpty()) {
                    setSelectedProfile(profiles.first());
                } else {
                    selected = null;
                }
            } else {
                profiles.remove(p);
                console.print("Profile " + p + " deleted.");
            }
            return true;
        }
        console.print("Profile " + p + " doesn't exist.");
        return false;
    }

    /**
     * Loads the profiles from the launcher_profiles.json
     */
    public final void fetchProfiles() {
        console.print("Fetching profiles.");
        Timestamp latestUsedMillis = new Timestamp(-1);
        JSONObject root = kernel.getLauncherProfiles();
        if (root != null) {
            try {
                JSONObject ples = root.getJSONObject("profiles");
                Set<String> keys = ples.keySet();
                Iterator<String> it = keys.iterator();
                Profile first = null, latestUsedID = null;
                while (it.hasNext()) {
                    String key = it.next();
                    JSONObject o = ples.getJSONObject(key);
                    try {
                        if (key.length() != 32) {
                            key = UUID.randomUUID().toString().replace("-", "");
                        } else {
                            String uuid = key.replaceAll("(.{8})(.{4})(.{4})(.{4})(.+)", "$1-$2-$3-$4-$5");
                            UUID.fromString(uuid);
                        }
                    } catch (IllegalArgumentException ex) {
                        key = UUID.randomUUID().toString().replace("-", "");
                    }
                    ProfileType type;
                    String typeString = o.has("type") ? o.getString("type") : null;
                    if (typeString != null) {
                        switch (typeString) {
                            case "latest-release":
                                type = ProfileType.RELEASE;
                                break;
                            case "latest-snapshot":
                                type = ProfileType.SNAPSHOT;
                                break;
                            default:
                                type = ProfileType.CUSTOM;
                        }
                    } else {
                        type = ProfileType.CUSTOM;
                    }
                    String name;
                    VersionMeta version;
                    String icon;
                    boolean latestRelease = false, latestSnapshot = false;
                    if (type == ProfileType.CUSTOM) {
                        name = o.has("name") ? o.getString("name") : null;
                        String ver = o.has("lastVersionId") ? o.getString("lastVersionId") : null;
                        if (ver != null) {
                            switch (ver) {
                                case "latest-release":
                                    latestRelease = true;
                                    break;
                                case "latest-snapshot":
                                    latestSnapshot = true;
                                    break;
                            }
                        }
                        version = kernel.getVersions().getVersionMeta(ver);
                        try {
                            icon = o.has("icon") ? o.getString("icon") : null;
                        } catch (IllegalArgumentException ex) {
                            icon = null;
                            console.print("Invalid profile icon for profile " + key);
                        }
                    } else {
                        name = null;
                        version = null;
                        icon = null;
                    }
                    String created = o.has("created") ? o.getString("created") : null;
                    String lastUsed = o.has("lastUsed") ? o.getString("lastUsed") : null;
                    String gameDir = o.has("gameDir") ? o.getString("gameDir") : null;
                    String javaDir = o.has("javaDir") ? o.getString("javaDir") : null;
                    String javaArgs = o.has("javaArgs") ? o.getString("javaArgs") : null;
                    Map<String, Integer> resolution = new HashMap<>();
                    if (o.has("resolution")) {
                        JSONObject res = o.getJSONObject("resolution");
                        if (res.has("width") && res.has("height")) {
                            resolution.put("width", res.getInt("width"));
                            resolution.put("height", res.getInt("height"));
                        } else {
                            console.print("Profile " + name != null ? name : "UNKNOWN" + " has an invalid resolution.");
                        }
                    }
                    Profile p = new Profile(key, name, type, created, lastUsed, version, gameDir, javaDir, javaArgs, resolution, icon, latestRelease, latestSnapshot);
                    if (first == null) {
                        first = p;
                    }
                    if (!profiles.contains(p)) {
                        addProfile(p);
                        if (p.getLastUsed().compareTo(latestUsedMillis) > 0) {
                            latestUsedMillis = p.getLastUsed();
                            latestUsedID = p;
                        }
                        if (type == ProfileType.RELEASE && releaseProfile == null) {
                            releaseProfile = p;
                        } else if (type == ProfileType.SNAPSHOT && snapshotProfile == null) {
                            snapshotProfile = p;
                        }
                    }
                }
                if (releaseProfile == null) {
                    releaseProfile = new Profile(ProfileType.RELEASE);
                    if (first == null) {
                        first = releaseProfile;
                    }
                    addProfile(releaseProfile);
                }
                if (snapshotProfile == null) {
                    snapshotProfile = new Profile(ProfileType.SNAPSHOT);
                    addProfile(snapshotProfile);
                }
                if (latestUsedID != null) {
                    Settings settings = kernel.getSettings();
                    if (latestUsedID.getType() == ProfileType.SNAPSHOT && !settings.getEnableSnapshots()) {
                        setSelectedProfile(releaseProfile);
                    } else if (latestUsedID.getType() == ProfileType.CUSTOM) {
                        VersionType type = latestUsedID.getVersionID().getType();
                        if (type == VersionType.SNAPSHOT && !settings.getEnableSnapshots()) {
                            setSelectedProfile(releaseProfile);
                        } else if (type == VersionType.OLD_ALPHA && !settings.getEnableHistorical()) {
                            setSelectedProfile(releaseProfile);
                        } else if (type == VersionType.OLD_BETA && !settings.getEnableHistorical()) {
                            setSelectedProfile(releaseProfile);
                        } else {
                            setSelectedProfile(latestUsedID);
                        }
                    } else {
                        setSelectedProfile(latestUsedID);
                    }
                } else {
                    console.print("No profile is selected! Using first loaded (" + first + ')');
                    setSelectedProfile(first);
                }
            } catch (JSONException ex) {
                console.print("Failed to fetch profiles.");
                ex.printStackTrace(console.getWriter());
            }
        } else {
            console.print("No profiles to be loaded. Generating defaults.");
            if (releaseProfile == null) {
                releaseProfile = new Profile(ProfileType.RELEASE);
                addProfile(releaseProfile);
            }
            if (snapshotProfile == null) {
                snapshotProfile = new Profile(ProfileType.SNAPSHOT);
                addProfile(snapshotProfile);
            }
        }
        if (selected == null) {
            setSelectedProfile(releaseProfile);
        }
    }

    /**
     * Gets a profile by id
     * @param id The id to search
     * @return The profile that matches the id or null
     */
    public final Profile getProfile(String id) {
        for (Profile p : profiles) {
            if (p.getID().equalsIgnoreCase(id)) {
                return p;
            }
        }
        return null;
    }

    /**
     * Returns the selected profile
     * @return The selected profile
     */
    public final Profile getSelectedProfile() {
        return selected;
    }

    /**
     * Returns the release profile
     * @return The release profile
     */
    public final Profile getReleaseProfile() {
        return releaseProfile;
    }

    /**
     * Sets the current selected profile
     * @param p Profile to be selected
     */
    public void setSelectedProfile(Profile p) {
        p.setLastUsed(new Timestamp(System.currentTimeMillis()));
        selected = p;
        console.print("Profile " + p + " has been selected.");
    }

    /**
     * Converts the profile database to JSON
     * @return The json conversion of the profile database
     */
    public final JSONObject toJSON() {
        JSONObject o = new JSONObject();
        JSONObject profilesJSON = new JSONObject();
        for (Profile p : profiles) {
            JSONObject prof = new JSONObject();
            switch (p.getType()) {
                case RELEASE:
                    prof.put("type", "latest-release");
                    break;
                case SNAPSHOT:
                    prof.put("type", "latest-snapshot");
                    break;
                default:
                    prof.put("type", "custom");
            }
            if (p.getType() == ProfileType.CUSTOM) {
                if (p.hasName()) {
                    prof.put("name", p.getName());
                }
                if (p.hasVersion()) {
                    if (p.isLatestRelease()) {
                        prof.put("lastVersionId", "latest-release");
                    } else if (p.isLatestSnapshot()) {
                        prof.put("lastVersionId", "latest-snapshot");
                    } else {
                        prof.put("lastVersionId", p.getVersionID());
                    }
                }
                if (p.hasIcon()) {
                    prof.put("icon", p.getIcon());
                }
            }
            if (p.hasCreated()) {
                prof.put("created", p.getCreated().toString().replace(" ", "T") + 'Z');
            }
            prof.put("lastUsed", p.getLastUsed().toString().replace(" ", "T") + 'Z');
            if (p.hasGameDir()) {
                prof.put("gameDir", p.getGameDir().toString());
            }
            if (p.hasJavaDir()) {
                prof.put("javaDir", p.getJavaDir().toString());
            }
            if (p.hasJavaArgs()) {
                prof.put("javaArgs", p.getJavaArgs());
            }
            if (p.hasResolution()) {
                JSONObject res = new JSONObject();
                res.put("width", p.getResolutionWidth());
                res.put("height", p.getResolutionHeight());
                prof.put("resolution", res);
            }
            profilesJSON.put(p.getID(), prof);
        }
        o.put("profiles", profilesJSON);
        return o;
    }
} public class Versions {
    private final Set<VersionMeta> versions = new LinkedHashSet<>();
    private final Collection<Version> version_cache = new HashSet<>();
    private final Console console;
    private final Kernel kernel;
    private VersionMeta latestSnap, latestRel;

    public Versions(Kernel k) {
        kernel = k;
        console = k.getConsole();
    }

    /**
     * Gets the version meta by id
     * @param id The id to fetch the version meta
     * @return The version meta from the specified id or from the latest release
     */
    public final VersionMeta getVersionMeta(String id) {
        if (id != null) {
            switch (id) {
                case "latest-release":
                    return latestRel;
                case "latest-snapshot":
                    return latestSnap;
            }
            for (VersionMeta m : versions) {
                if (m.getID().equalsIgnoreCase(id)) {
                    return m;
                }
            }
        }
        return latestRel;
    }

    /**
     * Gets the version data from a version meta
     * @param vm The target version meta
     * @return The version data from the specified version meta or null if an error happened
     */
    public final Version getVersion(VersionMeta vm) {
        if (versions.contains(vm)) {
            for (Version v : version_cache) {
                if (v.getID().equalsIgnoreCase(vm.getID())) {
                    return v;
                }
            }
            try {
                Version v = new Version(vm.getURL(), kernel);
                version_cache.add(v);
                return v;
            } catch (Exception ex) {
                console.print(ex.getMessage());
                return null;
            }
        }
        console.print("Version id " + vm.getID() + " not found.");
        return null;
    }

    /**
     * Loads versions from Mojang servers or from local versions
     */
    public final void fetchVersions() {
        String lr = "", ls = "";
        console.print("Fetching remote version list.");
        try {
            String versionManifest = "https://launchermeta.mojang.com/mc/game/version_manifest.json";
            String response = Utils.readURL(versionManifest);
            if (!response.isEmpty()) {
                JSONObject root = new JSONObject(response);
                if (root.has("latest")) {
                    JSONObject latest = root.getJSONObject("latest");
                    if (latest.has("snapshot")) {
                        ls = latest.getString("snapshot");
                    }
                    if (latest.has("release")) {
                        lr = latest.getString("release");
                    }
                }
                JSONArray vers = root.getJSONArray("versions");
                for (int i = 0; i < vers.length(); i++) {
                    JSONObject ver = vers.getJSONObject(i);
                    String id = null;
                    VersionType type;
                    String url = null;
                    if (ver.has("id")) {
                        id = ver.getString("id");
                    }
                    if (ver.has("url")) {
                        url = ver.getString("url");
                    }
                    if (id == null || url == null) {
                        continue;
                    }
                    if (ver.has("type")) {
                        try {
                            type = VersionType.valueOf(ver.getString("type").toUpperCase(Locale.ENGLISH));
                        } catch (IllegalArgumentException ex) {
                            type = VersionType.RELEASE;
                            console.print("Invalid type for version " + id);
                        }
                    } else {
                        type = VersionType.RELEASE;
                        console.print("Remote version " + id + " has no version type. Will be loaded as a RELEASE.");
                    }
                    VersionMeta vm = new VersionMeta(id, url, type);
                    if (lr.equalsIgnoreCase(id)) {
                        latestRel = vm;
                    }
                    if (ls.equalsIgnoreCase(id)) {
                        latestSnap = vm;
                    }
                    versions.add(vm);
                }
                console.print("Remote version list loaded.");
            } else {
                console.print("Remote version list returned empty response.");
            }
        } catch (JSONException ex) {
            console.print("Failed to fetch remote version list.");
            ex.printStackTrace(console.getWriter());
        }
        console.print("Fetching local version list versions.");
        VersionMeta lastRelease = null, lastSnapshot = null;
        String latestRelease = "", latestSnapshot = "";
        File versionsDir = new File(Kernel.APPLICATION_WORKING_DIR, "versions");
        try {
            if (versionsDir.isDirectory()) {
                File[] files = versionsDir.listFiles();
                if (files != null) {
                    for (File file : files) {
                        if (file.isDirectory()) {
                            File jsonFile = new File(file.getAbsolutePath(), file.getName() + ".json");
                            if (jsonFile.isFile()) {
                                String id;
                                String url = jsonFile.toURI().toURL().toString();
                                VersionType type;
                                JSONObject ver = new JSONObject(Utils.readURL(url));
                                if (ver.has("id")) {
                                    id = ver.getString("id");
                                } else {
                                    continue;
                                }
                                if (ver.has("type")) {
                                    try {
                                        type = VersionType.valueOf(ver.getString("type").toUpperCase(Locale.ENGLISH));
                                    } catch (IllegalArgumentException ex) {
                                        type = VersionType.RELEASE;
                                        console.print("Invalid type for version " + id);
                                    }
                                } else {
                                    type = VersionType.RELEASE;
                                    console.print("Local version " + id + " has no version type. Will be loaded as a RELEASE.");
                                }
                                VersionMeta vm = new VersionMeta(id, url, type);
                                versions.add(vm);
                                if (ver.has("releaseTime")) {
                                    if (type == VersionType.RELEASE && ver.getString("releaseTime").compareTo(latestRelease) > 0) {
                                        lastRelease = vm;
                                        latestRelease = ver.getString("releaseTime");
                                    } else if (type == VersionType.SNAPSHOT && ver.getString("releaseTime").compareTo(latestSnapshot) > 0) {
                                        lastSnapshot = vm;
                                        latestSnapshot = ver.getString("releaseTime");
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (latestRel == null && lastRelease != null) {
                latestRel = lastRelease;
            }
            if (latestSnap == null && lastSnapshot != null) {
                latestSnap = lastSnapshot;
            }
            console.print("Local version list loaded.");
        } catch (JSONException | IOException ex) {
            console.print("Failed to fetch local version list.");
            ex.printStackTrace(console.getWriter());
        }
    }

    /**
     * Returns the version database
     * @return The version database
     */
    public final Iterable<VersionMeta> getVersions() {
        return versions;
    }

    /**
     * Returns the latest release
     * @return The latest release
     */
    public final VersionMeta getLatestRelease() {
        return latestRel;
    }

    /**
     * Returns the latest snapshot
     * @return The latest snapshot
     */
    public final VersionMeta getLatestSnapshot() {
        return latestSnap;
    }
} public class BrowserFX {
    @FXML
    private WebView webBrowser;

    private Stage stage;
    private Scene browser;
    private Scene main;

    public final void initialize(Stage s, Scene browser) {
        stage = s;
        this.browser = browser;
        final WebEngine engine = webBrowser.getEngine();
        engine.setJavaScriptEnabled(true);
        engine.getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {
            @Override
            public void changed(ObservableValue<? extends State> observable, State oldValue, State newValue) {
                if (newValue.equals(State.SUCCEEDED)) {
                    String location = engine.getLocation();
                    if (!location.contains("sh.st") && !location.contains("krothium.com") && !location.contains("about:blank")) {
                        webBrowser.getEngine().load("about:blank");
                    }
                    if (location.contains("about:blank")) {
                        double stageW = stage.widthProperty().doubleValue();
                        double stageH = stage.heightProperty().doubleValue();
                        stage.setScene(main);
                        if (!Double.isNaN(stageH) && !Double.isNaN(stageW)) {
                            stage.setWidth(stageW);
                            stage.setHeight(stageH);
                        }
                    }
                }
            }
        });
    }

    public final void loadWebsite(String url) {
        webBrowser.getEngine().load(url);
    }

    public final void show(Scene main) {
        this.main = main;
        double stageW = stage.widthProperty().doubleValue();
        double stageH = stage.heightProperty().doubleValue();
        stage.setScene(browser);
        if (!Double.isNaN(stageH) && !Double.isNaN(stageW)) {
            stage.setWidth(stageW);
            stage.setHeight(stageH);
        }

    }
} public class MainFX {

    @FXML private Label progressText, newsLabel, skinsLabel, settingsLabel, launchOptionsLabel,
            keepLauncherOpen, outputLog, enableSnapshots, historicalVersions,
            advancedSettings, resolutionLabel, gameDirLabel, javaExecLabel, javaArgsLabel, accountButton,
            switchAccountButton, languageButton, newsTitle, newsText, slideBack, slideForward, rotateRight,
            rotateLeft, includeCape, versionLabel, usernameLabel, passwordLabel, existingLabel, launcherSettings,
            nameLabel, profileVersionLabel, skinLabel, capeLabel, modelLabel, iconLabel, helpButton, gameVersion,
            authenticationLabel, authServer;
    @FXML private Button playButton, deleteButton, changeIcon, deleteSkin, deleteCape, logoutButton,
            loginButton, registerButton, loginExisting, cancelButton, saveButton, selectSkin,
            selectCape, exportLogs, downloadServer, deleteCache, profilePopupButton;
    @FXML private Tab loginTab, newsTab, skinsTab,
            settingsTab, launchOptionsTab, profileEditorTab;
    @FXML private ProgressBar progressBar;
    @FXML private TabPane contentPane;
    @FXML private ListView<Label> languagesList, profileList, profilePopupList;
    @FXML private ListView<ImageView> iconList;
    @FXML private VBox progressPane, existingPanel, playPane, skinActions, newsContainer;
    @FXML private HBox tabMenu, slideshowBox;
    @FXML private TextField username, profileName,javaExec, gameDir, javaArgs,
            resH, resW;
    @FXML private PasswordField password;
    @FXML private ComboBox<User> existingUsers;
    @FXML private ComboBox<VersionMeta> versionList;
    @FXML private StackPane versionBlock, javaArgsBlock, javaExecBlock, iconBlock;
    @FXML private ImageView profileIcon, slideshow, skinPreview;
    @FXML private RadioButton skinClassic, skinSlim, authKrothium, authMojang;
    @FXML private Hyperlink forgotPasswordLink;

    private Kernel kernel;
    private Console console;
    private Settings settings;
    private Stage stage;
    private Scene mainScene;
    private final List<Slide> slides = new ArrayList<>();
    private int currentSlide;
    private int currentPreview; // 0 = front / 1 = right / 2 = back / 3 = left
    private final Image[] skinPreviews = new Image[4];
    private Image skin, cape, alex, steve;
    private boolean texturesLoaded;
    private String urlPrefix = "";
    private boolean iconListLoaded, versionListLoaded, languageListLoaded, loadingTextures, profileListLoaded,
            profileListPopupLoaded;

    /**
     * Initializes all required stuff from the GUI
     * @param k The Kernel instance
     * @param s The Stage instance
     */
    public final void initialize(Kernel k, Stage s, Scene scene, final Scene browser) {
        //Require to exit using Platform.exit()
        Platform.setImplicitExit(false);

        //Set kernel and stage
        kernel = k;
        console = k.getConsole();
        settings = k.getSettings();
        stage = s;
        mainScene = scene;

        //Update version label
        versionLabel.setText(Kernel.KERNEL_BUILD_NAME);

        //Load news slideshow
        slideshowBox.setVisible(false);
        slideshowBox.setManaged(false);
        newsTitle.setText("Loading news...");
        newsText.setText("Please wait a moment...");
        loadSlideshow();

        //Refresh session
        refreshSession();

        //Prepare language list
        languageButton.setText(settings.getSupportedLocales().get(settings.getLocale()));

        //Update settings labels
        toggleLabel(keepLauncherOpen, settings.getKeepLauncherOpen());
        toggleLabel(outputLog, settings.getShowGameLog());
        toggleLabel(enableSnapshots, settings.getEnableSnapshots());
        toggleLabel(historicalVersions, settings.getEnableHistorical());
        toggleLabel(advancedSettings, settings.getEnableAdvanced());

        //Prepare Spinners
        resW.setEditable(true);
        resH.setEditable(true);

        //If offline mode make play button bigger for language support and hide skins tab
        if (Kernel.USE_LOCAL) {
            skinsLabel.setVisible(false);
            skinsLabel.setManaged(false);
        }

        //Localize elements
        localizeElements();

        //Validate selected profile
        validateSelectedProfile();

        //Manual component resize binding to fix JavaFX maximize bug
        TimerTask newsResize = new TimerTask() {
            @Override
            public void run() {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        if (!MainFX.this.stage.isMaximized()) {
                            Window w = MainFX.this.mainScene.getWindow();
                            if (w == null) {
                                w = browser.getWindow();
                            }
                            if (w != null) {
                                settings.setLauncherHeight(w.getHeight());
                                settings.setLauncherWidth(w.getWidth());
                            }
                        }
                        double computedHeight = MainFX.this.newsContainer.heightProperty().doubleValue()  * 0.7;
                        double computedWidth = MainFX.this.newsContainer.widthProperty().doubleValue()  * 0.7;
                        if (MainFX.this.slideshow.getImage() != null) {
                            if (computedHeight > MainFX.this.slideshow.getImage().getHeight()) {
                                MainFX.this.slideshow.setFitHeight(MainFX.this.slideshow.getImage().getHeight());
                            } else {
                                MainFX.this.slideshow.setFitHeight(computedHeight);
                            }
                            if (computedWidth > MainFX.this.slideshow.getImage().getWidth()) {
                                MainFX.this.slideshow.setFitWidth(MainFX.this.slideshow.getImage().getWidth());
                            } else {
                                MainFX.this.slideshow.setFitWidth(computedWidth);
                            }
                        }
                    }
                });
            }
        };
        Timer resize = new Timer();
        resize.schedule(newsResize, 0, 25);

        //Close popups on resize
        mainScene.heightProperty().addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
                MainFX.this.checkPopups();
            }
        });
        mainScene.widthProperty().addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
                MainFX.this.checkPopups();
            }
        });
    }

    /**
     * Load language list
     */
    private void loadLanguages() {
        console.print("Loading languages...");
        HashMap<String, String> supportedLocales = settings.getSupportedLocales();
        ObservableList<Label> languageListItems = FXCollections.observableArrayList();
        for (String key : supportedLocales.keySet()) {
            Image i = new Image("/kml/gui/textures/flags/flag_" + key + ".png");
            Label l = new Label(supportedLocales.get(key), new ImageView(i));
            l.setId(key);
            languageListItems.add(l);
        }
        languagesList.setItems(languageListItems);
        console.print("Languages loaded.");
    }

    /**
     * Fetches any advertisement available for the logged user
     */
    private void fetchAds() {
        User user = kernel.getAuthentication().getSelectedUser();
        if (user.getType() != UserType.MOJANG) {
            String profileID = user.getSelectedProfile();
            String adsCheck = "https://mc.krothium.com/ads.php?profileID=" + profileID;
            String response = Utils.readURL(adsCheck);
            if (!response.isEmpty()) {
                String[] chunks = response.split(":");
                String firstChunk = Utils.fromBase64(chunks[0]);
                urlPrefix = firstChunk == null ? "" : firstChunk;
                if (chunks.length == 2) {
                    String secondChunk = Utils.fromBase64(response.split(":")[1]);
                    String adsURL = secondChunk == null ? "" : secondChunk;
                    kernel.getBrowser().loadWebsite(adsURL);
                    kernel.getBrowser().show(mainScene);
                }
                console.print("Ads loaded.");
            } else {
                console.print("Ads info not available.");
            }
        } else {
            console.print("Ads not available for Mojang user.");
        }
    }

    /**
     * Updates all components text with its localized Strings
     */
    private void localizeElements() {
        helpButton.setText(Language.get(2));
        logoutButton.setText(Language.get(3));
        newsLabel.setText(Language.get(4));
        skinsLabel.setText(Language.get(5));
        settingsLabel.setText(Language.get(6));
        launchOptionsLabel.setText(Language.get(7));
        if (kernel.getGameLauncher().isRunning()) {
            playButton.setText(Language.get(14));
        } else {
            if (Kernel.USE_LOCAL) {
                playButton.setText(Language.get(79));
            } else {
                playButton.setText(Language.get(12));
            }
        }
        usernameLabel.setText(Language.get(18));
        passwordLabel.setText(Language.get(19));
        loginButton.setText(Language.get(20));
        loginExisting.setText(Language.get(20));
        registerButton.setText(Language.get(21));
        changeIcon.setText(Language.get(24));
        exportLogs.setText(Language.get(27));
        downloadServer.setText(Language.get(28));
        skinLabel.setText(Language.get(29));
        capeLabel.setText(Language.get(30));
        launcherSettings.setText(Language.get(45));
        keepLauncherOpen.setText(Language.get(46));
        outputLog.setText(Language.get(47));
        enableSnapshots.setText(Language.get(48));
        historicalVersions.setText(Language.get(49));
        advancedSettings.setText(Language.get(50));
        saveButton.setText(Language.get(52));
        cancelButton.setText(Language.get(53));
        deleteButton.setText(Language.get(54));
        nameLabel.setText(Language.get(63));
        profileVersionLabel.setText(Language.get(64));
        resolutionLabel.setText(Language.get(65));
        gameDirLabel.setText(Language.get(66));
        javaExecLabel.setText(Language.get(67));
        javaArgsLabel.setText(Language.get(68));
        existingLabel.setText(Language.get(85));
        switchAccountButton.setText(Language.get(86));
        selectSkin.setText(Language.get(87));
        selectCape.setText(Language.get(87));
        deleteSkin.setText(Language.get(88));
        deleteCape.setText(Language.get(88));
        modelLabel.setText(Language.get(89));
        skinClassic.setText(Language.get(90));
        skinSlim.setText(Language.get(91));
        iconLabel.setText(Language.get(92));
        includeCape.setText(Language.get(93));
        deleteCache.setText(Language.get(94));
        forgotPasswordLink.setText(Language.get(97));
        profileName.setPromptText(Language.get(98));
        authenticationLabel.setText(Language.get(99));
        if (slides.isEmpty()) {
            newsTitle.setText(Language.get(102));
            newsText.setText(Language.get(103));
        }
        updateGameVersion();
    }

    /**
     * Loads the skin preview for the logged user
     */
    private void loadTextures() {
        if (loadingTextures) {
            return;
        }
        selectSkin.setDisable(true);
        selectCape.setDisable(true);
        deleteSkin.setDisable(true);
        deleteCape.setDisable(true);
        includeCape.setDisable(true);
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    console.print("Loading textures...");
                    loadingTextures = true;
                    if (alex == null || steve == null) {
                        //Load placeholder skins
                        alex = new Image("/kml/gui/textures/alex.png");
                        steve = new Image("/kml/gui/textures/steve.png");
                    }
                    User selected = kernel.getAuthentication().getSelectedUser();
                    String domain;
                    if (selected.getType() == UserType.MOJANG) {
                        domain = "sessionserver.mojang.com/session/minecraft/profile/";
                        skinActions.setVisible(false);
                        skinActions.setManaged(false);
                    } else {
                        domain = "mc.krothium.com/profiles/";
                        skinActions.setVisible(true);
                        skinActions.setManaged(true);
                    }
                    String profileURL = "https://" + domain + selected.getSelectedProfile() + "?unsigned=true";
                    JSONObject root = new JSONObject(Utils.readURL(profileURL));
                    JSONArray properties = root.getJSONArray("properties");
                    for (int i = 0; i < properties.length(); i++) {
                        JSONObject property = properties.getJSONObject(i);
                        if ("textures".equalsIgnoreCase(property.getString("name"))) {
                            JSONObject data = new JSONObject(Utils.fromBase64(property.getString("value")));
                            JSONObject textures = data.getJSONObject("textures");
                            skin = null;
                            cape = null;
                            boolean slim = false;
                            if (textures.has("SKIN")) {
                                JSONObject skinData = textures.getJSONObject("SKIN");
                                if (skinData.has("metadata")) {
                                    if ("slim".equalsIgnoreCase(skinData.getJSONObject("metadata").getString("model"))) {
                                        slim = true;
                                    }
                                }
                                InputStream stream = Utils.readCachedStream(textures.getJSONObject("SKIN").getString("url"));
                                skin = new Image(stream);
                                stream.close();
                            }
                            if (skin == null || skin.getHeight() == 0 && !slim) {
                                skin = steve;
                            } else if (skin.getHeight() == 0) {
                                skin = alex;
                            } else {
                                deleteSkin.setDisable(false);
                            }
                            if (textures.has("CAPE")) {
                                InputStream stream = Utils.readCachedStream(textures.getJSONObject("CAPE").getString("url"));
                                cape = new Image(stream);
                                stream.close();
                                includeCape.setDisable(false);
                                deleteCape.setDisable(false);
                            }
                            if (slim) {
                                skinSlim.setSelected(true);
                            } else {
                                skinClassic.setSelected(true);
                            }
                            texturesLoaded = true;
                            console.print("Textures loaded.");
                            MainFX.this.updatePreview();
                        }
                    }
                    selectSkin.setDisable(false);
                    selectCape.setDisable(false);
                } catch (Exception ex) {
                    console.print("Failed to parse remote profile textures.");
                    ex.printStackTrace(console.getWriter());
                }
                loadingTextures = false;
            }
        });
        t.start();
    }

    /**
     * Toggles the label of the toggle cape button
     */
    @FXML public final void toggleCapePreview() {
        if (includeCape.getStyleClass().contains("toggle-enabled")) {
            toggleLabel(includeCape, false);
        } else {
            toggleLabel(includeCape, true);
        }
        updatePreview();
    }

    /**
     * Changes the skin type
     */
    @FXML public final void toggleSkinType() {
        if (deleteSkin.isDisabled()) {
            if (skinClassic.isSelected()) {
                skin = steve;
            } else {
                skin = alex;
            }
            updatePreview();
        }
    }

    /**
     * Updates the skin preview
     */
    private void updatePreview() {
        if (skin == null) {
            return;
        }
        boolean slim = skinSlim.isSelected();
        if (includeCape.getStyleClass().contains("toggle-enabled")) {
            skinPreviews[0] = TexturePreview.resampleImage(TexturePreview.generateFront(skin, cape, slim), 10);
            skinPreviews[1] = TexturePreview.resampleImage(TexturePreview.generateRight(skin, cape), 10);
            skinPreviews[2] = TexturePreview.resampleImage(TexturePreview.generateBack(skin, cape, slim), 10);
            skinPreviews[3] = TexturePreview.resampleImage(TexturePreview.generateLeft(skin, cape), 10);
        } else {
            skinPreviews[0] = TexturePreview.resampleImage(TexturePreview.generateFront(skin, null, slim), 10);
            skinPreviews[1] = TexturePreview.resampleImage(TexturePreview.generateRight(skin, null), 10);
            skinPreviews[2] = TexturePreview.resampleImage(TexturePreview.generateBack(skin, null, slim), 10);
            skinPreviews[3] = TexturePreview.resampleImage(TexturePreview.generateLeft(skin, null), 10);
        }
        skinPreview.setImage(skinPreviews[currentPreview]);
    }

    /**
     * Submits a texure change
     * @param target Skin or cape
     * @param file File to be submited. Null if it's a deletion.
     */
    private void submitChange(String target, File file) {
        String CHANGESKIN_URL = "https://mc.krothium.com/changeskin";
        String CHANGECAPE_URL = "https://mc.krothium.com/changecape";
        String url = target.equals("skin") ? CHANGESKIN_URL : CHANGECAPE_URL;
        Map<String, String> params = new HashMap<>();
        params.put("Access-Token", kernel.getAuthentication().getSelectedUser().getAccessToken());
        params.put("Client-Token", kernel.getAuthentication().getClientToken());
        byte[] data = null;
        if (file != null) {
            if (file.length() > 131072) {
                if (target.equals("skin")) {
                    console.print("Skin file exceeds 128KB file size limit.");
                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            kernel.showAlert(Alert.AlertType.ERROR, null, Language.get(105));
                        }
                    });
                } else {
                    console.print("Cape file exceeds 128KB file size limit.");
                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            kernel.showAlert(Alert.AlertType.ERROR, null, Language.get(104));
                        }
                    });
                }
                return;
            }
            try {
                data = Files.readAllBytes(file.toPath());
                if (target.equals("skin")) {
                    if (skinSlim.isSelected()) {
                        params.put("Skin-Type", "alex");
                    } else {
                        params.put("Skin-Type", "steve");
                    }
                }
                params.put("Content-Type", "image/png");
            } catch (Exception ex) {
                console.print("Failed read textures.");
                ex.printStackTrace(console.getWriter());
            }
        }
        try {
            String r = Utils.sendPost(url, data, params);
            String text;
            if (!"OK".equals(r)) {
                if (target.equals("skin")) {
                    if (file != null) {
                        text = Language.get(42);
                    } else {
                        text = Language.get(33);
                    }
                } else {
                    if (file != null) {
                        text = Language.get(43);
                    } else {
                        text = Language.get(38);
                    }
                }
                console.print("Failed to " + (file != null ? "change" : "delete") + " the " + target + ".");
                console.print(r);
                final String finalText = text;
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        kernel.showAlert(Alert.AlertType.ERROR, null, finalText);
                    }
                });
                return;
            }
            if (target.equals("skin")) {
                if (file != null) {
                    text = Language.get(40);
                } else {
                    text = Language.get(34);
                }
            } else {
                if (file != null) {
                    text = Language.get(41);
                } else {
                    text = Language.get(39);
                }
            }
            target = target.substring(0, 1).toUpperCase() + target.substring(1);
            console.print(target + " " + (file != null ? "changed" : "deleted") + " successfully!");
            final String finalText = text;
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    kernel.showAlert(Alert.AlertType.INFORMATION, null, finalText);
                }
            });
            loadTextures();
        } catch (IOException ex) {
            console.print("Failed to perform textures post.");
            ex.printStackTrace(console.getWriter());
        }
    }

    /**
     * Changes the skin of the user
     */
    @FXML private void changeSkin() {
        final File selected = selectFile(Language.get(44), "*.png", "open");
        if (selected != null) {
            selectSkin.setDisable(true);
            deleteSkin.setDisable(true);
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    MainFX.this.submitChange("skin", selected);
                }
            });
            t.start();
        }
    }

    /**
     * Changes the cape of the user
     */
    @FXML private void changeCape() {
        final File selected = selectFile(Language.get(25), "*.png", "open");
        if (selected != null) {
            selectCape.setDisable(true);
            deleteCape.setDisable(true);
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    MainFX.this.submitChange("cape", selected);
                }
            });
            t.start();
        }

    }

    /**
     * Deletes the skin of the user
     */
    @FXML private void deleteSkin() {
        int result = kernel.showAlert(Alert.AlertType.CONFIRMATION, null, Language.get(31));
        if (result == 1){
            selectSkin.setDisable(true);
            deleteSkin.setDisable(true);
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    MainFX.this.submitChange("skin", null);
                }
            });
            t.start();
        }
    }

    /**
     * Deletes the cape of the user
     */
    @FXML private void deleteCape() {
        int result = kernel.showAlert(Alert.AlertType.CONFIRMATION, null, Language.get(36));
        if (result == 1){
            selectCape.setDisable(true);
            deleteCape.setDisable(true);
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    MainFX.this.submitChange("cape", null);
                }
            });
            t.start();
        }
    }

    /**
     * Loads the news slideshow
     */
    private void loadSlideshow() {
        console.print("Loading news slideshow...");
        try {
            String newsURL = "https://launchermeta.mojang.com/mc/news.json";
            String response = Utils.readURL(newsURL);
            if (response.isEmpty()) {
                console.print("News data returned empty response.");
                return;
            }
            JSONObject root = new JSONObject(response);
            JSONArray entries = root.getJSONArray("entries");
            for (int i = 0; i < entries.length(); i++) {
                JSONObject entry = entries.getJSONObject(i);
                boolean isDemo = false;
                JSONArray tags = entry.getJSONArray("tags");
                for (int j = 0; j < tags.length(); j++) {
                    if ("demo".equalsIgnoreCase(tags.getString(j))) {
                        isDemo = true;
                        break;
                    }
                }
                if (isDemo) {
                    continue;
                }
                JSONObject content = entry.getJSONObject("content").getJSONObject("en-us");
                Slide s = new Slide(content.getString("action"), content.getString("image"), content.getString("title"), content.getString("text"));
                slides.add(s);
            }
        } catch (Exception ex) {
            newsTitle.setText(Language.get(80));
            newsText.setText(Language.get(101));
            console.print("Couldn't parse news data.");
            ex.printStackTrace(console.getWriter());
            return;
        }
        if (!slides.isEmpty()) {
            slideshowBox.setVisible(true);
            slideshowBox.setManaged(true);
            Slide s = slides.get(0);
            Image i = s.getImage();
            if (i != null) {
                slideshow.setImage(s.getImage());
            }
            newsTitle.setText(s.getTitle());
            newsText.setText(s.getText());
        } else {
            newsTitle.setText(Language.get(102));
            newsText.setText(Language.get(103));
        }
        console.print("News slideshow loaded.");
    }

    /**
     * Changes the news slide
     * @param e The trigger event
     */
    @FXML public final void changeSlide(MouseEvent e) {
        if (slides.isEmpty()) {
            //No slides
            return;
        }
        Label source = (Label)e.getSource();
        if (source == slideBack) {
            if (currentSlide == 0) {
                currentSlide = slides.size() - 1;
            } else {
                currentSlide--;
            }
        } else if (source == slideForward) {
            if (currentSlide == slides.size() - 1) {
                currentSlide = 0;
            } else {
                currentSlide++;
            }
        }
        final Slide s = slides.get(currentSlide);
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                Image i = s.getImage();
                if (i != null) {
                    slideshow.setImage(i);
                }
            }
        });
        t.start();
        newsTitle.setText(s.getTitle());

        newsText.setText(s.getText());
    }

    /**
     * Performs an action when a slide is clicked
     */
    @FXML public final void performSlideAction() {
        if (slides.isEmpty()) {
            //No slides
            return;
        }
        Slide s = slides.get(currentSlide);
        kernel.getHostServices().showDocument(urlPrefix + s.getAction());
    }

    /**
     * Rotates the skin preview
     * @param e The trigger event
     */
    @FXML public final void rotatePreview(MouseEvent e) {
        Label src = (Label)e.getSource();
        if (src == rotateRight) {
            if (currentPreview < 3) {
                currentPreview++;
                skinPreview.setImage(skinPreviews[currentPreview]);
            } else {
                currentPreview = 0;
                skinPreview.setImage(skinPreviews[currentPreview]);
            }
        } else if (src == rotateLeft) {
            if (currentPreview > 0) {
                currentPreview--;
                skinPreview.setImage(skinPreviews[currentPreview]);
            } else {
                currentPreview = 3;
                skinPreview.setImage(skinPreviews[currentPreview]);
            }
        }
    }

    /**
     * Loads profiles list items
     */
    private void loadProfileList() {
        console.print("Loading profile list...");
        ObservableList<Label> profileListItems = getProfileList();

        //Add "Add New Profile" item
        profileListItems.add(0, new Label(Language.get(51), new ImageView(new Image("/kml/gui/textures/add.png"))));
        profileList.setItems(profileListItems);
        profileListLoaded = true;
        console.print("Profile list loaded.");
    }

    /**
     * Loads profiles popup list items
     */
    private void loadProfileListPopup() {
        console.print("Loading profile list popup...");
        ObservableList<Label> profileListItems = getProfileList();
        profilePopupList.setItems(profileListItems);
        profileListPopupLoaded = true;
        console.print("Profile list popup loaded.");
    }

    /**
     * Generates an ObservableList of Labels representing each profile
     * @return The profiles ObservableList
     */
    private ObservableList<Label> getProfileList() {
        ObservableList<Label> profileListItems = FXCollections.observableArrayList();
        Profiles ps = kernel.getProfiles();
        Label l;
        ImageView iv;
        String text;
        for (Profile p : ps.getProfiles()) {
            if (p.getType() == ProfileType.SNAPSHOT && !settings.getEnableSnapshots()) {
                continue;
            }
            switch (p.getType()) {
                case RELEASE:
                    iv = new ImageView(kernel.getProfileIcon("Grass"));
                    text = Language.get(59);
                    break;
                case SNAPSHOT:
                    iv = new ImageView(kernel.getProfileIcon("Crafting_Table"));
                    text = Language.get(60);
                    break;
                default:
                    text = p.hasName() ? p.getName() : Language.get(70);
                    String pi = p.hasIcon() ? p.getIcon() : "Furnace";
                    iv = new ImageView(kernel.getProfileIcon(pi));
                    break;
            }
            iv.setFitWidth(68);
            iv.setFitHeight(68);
            l = new Label(text, iv);
            //Fetch Minecraft version used by the profile
            VersionMeta verID;
            switch (p.getType()) {
                case CUSTOM:
                    Versions versions = kernel.getVersions();
                    verID = p.hasVersion() ? p.getVersionID() : versions.getLatestRelease();
                    break;
                case RELEASE:
                    verID = kernel.getVersions().getLatestRelease();
                    break;
                default:
                    verID = kernel.getVersions().getLatestSnapshot();
                    break;
            }
            l.setId(p.getID());
            if (verID != null) {
                //If profile has any known version just show it below the profile name
                if (verID.getType() == VersionType.SNAPSHOT && !settings.getEnableSnapshots()) {
                    continue;
                }
                if ((verID.getType() == VersionType.OLD_ALPHA || verID.getType() == VersionType.OLD_BETA) && !settings.getEnableHistorical()) {
                    continue;
                }
                l.setText(l.getText() + '\n' + verID.getID());
            }
            if (ps.getSelectedProfile().equals(p)) {
                l.getStyleClass().add("selectedProfile");
            }
            profileListItems.add(l);
        }
        return profileListItems;
    }

    /**
     * Updates the selected minecraft version indicator
     */
    private void updateGameVersion() {
        Profile p = kernel.getProfiles().getSelectedProfile();
        if (p != null) {
            switch (p.getType()) {
                case RELEASE:
                    gameVersion.setText(Language.get(26));
                    break;
                case SNAPSHOT:
                    gameVersion.setText(Language.get(32));
                    break;
                default:
                    if (p.isLatestRelease()) {
                        gameVersion.setText(Language.get(26));
                    } else if (p.isLatestSnapshot()) {
                        gameVersion.setText(Language.get(32));
                    } else if (p.hasVersion()) {
                        VersionMeta version = p.getVersionID();
                        gameVersion.setText("Minecraft " + version.getID());
                    }
                    break;
            }
        }  else {
            gameVersion.setText("");
        }
    }

    /**
     * Loads the profile icons
     */
    private void loadIcons() {
        console.print("Loading icons...");
        ObservableList<ImageView> icons = FXCollections.observableArrayList();
        Set<String> keys = kernel.getIcons().keySet();
        for (String key : keys) {
            if (!key.equals("Crafting_Table") && !key.equals("Grass")) {
                ImageView imv = new ImageView(kernel.getProfileIcon(key));
                imv.setFitHeight(68);
                imv.setFitWidth(68);
                imv.setId(key);
                icons.add(imv);
            }
        }
        iconList.setItems(icons);
        console.print("Icons loaded.");
    }

    /**
     * Validates the selected profile according to the constraints
     */
    private void validateSelectedProfile() {
        Profiles ps = kernel.getProfiles();

        //Check if selected profile passes the current settings
        Profile selected = ps.getSelectedProfile();
        VersionMeta selectedVersion = selected.getVersionID();

        if (selected.getType() == ProfileType.SNAPSHOT && !settings.getEnableSnapshots()) {
            ps.setSelectedProfile(ps.getReleaseProfile());
        } else if (selected.getType() == ProfileType.CUSTOM) {
            VersionType type = selectedVersion.getType();
            if (type == VersionType.SNAPSHOT && !settings.getEnableSnapshots()) {
                ps.setSelectedProfile(ps.getReleaseProfile());
            } else if (type == VersionType.OLD_ALPHA && !settings.getEnableHistorical()) {
                ps.setSelectedProfile(ps.getReleaseProfile());
            } else if (type == VersionType.OLD_BETA && !settings.getEnableHistorical()) {
                ps.setSelectedProfile(ps.getReleaseProfile());
            }
        }

        updateGameVersion();
    }

    /**
     * Selects the selected profile from the list
     */
    @FXML private void selectProfile() {
        if (profilePopupList.getSelectionModel().getSelectedIndex() == -1) {
            //Nothing has been selected
            return;
        }
        //Select profile and refresh list
        kernel.getProfiles().setSelectedProfile(kernel.getProfiles().getProfile(profilePopupList.getSelectionModel().getSelectedItem().getId()));
        updateGameVersion();
        SingleSelectionModel<Tab> selection = contentPane.getSelectionModel();
        Tab selectedTab = selection.getSelectedItem();
        if (selectedTab == launchOptionsTab) {
            loadProfileList();
        } else {
            profileListLoaded = false;
        }
        profileListPopupLoaded = false;
        profilePopupList.setVisible(false);
        kernel.saveProfiles();
    }

    /**
     * Downloads and launches the game
     */
    @FXML public final void launchGame() {
        progressPane.setVisible(true);
        playPane.setVisible(false);
        progressBar.setProgress(0);
        progressText.setText("");
        final Downloader d = kernel.getDownloader();
        final GameLauncher gl = kernel.getGameLauncher();

        //Keep track of the progress
        final TimerTask progressTask = new TimerTask() {
            @Override
            public void run() {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        MainFX.this.progressBar.setProgress(d.getProgress());
                        MainFX.this.progressText.setText(Language.get(13) + ' ' + d.getCurrentFile() + "...");
                    }
                });
            }
        };

        Thread runThread = new Thread(new Runnable() {
            @Override
            public void run() {
                //Begin download and game launch task
                try {
                    Timer timer = new Timer();
                    timer.schedule(progressTask, 0, 25);
                    d.download();
                    timer.cancel();
                    timer.purge();
                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            progressText.setText(Language.get(78));
                            progressBar.setProgress(ProgressIndicator.INDETERMINATE_PROGRESS);
                        }
                    });
                    gl.launch(MainFX.this);

                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            progressPane.setVisible(false);
                            playPane.setVisible(true);
                            playButton.setText(Language.get(14));
                            playButton.setDisable(true);
                            profilePopupButton.setDisable(true);
                        }
                    });

                    if (!settings.getKeepLauncherOpen()) {
                        Platform.runLater(new Runnable() {
                            @Override
                            public void run() {
                                MainFX.this.stage.close();
                            }
                        });
                    }
                } catch (DownloaderException e) {
                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            kernel.showAlert(Alert.AlertType.ERROR, Language.get(83), Language.get(84));
                        }
                    });
                    console.print("Failed to perform game download task");
                    e.printStackTrace(console.getWriter());
                } catch (GameLauncherException e) {
                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            kernel.showAlert(Alert.AlertType.ERROR, Language.get(81), Language.get(82));
                        }
                    });
                    console.print("Failed to perform game launch task");
                    e.printStackTrace(console.getWriter());
                }
            }
        });
        runThread.start();
    }

    /**
     * Callback from Game Launcher
     * @param error True if an error happened during launch
     */
    public final void gameEnded(final boolean error) {
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                if (error) {
                    kernel.showAlert(Alert.AlertType.ERROR, Language.get(16), Language.get(15));
                }
                if (!settings.getKeepLauncherOpen()) {
                    kernel.exitSafely();
                }
                playButton.setDisable(false);
                profilePopupButton.setDisable(false);
                if (Kernel.USE_LOCAL) {
                    playButton.setText(Language.get(79));
                } else {
                    playButton.setText(Language.get(12));
                }
            }
        });
    }

    /**
     * Shows the language list
     */
    @FXML public final void showLanguages(Event e) {
        e.consume();
        if (languagesList.isVisible()) {
            languagesList.setVisible(false);
        } else {
            if (!languageListLoaded) {
                loadLanguages();
                languageListLoaded = true;
            }
            languagesList.setVisible(true);
        }
    }

    public final void checkPopups() {
        if (languagesList.isVisible()) {
            languagesList.setVisible(false);
        }
        if (switchAccountButton.isVisible()) {
            switchAccountButton.setVisible(false);
        }
        if (profilePopupList.isVisible()) {
            profilePopupList.setVisible(false);
        }
        if (iconList.isVisible()) {
            iconList.setVisible(false);
        }
    }

    /**
     * Deselects the current user and allows to select another
     */
    @FXML public final void switchAccount() {
        if (switchAccountButton.isVisible()) {
            switchAccountButton.setVisible(false);
        }
        Authentication a = kernel.getAuthentication();
        a.setSelectedUser(null);
        kernel.saveProfiles();
        showLoginPrompt(true);
        updateExistingUsers();
    }

    /**
     * Shows the profile popup list
     */
    @FXML public final void showProfiles() {
        if (profilePopupList.isVisible()) {
            profilePopupList.setVisible(false);
        } else {
            if (!profileListPopupLoaded) {
                loadProfileListPopup();
            }
            Bounds b = playButton.localToScene(playButton.getBoundsInLocal());
            profilePopupList.setTranslateX(b.getMinX() - 70);
            profilePopupList.setTranslateY(b.getMinY() - 180);
            profilePopupList.setVisible(true);
            profilePopupList.getSelectionModel().clearSelection();
        }
    }

    /**
     * Shows the profile editor profile icons
     */
    @FXML public final void showIcons(Event e) {
        e.consume();
        if (iconList.isVisible()) {
            iconList.setVisible(false);
        } else {
            if (!iconListLoaded) {
                loadIcons();
                iconListLoaded = true;
            }
            //Calculate change icon button position on scene
            Bounds b = changeIcon.localToScene(changeIcon.getBoundsInLocal());
            iconList.setTranslateX(b.getMinX());
            iconList.setTranslateY(b.getMaxY());
            iconList.setVisible(true);
        }
    }

    /**
     * Shows the Switch Account option when the user label is clicked
     */
    @FXML public final void showAccountOptions(Event e) {
        e.consume();
        if (switchAccountButton.isVisible()) {
            switchAccountButton.setVisible(false);
        } else {
            switchAccountButton.setVisible(true);
        }
    }

    /**
     * Switched the selected tab according to the clicked label
     * @param e The trigger event
     */
    @FXML public final void switchTab(Event e) {
        switchTab(e.getSource());
    }

    /**
     * Switched the selected tab according to the source
     * @param source The object that trigger the change
     */
    private void switchTab(Object source) {
        SingleSelectionModel<Tab> selection = contentPane.getSelectionModel();
        Tab oldTab = selection.getSelectedItem();
        if (oldTab == newsTab) {
            newsLabel.getStyleClass().remove("selectedItem");
        } else if (oldTab == skinsTab) {
            skinsLabel.getStyleClass().remove("selectedItem");
        } else if (oldTab == settingsTab) {
            settingsLabel.getStyleClass().remove("selectedItem");
        } else if (oldTab == launchOptionsTab && source != profileEditorTab) {
            launchOptionsLabel.getStyleClass().remove("selectedItem");
        } else if (oldTab == profileEditorTab) {
            //Show play button
            if (!kernel.getDownloader().isDownloading()) {
                playPane.setVisible(true);
            }
            launchOptionsLabel.getStyleClass().remove("selectedItem");
        } else if (oldTab == loginTab) {
            newsLabel.getStyleClass().remove("selectedItem");
            skinsLabel.getStyleClass().remove("selectedItem");
            settingsLabel.getStyleClass().remove("selectedItem");
            launchOptionsLabel.getStyleClass().remove("selectedItem");
        }
        if (source == newsLabel) {
            newsLabel.getStyleClass().add("selectedItem");
            selection.select(newsTab);
        } else if (source == skinsLabel) {
            skinsLabel.getStyleClass().add("selectedItem");
            selection.select(skinsTab);
            if (!texturesLoaded) {
                loadTextures();
            }
        } else if (source == settingsLabel) {
            settingsLabel.getStyleClass().add("selectedItem");
            selection.select(settingsTab);
        } else if (source == launchOptionsLabel) {
            launchOptionsLabel.getStyleClass().add("selectedItem");
            selection.select(launchOptionsTab);
            if (!profileListLoaded) {
                loadProfileList();
            }
            profileList.getSelectionModel().clearSelection();
        } else if (source == profileEditorTab) {
            //Hide play button
            playPane.setVisible(false);
            selection.select(profileEditorTab);
        }
    }

    /**
     * Hides any open popup that triggers this method
     * @param e The event trigger
     */
    @FXML public final void hidePopup(Event e) {
        Node ls = (Node)e.getSource();
        if (ls.isVisible()) {
            ls.setVisible(false);
        }
    }

    /**
     * Updates the selected language
     */
    @FXML public final void updateLanguage() {
        if (languagesList.getSelectionModel().getSelectedIndex() == -1) {
            //Nothing has been selected
            return;
        }
        Label selected = languagesList.getSelectionModel().getSelectedItem();
        languageButton.setText(selected.getText());
        settings.setLocale(selected.getId());
        languagesList.setVisible(false);
        SingleSelectionModel<Tab> selection = contentPane.getSelectionModel();
        Tab selectedTab = selection.getSelectedItem();
        if (selectedTab == launchOptionsTab) {
            loadProfileList();
        } else {
            profileListLoaded = false;
        }
        if (selectedTab == profileEditorTab) {
            loadVersionList();
        } else {
            versionListLoaded = false;
        }
        profileListPopupLoaded = false;
        localizeElements();
    }

    /**
     * Updates the selected icon
     */
    @FXML public final void updateIcon() {
        if (iconList.getSelectionModel().getSelectedIndex() == -1) {
            //Nothing has been selected
            return;
        }
        ImageView selected = iconList.getSelectionModel().getSelectedItem();
        profileIcon.setImage(selected.getImage());
        profileIcon.setId(selected.getId());
        iconList.setVisible(false);
    }

    /**
     * Prepares the editor with the selected profile or with a new one
     */
    @FXML public final void loadEditor() {
        if (profileList.getSelectionModel().getSelectedIndex() == -1) {
            //Nothing has been selected
            return;
        }
        if (!versionListLoaded) {
            loadVersionList();
        }
        if (profileList.getSelectionModel().getSelectedIndex() == 0) {
            profileName.setEditable(true);
            profileName.setText("");
            deleteButton.setVisible(false);
            versionBlock.setVisible(true);
            versionBlock.setManaged(true);
            iconBlock.setVisible(true);
            iconBlock.setManaged(true);
            versionList.getSelectionModel().select(0);
            profileIcon.setImage(kernel.getProfileIcon("Furnace"));
            profileIcon.setId("Furnace");
            if (settings.getEnableAdvanced()) {
                javaExecBlock.setVisible(true);
                javaExecBlock.setManaged(true);
                javaArgsBlock.setVisible(true);
                javaArgsBlock.setManaged(true);
                toggleEditorOption(javaExecLabel, false);
                javaExec.setText(Utils.getJavaDir());
                toggleEditorOption(javaArgsLabel, false);
                StringBuilder jA = new StringBuilder(15);
                if (Utils.getOSArch() == OSArch.OLD) {
                    jA.append("-Xmx1G");
                    jA.append("-Xss1M");
                } else {
                    jA.append("-Xmx2G");
                }
                jA.append(" -Xmn128M");
                javaArgs.setText(jA.toString());
            } else {
                javaExecBlock.setVisible(false);
                javaExecBlock.setManaged(false);
                javaArgsBlock.setVisible(false);
                javaArgsBlock.setManaged(false);
            }
            toggleEditorOption(resolutionLabel, false);
            resW.setText(String.valueOf(854));
            resH.setText(String.valueOf(480));
            toggleEditorOption(gameDirLabel, false);
            gameDir.setText(Utils.getWorkingDirectory().getAbsolutePath());
        } else {
            Label selectedElement = profileList.getSelectionModel().getSelectedItem();
            if (selectedElement != null) {
                Profile p = kernel.getProfiles().getProfile(selectedElement.getId());
                if (p.getType() != ProfileType.CUSTOM) {
                    profileName.setEditable(false);
                    deleteButton.setVisible(false);
                    if (p.getType() == ProfileType.RELEASE) {
                        profileName.setText(Language.get(59));
                        profileIcon.setImage(kernel.getProfileIcon("Grass"));
                    } else {
                        profileName.setText(Language.get(60));
                        profileIcon.setImage(kernel.getProfileIcon("Crafting_Table"));
                    }
                    versionBlock.setVisible(false);
                    versionBlock.setManaged(false);
                    iconBlock.setVisible(false);
                    iconBlock.setManaged(false);
                } else {
                    if (p.hasIcon()) {
                        profileIcon.setImage(kernel.getProfileIcon(p.getIcon()));
                        profileIcon.setId(p.getIcon());
                    } else {
                        profileIcon.setImage(kernel.getProfileIcon("Furnace"));
                    }
                    profileName.setEditable(true);
                    deleteButton.setVisible(true);
                    if (p.hasName()){
                        profileName.setText(p.getName());
                    } else {
                        profileName.setText("");
                    }
                    versionBlock.setVisible(true);
                    versionBlock.setManaged(true);
                    iconBlock.setVisible(true);
                    iconBlock.setManaged(true);
                    if (p.hasVersion()) {
                        if (p.isLatestRelease()) {
                            versionList.getSelectionModel().select(0);
                        } else if (p.isLatestSnapshot() && settings.getEnableSnapshots()) {
                            versionList.getSelectionModel().select(1);
                        } else if (versionList.getItems().contains(p.getVersionID())) {
                            versionList.getSelectionModel().select(p.getVersionID());
                        } else {
                            versionList.getSelectionModel().select(0);
                        }
                    } else {
                        versionList.getSelectionModel().select(0);
                    }
                }

                if (p.hasResolution()) {
                    toggleEditorOption(resolutionLabel, true);
                    resH.setText(String.valueOf(p.getResolutionHeight()));
                    resW.setText(String.valueOf(p.getResolutionWidth()));
                } else {
                    toggleEditorOption(resolutionLabel, false);
                    resW.setText(String.valueOf(854));
                    resH.setText(String.valueOf(480));
                }
                if (p.hasGameDir()) {
                    toggleEditorOption(gameDirLabel, true);
                    gameDir.setText(p.getGameDir().getAbsolutePath());
                } else {
                    toggleEditorOption(gameDirLabel, false);
                    gameDir.setText(Utils.getWorkingDirectory().getAbsolutePath());
                }
                if (settings.getEnableAdvanced()) {
                    javaExecBlock.setVisible(true);
                    javaExecBlock.setManaged(true);
                    javaArgsBlock.setVisible(true);
                    javaArgsBlock.setManaged(true);
                    if (p.hasJavaDir()){
                        toggleEditorOption(javaExecLabel, true);
                        javaExec.setText(p.getJavaDir().getAbsolutePath());
                    } else {
                        toggleEditorOption(javaExecLabel, false);
                        javaExec.setText(Utils.getJavaDir());
                    }
                    if (p.hasJavaArgs()) {
                        toggleEditorOption(javaArgsLabel, true);
                        javaArgs.setText(p.getJavaArgs());
                    } else {
                        toggleEditorOption(javaArgsLabel, false);
                        StringBuilder jA = new StringBuilder(15);
                        if (Utils.getOSArch() == OSArch.OLD) {
                            jA.append("-Xmx1G");
                        } else {
                            jA.append("-Xmx2G");
                        }
                        jA.append(" -Xmn128M");
                        javaArgs.setText(jA.toString());
                    }
                } else {
                    javaExecBlock.setVisible(false);
                    javaExecBlock.setManaged(false);
                    javaArgsBlock.setVisible(false);
                    javaArgsBlock.setManaged(false);
                }
            }
        }
        switchTab(profileEditorTab);
    }

    /**
     * Loads the list of version for the profile editor
     */
    private void loadVersionList() {
        console.print("Loading version list...");
        ObservableList<VersionMeta> vers = FXCollections.observableArrayList();
        VersionMeta latestVersion = new VersionMeta(Language.get(59), null, null);
        vers.add(latestVersion);
        if (settings.getEnableSnapshots()) {
            VersionMeta latestSnapshot = new VersionMeta(Language.get(60), null, null);
            vers.add(latestSnapshot);
        }
        for (VersionMeta v : kernel.getVersions().getVersions()) {
            if (v.getType() == VersionType.RELEASE) {
                vers.add(v);
            } else if (v.getType() == VersionType.SNAPSHOT && settings.getEnableSnapshots()) {
                vers.add(v);
            } else if ((v.getType() == VersionType.OLD_BETA || v.getType() == VersionType.OLD_ALPHA) && settings.getEnableHistorical()) {
                vers.add(v);
            }
        }

        versionList.setItems(vers);
        if (!versionListLoaded) {
            versionList.getSelectionModel().select(0);
            versionListLoaded = true;
        }
        console.print("Version list loaded.");
    }

    /**
     * Saves the profile data from the profile editor
     */
    @FXML public final void saveProfile() {
        Profile target;
        if (profileList.getSelectionModel().getSelectedIndex() == 0) {
            target = new Profile(ProfileType.CUSTOM);
            kernel.getProfiles().addProfile(target);
        } else {
            Label selectedElement = profileList.getSelectionModel().getSelectedItem();
            target = kernel.getProfiles().getProfile(selectedElement.getId());
        }
        if (target.getType() == ProfileType.CUSTOM) {
            if (!profileName.getText().isEmpty()) {
                target.setName(profileName.getText());
            } else {
                target.setName(null);
            }
            if (versionList.getSelectionModel().getSelectedIndex() == 0) {
                target.setVersionID(kernel.getVersions().getLatestRelease());
                target.setLatestRelease(true);
                target.setLatestSnapshot(false);
            } else if (versionList.getSelectionModel().getSelectedIndex() == 1 && settings.getEnableSnapshots()) {
                target.setVersionID(kernel.getVersions().getLatestSnapshot());
                target.setLatestRelease(false);
                target.setLatestSnapshot(true);
            } else {
                target.setVersionID(versionList.getSelectionModel().getSelectedItem());
                target.setLatestRelease(false);
                target.setLatestSnapshot(false);
            }
            try {
                target.setIcon(profileIcon.getId());
            } catch (IllegalArgumentException ex) {
                target.setIcon(null);
            }
        }
        if (!resW.isDisabled()) {
            try {
                int h = Integer.parseInt(resH.getText());
                int w = Integer.parseInt(resW.getText());
                target.setResolution(w, h);
            } catch (NumberFormatException ex) {
                console.print("Invalid resolution given.");
            }
        } else {
            target.setResolution(-1, -1);
        }
        if (!gameDir.isDisabled() && !gameDir.getText().isEmpty()) {
            target.setGameDir(new File(gameDir.getText()));
        } else {
            target.setGameDir(null);
        }
        if (settings.getEnableAdvanced()) {
            if (!javaExec.isDisabled() && !javaExec.getText().isEmpty()) {
                target.setJavaDir(new File(javaExec.getText()));
            } else {
                target.setJavaDir(null);
            }
            if (!javaArgs.isDisabled() && !javaArgs.getText().isEmpty()) {
                target.setJavaArgs(javaArgs.getText());
            } else {
                target.setJavaArgs(null);
            }
        }
        kernel.saveProfiles();
        if (kernel.getProfiles().getSelectedProfile() == target) {
            updateGameVersion();
        }
        kernel.showAlert(Alert.AlertType.INFORMATION, null, Language.get(57));
        profileListLoaded = false;
        profileListPopupLoaded = false;
        switchTab(launchOptionsLabel);
    }

    /**
     * Discards the changes of the profile editor
     */
    @FXML public final void cancelProfile() {
        int result = kernel.showAlert(Alert.AlertType.CONFIRMATION, null, Language.get(55));
        if (result == 1) {
            switchTab(launchOptionsLabel);
        }
    }

    /**
     * Deletes the profile loaded by the profile editor
     */
    @FXML public final void deleteProfile() {
        int result = kernel.showAlert(Alert.AlertType.CONFIRMATION, null, Language.get(61));
        if (result == 1) {
            Label selectedElement = profileList.getSelectionModel().getSelectedItem();
            Profile p = kernel.getProfiles().getProfile(selectedElement.getId());
            if (kernel.getProfiles().deleteProfile(p)) {
                kernel.saveProfiles();
                updateGameVersion();
                kernel.showAlert(Alert.AlertType.INFORMATION, null, Language.get(56));
            } else {
                kernel.showAlert(Alert.AlertType.ERROR, null, Language.get(58));
            }
            loadProfileList();
            switchTab(launchOptionsLabel);
        }
    }

    /**
     * Toggles the editor options on and off
     * @param src The object that has been clicked
     * @param newState The new state
     */
    private void toggleEditorOption(Object src, boolean newState) {
        if (src instanceof Label) {
            Label l = (Label)src;
            toggleLabel(l, newState);
        }
        if (src == resolutionLabel) {
            resW.setDisable(!newState);
            resH.setDisable(!newState);
        } else if (src == gameDirLabel) {
            gameDir.setDisable(!newState);
        } else if (src == javaExecLabel) {
            javaExec.setDisable(!newState);
        } else if (src == javaArgsLabel) {
            javaArgs.setDisable(!newState);
        }
    }

    /**
     * Update editor when clicking labels. This method fetches the adjacent sibling to determine if is disabled
     * @param e The event trigger
     */
    @FXML public final void updateEditor(MouseEvent e) {
        Label l = (Label)e.getSource();
        toggleEditorOption(l, l.getParent().getChildrenUnmodifiable().get(1).isDisable());
    }

    /**
     * Updates the existing users list
     */
    private void updateExistingUsers() {
        Authentication a = kernel.getAuthentication();
        if (!a.getUsers().isEmpty() && a.getSelectedUser() == null) {
            existingPanel.setVisible(true);
            existingPanel.setManaged(true);
            ObservableList<User> users = FXCollections.observableArrayList();
            Set<User> us = a.getUsers();
            users.addAll(us);
            existingUsers.setItems(users);
            existingUsers.getSelectionModel().select(0);
        } else {
            existingPanel.setVisible(false);
            existingPanel.setManaged(false);
        }
    }

    /**
     * Shows or hides the login prompt
     * @param showLoginPrompt The new state
     */
    private void showLoginPrompt(boolean showLoginPrompt) {
        if (showLoginPrompt) {
            contentPane.getSelectionModel().select(loginTab);
            tabMenu.setVisible(false);
            tabMenu.setManaged(false);
            accountButton.setVisible(false);
            playPane.setVisible(false);
            updateExistingUsers();
        } else {
            switchTab(newsLabel);
            tabMenu.setVisible(true);
            tabMenu.setManaged(true);
            accountButton.setVisible(true);
            //Show play button
            if (!kernel.getDownloader().isDownloading()) {
                playPane.setVisible(true);
            }
            //Set account name for current user
            accountButton.setText(kernel.getAuthentication().getSelectedUser().getDisplayName());
        }
    }

    /**
     * Performs an authenticate with the data typed in the login form
     */
    public final void authenticate() {
        if (username.getText().isEmpty()) {
            kernel.showAlert(Alert.AlertType.WARNING, null, Language.get(17));
        } else if (password.getText().isEmpty()) {
            kernel.showAlert(Alert.AlertType.WARNING, null, Language.get(23));
        } else {
            try {
                Authentication auth = kernel.getAuthentication();
                String user;
                if (authKrothium.isSelected()) {
                    user = "krothium://" + username.getText();
                } else {
                    user = username.getText();
                }
                auth.authenticate(user, password.getText());
                kernel.saveProfiles();
                username.setText("");
                password.setText("");
                showLoginPrompt(false);
                fetchAds();
                texturesLoaded = false;
            } catch (AuthenticationException ex) {
                kernel.showAlert(Alert.AlertType.ERROR, Language.get(22), ex.getMessage());
                password.setText("");
            }
        }
    }

    /**
     * Refreshes latest session
     */
    private void refreshSession() {
        console.print("Refreshing session...");
        Authentication a = kernel.getAuthentication();
        User u = a.getSelectedUser();
        try {
            if (u != null) {
                a.refresh();
                texturesLoaded = false;
                kernel.saveProfiles();
                console.print("Session refreshed.");
            } else {
                console.print("No user is selected.");
            }
        } catch (AuthenticationException ex) {
            if (u.getType() == UserType.KROTHIUM) {
                authKrothium.setSelected(true);
                username.setText(u.getUsername().replace("krothium://", ""));
            } else {
                authMojang.setSelected(true);
                username.setText(u.getUsername());
            }
            console.print("Couldn't refresh your session.");
        } finally {
            if (a.isAuthenticated()) {
                showLoginPrompt(false);
                fetchAds();
            } else {
                showLoginPrompt(true);
            }
        }
    }

    /**
     * Refreshes user selected from the existing user list
     */
    public final void refresh() {
        User selected = existingUsers.getSelectionModel().getSelectedItem();
        Authentication auth = kernel.getAuthentication();
        try {
            auth.setSelectedUser(selected);
            auth.refresh();
            kernel.saveProfiles();
            texturesLoaded = false;
            showLoginPrompt(false);
            fetchAds();
        } catch (AuthenticationException ex) {
            kernel.showAlert(Alert.AlertType.ERROR, Language.get(62), ex.getMessage());
            updateExistingUsers();
        }
    }

    /**
     * Logs out the selected user from the existing user list
     */
    public final void logout() {
        User selected = existingUsers.getSelectionModel().getSelectedItem();
        int result = kernel.showAlert(Alert.AlertType.CONFIRMATION, null, Language.get(8));
        if (result == 1) {
            Authentication auth = kernel.getAuthentication();
            auth.removeUser(selected);
            kernel.saveProfiles();
            updateExistingUsers();
        }
    }

    /**
     * Opens the register page
     */
    @FXML public final void register() {
        if (authKrothium.isSelected()) {
            kernel.getHostServices().showDocument("https://krothium.com/register");
        } else {
            kernel.getHostServices().showDocument("https://minecraft.net/");
        }
    }

    /**
     * Opens the help page
     */
    @FXML public final void openHelp() {
        kernel.getHostServices().showDocument(urlPrefix + "https://krothium.com/forum/12-soporte/");
    }

    /**
     * Opens the news page
     */
    @FXML public final void openNews() {
        kernel.getHostServices().showDocument(urlPrefix + "https://krothium.com/forum/3-noticias/");
    }

    /**
     * Performs an authenticate if the Enter key is pressed in the Username or Password field
     * @param e The trigger event
     */
    @FXML public final void triggerAuthenticate(KeyEvent e) {
        if (e.getCode() == KeyCode.ENTER) {
            authenticate();
        }
    }

    /**
     * Updates the settings according to the label clicked
     * @param e The trigger event
     */
    @FXML public final void updateSettings(MouseEvent e) {
        Label source = (Label)e.getSource();
        if (source == keepLauncherOpen) {
            settings.setKeepLauncherOpen(!settings.getKeepLauncherOpen());
            toggleLabel(source, settings.getKeepLauncherOpen());
        } else if (source == outputLog) {
            settings.setShowGameLog(!settings.getShowGameLog());
            toggleLabel(source, settings.getShowGameLog());
        } else if (source == enableSnapshots) {
            if (!settings.getEnableSnapshots()) {
                kernel.showAlert(Alert.AlertType.WARNING, null, Language.get(71) + System.lineSeparator() + Language.get(72));
            }
            settings.setEnableSnapshots(!settings.getEnableSnapshots());
            toggleLabel(source, settings.getEnableSnapshots());
            validateSelectedProfile();
            loadProfileList();
            profileListPopupLoaded = false;
            versionListLoaded = false;
        } else if (source == historicalVersions) {
            if (!settings.getEnableHistorical()) {
                kernel.showAlert(Alert.AlertType.WARNING, null, Language.get(73) + System.lineSeparator()
                        + Language.get(74) + System.lineSeparator()
                        + Language.get(75));

            }
            settings.setEnableHistorical(!settings.getEnableHistorical());
            toggleLabel(source, settings.getEnableHistorical());
            validateSelectedProfile();
            loadProfileList();
            profileListPopupLoaded = false;
            versionListLoaded = false;
        } else if (source == advancedSettings) {
            if (!settings.getEnableAdvanced()) {
                kernel.showAlert(Alert.AlertType.WARNING, null, Language.get(76) + System.lineSeparator() + Language.get(77));
            }
            settings.setEnableAdvanced(!settings.getEnableAdvanced());
            toggleLabel(source, settings.getEnableAdvanced());
        }
        kernel.saveProfiles();
    }

    /**
     * Changes any label icon
     * @param label The target label
     * @param state The new state
     */
    private void toggleLabel(Styleable label, boolean state) {
        Object[] classes = label.getStyleClass().toArray();
        for (Object ckl : classes) {
            if (ckl.toString().startsWith("toggle")) {
                label.getStyleClass().remove(ckl.toString());
            }
        }
        if (state) {
            label.getStyleClass().add("toggle-enabled");
        } else {
            label.getStyleClass().add("toggle-disabled");
        }
    }

    /**
     * Exports the logs to a ZIP file
     */
    @FXML private void exportLogs() {
        File selected = selectFile("ZIP", "*.zip", "save");
        if (selected != null) {
            try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(selected))) {
                File[] files = Kernel.APPLICATION_LOGS.listFiles();
                if (files != null) {
                    byte[] bytes;
                    for (File file : files) {
                        ZipEntry entry = new ZipEntry(file.getName());
                        out.putNextEntry(entry);
                        bytes = Files.readAllBytes(file.toPath());
                        out.write(bytes);
                        out.closeEntry();
                    }
                }
                kernel.showAlert(Alert.AlertType.INFORMATION, null, Language.get(35) + System.lineSeparator() + selected.getAbsolutePath());
            } catch (IOException ex) {
                kernel.showAlert(Alert.AlertType.ERROR, null, Language.get(35) + '\n' + selected.getAbsolutePath());
            }
        }
    }

    /**
     * Removes the launcher cache
     */
    @FXML private void deleteCache() {
        int result = kernel.showAlert(Alert.AlertType.CONFIRMATION, null, Language.get(10));
        if (result == 1) {
            File[] files = Kernel.APPLICATION_CACHE.listFiles();
            if (files != null) {
                for (File f : files) {
                    f.delete();
                }
            }
            kernel.showAlert(Alert.AlertType.INFORMATION, null, Language.get(11));
        }
    }

    /**
     * Opens the URL of the selected version server in the default user web browser
     */
    @FXML private void downloadServer() {
        VersionMeta selectedItem = versionList.getSelectionModel().getSelectedItem();
        kernel.getHostServices().showDocument(urlPrefix + "https://s3.amazonaws.com/Minecraft.Download/versions/" + selectedItem.getID() + "/minecraft_server." + selectedItem.getID() + ".jar");
    }

    /**
     * Selects a game directory for the profile editor
     */
    @FXML private void selectGameDirectory() {
        DirectoryChooser chooser = new DirectoryChooser();
        if (gameDir.getText().isEmpty()) {
            chooser.setInitialDirectory(Kernel.APPLICATION_WORKING_DIR);
        } else {
            File gd = new File(gameDir.getText());
            if (gd.isDirectory()) {
                chooser.setInitialDirectory(gd);
            } else {
                chooser.setInitialDirectory(Kernel.APPLICATION_WORKING_DIR);
            }
        }
        File selectedFolder = chooser.showDialog(null);
        if (selectedFolder != null) {
            gameDir.setText(selectedFolder.getAbsolutePath());
        }
    }

    /**
     * Selects the java executable for the profile editor
     */
    @FXML private void selectJavaExecutable() {
        File selected = selectFile(null, null, "open");
        if (selected != null && selected.isFile()) {
            javaExec.setText(selected.getAbsolutePath());
        }
    }

    /**
     * Update auth server label on existing users
     */
    @FXML public void updateAuthServer() {
        User user = existingUsers.getValue();
        if (user != null) {
            if (user.getType() == UserType.KROTHIUM) {
                authServer.setText("(Krothium)");
            } else {
                authServer.setText("(Mojang)");
            }
        }
    }

    /**
     * Selects a file
     * @param extensionName The extension name
     * @param extension The extension
     * @param method Method to select the file
     * @return The selected file
     */
    private File selectFile(String extensionName, String extension, String method) {
        FileChooser chooser = new FileChooser();
        if (extension != null) {
            ExtensionFilter filter = new ExtensionFilter(extensionName, extension);
            chooser.getExtensionFilters().add(filter);
        }
        if (method.equalsIgnoreCase("open")) {
            chooser.setTitle(Language.get(95));
            return chooser.showOpenDialog(stage);
        } else if (method.equalsIgnoreCase("save")) {
            chooser.setTitle(Language.get(96));
            return chooser.showSaveDialog(stage);
        }
        return null;
    }

    /**
     * Opens the password recovery webpage
     */
    @FXML private void forgotPassword() {
        if (authKrothium.isSelected()) {
            kernel.getHostServices().showDocument("https://krothium.com/lostpassword");
        } else {
            kernel.getHostServices().showDocument("https://account.mojang.com/password");
        }
    }
} public class Language {
    private static final ArrayList<String> langData =  new ArrayList<>();

    /**
     * Loads a language file
     * @param lang The language to be loaded
     * @throws IOException When data read fails
     */
    public static void loadLang(String lang) throws IOException {
        langData.clear();
        URL resource = Language.class.getResource("/kml/gui/lang/" + lang + ".txt");
        if (resource == null) {
            resource = Language.class.getResource("/kml/gui/lang/en-us.txt");
        }
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.openStream(), Charset.forName("UTF-8")))) {
            String line;
            while ((line = reader.readLine()) != null) {
                langData.add(line);
            }
        }
    }

    /**
     * Gets a specific localized line
     * @param line The target line
     * @return The requested localized line
     */
    public static String get(int line) {
        if (line <= langData.size()) {
            return langData.get(line - 1);
        }
        return "";
    }
} public final class Utils {
    /**
     * Gets the current operating system
     * @return An OS enum with the detected OS
     */
    public static OS getPlatform() {
        String osName = System.getProperty("os.name").toLowerCase(Locale.ENGLISH);
        if (osName.contains("win")) {
            return OS.WINDOWS;
        }
        if (osName.contains("mac")) {
            return OS.OSX;
        }
        if (osName.contains("linux") || osName.contains("unix")) {
            return OS.LINUX;
        }
        return OS.UNKNOWN;
    }

    /**
     * Gets the default working directory for the launcher depending of the OS
     * @return The working directory
     */
    public static File getWorkingDirectory() {
        String userHome = System.getProperty("user.home", ".");
        File workingDirectory;
        switch (getPlatform()) {
            case LINUX:
                workingDirectory = new File(userHome, ".minecraft/");
                break;
            case WINDOWS:
                String applicationData = System.getenv("APPDATA");
                String folder = applicationData != null ? applicationData : userHome;
                workingDirectory = new File(folder, ".minecraft/");
                break;
            case OSX:
                workingDirectory = new File(userHome, "Library/Application Support/minecraft");
                break;
            default:
                workingDirectory = new File(userHome, "minecraft/");
        }
        return workingDirectory;
    }

    /**
     * Deletes a directory recursively
     * @param directory The target directory
     */
    public static void deleteDirectory(File directory) {
        if (directory.isDirectory()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File f : files) {
                    if (f.isDirectory()) {
                        deleteDirectory(f);
                    } else {
                        f.delete();
                    }
                }
            }
        }
        directory.delete();
    }

    /**
     * Downloads a file and even caches it if server ETAG is existent
     * @param url The source URL
     * @throws IOException When data read fails
     * @param output The output file
     */
    public static void downloadFile(String url, File output) throws IOException {
        if (url.startsWith("file")) {
            return;
        }
        URLConnection con = new URL(url).openConnection();
        String ETag = con.getHeaderField("ETag");
        //Match ETAG with existing file
        if (ETag != null) {
            if (output.isFile() && verifyChecksum(output, ETag.replace("\"", ""), "MD5")) {
                return;
            }
        }
        File parent = output.getParentFile();
        if (parent != null && !parent.exists()) {
            parent.mkdirs();
        }
        pipeStreams(con.getInputStream(), new FileOutputStream(output));
    }

    private static String readText(InputStream is) {
        if (is == null) {
            return "";
        }
        StringBuilder content = new StringBuilder();
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")))) {
            String line;
            boolean first = true;
            while ((line = bufferedReader.readLine()) != null) {
                if (!first) {
                    content.append(System.lineSeparator());
                } else {
                    first = false;
                }
                content.append(line);
            }
            return content.toString();
        } catch (IOException ex) {
            return "";
        }
    }

    private static void pipeStreams(InputStream in, OutputStream out) {
        if (in == null || out == null) {
            return;
        }
        try {
            byte[] buffer = new byte[8192];
            int read;
            while ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }
        } catch (IOException ignored) {
            //No problem
        } finally {
            try {
                in.close();
            } catch (IOException ignored) {
                //Nothing we can do
            }
            try {
                out.close();
            } catch (IOException ignored) {
                //Nothing we can do
            }
        }
    }

    public static InputStream readCachedStream(String url) {
        try {
            URLConnection con = new URL(url).openConnection();
            String ETag = con.getHeaderField("ETag");
            if (ETag != null) {
                ETag = ETag.replace("\"", "");
                File cachedFile = new File(Kernel.APPLICATION_CACHE, ETag);
                if (!cachedFile.isFile() || cachedFile.length() != con.getContentLength()) {
                    return new CachedInputStream(con.getInputStream(), cachedFile);
                }
                return new FileInputStream(cachedFile);
            }
            return con.getInputStream();
        } catch (IOException ex) {
            return null;
        }
    }

    /**
     * Reads a String from the source URL
     * @param url The source URL
     * @return The read String or null if an error occurred
     */
    public static String readURL(String url) {
        InputStream in = readCachedStream(url);
        if (in != null) {
            return readText(in);
        }
        return "";
    }

    /**
     * Verifies a checksum from a file
     * @param file The file to be checked
     * @param hash The hash or checksum to check
     * @param method The hash format (md5, sha1...)
     * @return A boolean that indicated if the hash matches
     */
    public static boolean verifyChecksum(File file, String hash, String method) {
        if (hash == null || method == null || !file.isFile()) {
            return false;
        }
        String fileHash = calculateChecksum(file, method);
        return hash.equals(fileHash);
    }

    /**
     * Calculates a checksum from a File
     * @param file The input File
     * @param algorithm The hash method (md5, sha1...)
     * @return The calculated hash
     */
    private static String calculateChecksum(File file, String algorithm) {
        try (FileInputStream fis = new FileInputStream(file)){
            MessageDigest sha1 = MessageDigest.getInstance(algorithm);
            byte[] data = new byte[8192];
            int read;
            while ((read = fis.read(data)) != -1) {
                sha1.update(data, 0, read);
            }
            byte[] hashBytes = sha1.digest();
            StringBuilder sb = new StringBuilder();
            for (byte hashByte : hashBytes) {
                sb.append(Integer.toString((hashByte & 0xff) + 0x100, 16).substring(1));
            }
            return sb.toString();
        } catch (IOException | NoSuchAlgorithmException ex) {
            return null;
        }
    }

    /**
     * Writes a String to a File
     * @param o The String to be written
     * @param f The output File
     * @return A boolean that indicated if the text has been written
     */
    public static boolean writeToFile(String o, File f) {
        try (FileOutputStream out = new FileOutputStream(f)) {
            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }
            out.write(o.getBytes(StandardCharsets.UTF_8));
            return true;
        } catch (IOException ex) {
            return false;
        }
    }

    /**
     * Checks whether the current OS arch is 32 or 64 bits
     * @return An OSArch enum with the detected architecture
     */
    public static OSArch getOSArch() {
        String arch = System.getProperty("os.arch");
        String realArch = arch.endsWith("64") ? "64" : "32";
        return "32".equals(realArch) ? OSArch.OLD : OSArch.NEW;
    }

    /**
     * Gets a real path from an artifact path
     * @param artifact The artifact path
     * @param ext The extension
     * @return The real path
     */
    public static String getArtifactPath(String artifact, String ext) {
        String[] parts = artifact.split(":", 3);
        return String.format("%s/%s/%s/%s." + ext, parts[0].replaceAll("\\.", "/"), parts[1], parts[2], parts[1] + '-' + parts[2]);
    }

    /**
     * Sends a post to the desired target
     * @param url The POST URL
     * @param data The data to be sent
     * @param params The headers to be sent
     * @return The response of the server
     * @throws IOException If connection failed
     */
    public static String sendPost(String url, byte[] data, Map<String, String> params) throws IOException {
        HttpURLConnection con = (HttpURLConnection)new URL(url).openConnection();
        con.setDoOutput(true);
        con.setRequestMethod("POST");
        if (!params.isEmpty()) {
            Set keys = params.keySet();
            for (Object key : keys) {
                String param = key.toString();
                con.setRequestProperty(param, params.get(param));
            }
        }
        if (data != null) {
            try (OutputStream out = con.getOutputStream()) {
                out.write(data);
            }
        }
        if (con.getResponseCode() == 200) {
            return readText(con.getInputStream());
        } else {
            return readText(con.getErrorStream());
        }
    }

    /**
     * Gets the java executable path
     * @return The java executable path
     */
    public static String getJavaDir() {
        String separator = System.getProperty("file.separator");
        String path = System.getProperty("java.home") + separator + "bin" + separator;
        if (getPlatform() == OS.WINDOWS && new File(path + "javaw.exe").isFile()) {
            return path + "javaw.exe";
        }
        return path + "java";
    }

    /**
     * Converts a Base64 String to text
     * @param st The Base64 String
     * @return The decoded text
     */
    public static String fromBase64(String st) {
        if (st == null || st.isEmpty()) {
            return null;
        }
        String conversion;
        try {
            conversion = new String(DatatypeConverter.parseBase64Binary(st), StandardCharsets.UTF_8);
        } catch (IllegalArgumentException ex) {
            conversion = "";
        }
        return conversion;
    }


    /**
     * Decompresses a ZIP file
     * @param input The ZIP file
     * @param output The output directory
     * @param exclusions Any extraction exclusions
     * @throws IOException If the process failed
     */
    public static void decompressZIP(InputStream input, File output, Iterable<String> exclusions) throws IOException {
        if(!output.isDirectory()){
            output.mkdirs();
        }
        try (ZipInputStream zis = new ZipInputStream(input)){
            ZipEntry ze = zis.getNextEntry();
            while(ze != null){
                String fileName = ze.getName();
                File newFile = new File(output + File.separator + fileName);
                if (ze.isDirectory()) {
                    newFile.mkdir();
                } else {
                    boolean excluded = false;
                    if (exclusions != null) {
                        for (String e : exclusions) {
                            if (fileName.startsWith(e)) {
                                excluded = true;
                            }
                        }
                    }
                    if (excluded) {
                        zis.closeEntry();
                        ze = zis.getNextEntry();
                        continue;
                    }
                    byte[] buffer = new byte[16384];
                    new File(newFile.getParent()).mkdirs();
                    try (FileOutputStream fos = new FileOutputStream(newFile)) {
                        int len;
                        while ((len = zis.read(buffer)) > 0) {
                            fos.write(buffer, 0, len);
                        }
                    }
                }
                zis.closeEntry();
                ze = zis.getNextEntry();
            }
            new File(output, "OK").createNewFile();
        }
    }
} public class JSONObject {
    /**
     * JSONObject.NULL is equivalent to the value that JavaScript calls null,
     * whilst Java's null is equivalent to the value that JavaScript calls
     * undefined.
     */
    private static final class Null {

        /**
         * There is only intended to be a single instance of the NULL object,
         * so the clone method returns itself.
         *
         * @return NULL.
         */
        @Override
        protected final Object clone() {
            return this;
        }

        /**
         * A Null object is equal to the null value and to itself.
         *
         * @param object
         *            An object to test for nullness.
         * @return true if the object parameter is the JSONObject.NULL object or
         *         null.
         */
        @Override
        public boolean equals(Object object) {
            return object == null || object == this;
        }
        /**
         * A Null object is equal to the null value and to itself.
         *
         * @return always returns 0.
         */
        @Override
        public int hashCode() {
            return 0;
        }

        /**
         * Get the "null" string value.
         *
         * @return The string "null".
         */
        @Override
        public String toString() {
            return "null";
        }
    }

    /**
     * The map where the JSONObject's properties are kept.
     */
    private final Map<String, Object> map;

    /**
     * It is sometimes more convenient and less ambiguous to have a
     * <code>NULL</code> object than to use Java's <code>null</code> value.
     * <code>JSONObject.NULL.equals(null)</code> returns <code>true</code>.
     * <code>JSONObject.NULL.toString()</code> returns <code>"null"</code>.
     */
    public static final Object NULL = new Null();

    /**
     * Construct an empty JSONObject.
     */
    public JSONObject() {
        // HashMap is used on purpose to ensure that elements are unordered by 
        // the specification.
        // JSON tends to be a portable transfer format to allows the container 
        // implementations to rearrange their items for a faster element 
        // retrieval based on associative access.
        // Therefore, an implementation mustn't rely on the order of the item.
        this.map = new HashMap<String, Object>();
    }

    /**
     * Construct a JSONObject from a subset of another JSONObject. An array of
     * strings is used to identify the keys that should be copied. Missing keys
     * are ignored.
     *
     * @param jo
     *            A JSONObject.
     * @param names
     *            An array of strings.
     */
    public JSONObject(JSONObject jo, String[] names) {
        this(names.length);
        for (int i = 0; i < names.length; i += 1) {
            try {
                this.putOnce(names[i], jo.opt(names[i]));
            } catch (Exception ignore) {
            }
        }
    }

    /**
     * Construct a JSONObject from a JSONTokener.
     *
     * @param x
     *            A JSONTokener object containing the source string.
     * @throws JSONException
     *             If there is a syntax error in the source string or a
     *             duplicated key.
     */
    public JSONObject(JSONTokener x) throws JSONException {
        this();
        char c;
        String key;

        if (x.nextClean() != '{') {
            throw x.syntaxError("A JSONObject text must begin with '{'");
        }
        for (;;) {
            c = x.nextClean();
            switch (c) {
            case 0:
                throw x.syntaxError("A JSONObject text must end with '}'");
            case '}':
                return;
            default:
                x.back();
                key = x.nextValue().toString();
            }

            // The key is followed by ':'.

            c = x.nextClean();
            if (c != ':') {
                throw x.syntaxError("Expected a ':' after a key");
            }
            
            // Use syntaxError(..) to include error location
            
            if (key != null) {
                // Check if key exists
                if (this.opt(key) != null) {
                    // key already exists
                    throw x.syntaxError("Duplicate key \"" + key + "\"");
                }
                // Only add value if non-null
                Object value = x.nextValue();
                if (value!=null) {
                    this.put(key, value);
                }
            }

            // Pairs are separated by ','.

            switch (x.nextClean()) {
            case ';':
            case ',':
                if (x.nextClean() == '}') {
                    return;
                }
                x.back();
                break;
            case '}':
                return;
            default:
                throw x.syntaxError("Expected a ',' or '}'");
            }
        }
    }

    /**
     * Construct a JSONObject from a Map.
     *
     * @param m
     *            A map object that can be used to initialize the contents of
     *            the JSONObject.
     * @throws JSONException
     *            If a value in the map is non-finite number.
     * @throws NullPointerException
     *            If a key in the map is <code>null</code>
     */
    public JSONObject(Map<?, ?> m) {
        if (m == null) {
            this.map = new HashMap<String, Object>();
        } else {
            this.map = new HashMap<String, Object>(m.size());
        	for (final Entry<?, ?> e : m.entrySet()) {
        	    if(e.getKey() == null) {
        	        throw new NullPointerException("Null key.");
        	    }
                final Object value = e.getValue();
                if (value != null) {
                    this.map.put(String.valueOf(e.getKey()), wrap(value));
                }
            }
        }
    }

    /**
     * Construct a JSONObject from an Object using bean getters. It reflects on
     * all of the public methods of the object. For each of the methods with no
     * parameters and a name starting with <code>"get"</code> or
     * <code>"is"</code> followed by an uppercase letter, the method is invoked,
     * and a key and the value returned from the getter method are put into the
     * new JSONObject.
     * <p>
     * The key is formed by removing the <code>"get"</code> or <code>"is"</code>
     * prefix. If the second remaining character is not upper case, then the
     * first character is converted to lower case.
     * <p>
     * Methods that are <code>static</code>, return <code>void</code>,
     * have parameters, or are "bridge" methods, are ignored.
     * <p>
     * For example, if an object has a method named <code>"getName"</code>, and
     * if the result of calling <code>object.getName()</code> is
     * <code>"Larry Fine"</code>, then the JSONObject will contain
     * <code>"name": "Larry Fine"</code>.
     * <p>
     * The {@link JSONPropertyName} annotation can be used on a bean getter to
     * override key name used in the JSONObject. For example, using the object
     * above with the <code>getName</code> method, if we annotated it with:
     * <pre>
     * &#64;JSONPropertyName("FullName")
     * public String getName() { return this.name; }
     * </pre>
     * The resulting JSON object would contain <code>"FullName": "Larry Fine"</code>
     * <p>
     * Similarly, the {@link JSONPropertyName} annotation can be used on non-
     * <code>get</code> and <code>is</code> methods. We can also override key
     * name used in the JSONObject as seen below even though the field would normally
     * be ignored:
     * <pre>
     * &#64;JSONPropertyName("FullName")
     * public String fullName() { return this.name; }
     * </pre>
     * The resulting JSON object would contain <code>"FullName": "Larry Fine"</code>
     * <p>
     * The {@link JSONPropertyIgnore} annotation can be used to force the bean property
     * to not be serialized into JSON. If both {@link JSONPropertyIgnore} and
     * {@link JSONPropertyName} are defined on the same method, a depth comparison is
     * performed and the one closest to the concrete class being serialized is used.
     * If both annotations are at the same level, then the {@link JSONPropertyIgnore}
     * annotation takes precedent and the field is not serialized.
     * For example, the following declaration would prevent the <code>getName</code>
     * method from being serialized:
     * <pre>
     * &#64;JSONPropertyName("FullName")
     * &#64;JSONPropertyIgnore 
     * public String getName() { return this.name; }
     * </pre>
     * <p>
     * 
     * @param bean
     *            An object that has getter methods that should be used to make
     *            a JSONObject.
     */
    public JSONObject(Object bean) {
        this();
        this.populateMap(bean);
    }

    /**
     * Construct a JSONObject from an Object, using reflection to find the
     * public members. The resulting JSONObject's keys will be the strings from
     * the names array, and the values will be the field values associated with
     * those keys in the object. If a key is not found or not visible, then it
     * will not be copied into the new JSONObject.
     *
     * @param object
     *            An object that has fields that should be used to make a
     *            JSONObject.
     * @param names
     *            An array of strings, the names of the fields to be obtained
     *            from the object.
     */
    public JSONObject(Object object, String names[]) {
        this(names.length);
        Class<?> c = object.getClass();
        for (int i = 0; i < names.length; i += 1) {
            String name = names[i];
            try {
                this.putOpt(name, c.getField(name).get(object));
            } catch (Exception ignore) {
            }
        }
    }

    /**
     * Construct a JSONObject from a source JSON text string. This is the most
     * commonly used JSONObject constructor.
     *
     * @param source
     *            A string beginning with <code>{</code>&nbsp;<small>(left
     *            brace)</small> and ending with <code>}</code>
     *            &nbsp;<small>(right brace)</small>.
     * @exception JSONException
     *                If there is a syntax error in the source string or a
     *                duplicated key.
     */
    public JSONObject(String source) throws JSONException {
        this(new JSONTokener(source));
    }

    /**
     * Construct a JSONObject from a ResourceBundle.
     *
     * @param baseName
     *            The ResourceBundle base name.
     * @param locale
     *            The Locale to load the ResourceBundle for.
     * @throws JSONException
     *             If any JSONExceptions are detected.
     */
    public JSONObject(String baseName, Locale locale) throws JSONException {
        this();
        ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale,
                Thread.currentThread().getContextClassLoader());

// Iterate through the keys in the bundle.

        Enumeration<String> keys = bundle.getKeys();
        while (keys.hasMoreElements()) {
            Object key = keys.nextElement();
            if (key != null) {

// Go through the path, ensuring that there is a nested JSONObject for each
// segment except the last. Add the value using the last segment's name into
// the deepest nested JSONObject.

                String[] path = ((String) key).split("\\.");
                int last = path.length - 1;
                JSONObject target = this;
                for (int i = 0; i < last; i += 1) {
                    String segment = path[i];
                    JSONObject nextTarget = target.optJSONObject(segment);
                    if (nextTarget == null) {
                        nextTarget = new JSONObject();
                        target.put(segment, nextTarget);
                    }
                    target = nextTarget;
                }
                target.put(path[last], bundle.getString((String) key));
            }
        }
    }
    
    /**
     * Constructor to specify an initial capacity of the internal map. Useful for library 
     * internal calls where we know, or at least can best guess, how big this JSONObject
     * will be.
     * 
     * @param initialCapacity initial capacity of the internal map.
     */
    protected JSONObject(int initialCapacity){
        this.map = new HashMap<String, Object>(initialCapacity);
    }

    /**
     * Accumulate values under a key. It is similar to the put method except
     * that if there is already an object stored under the key then a JSONArray
     * is stored under the key to hold all of the accumulated values. If there
     * is already a JSONArray, then the new value is appended to it. In
     * contrast, the put method replaces the previous value.
     *
     * If only one value is accumulated that is not a JSONArray, then the result
     * will be the same as using put. But if multiple values are accumulated,
     * then the result will be like append.
     *
     * @param key
     *            A key string.
     * @param value
     *            An object to be accumulated under the key.
     * @return this.
     * @throws JSONException
     *            If the value is non-finite number.
     * @throws NullPointerException
     *            If the key is <code>null</code>.
     */
    public JSONObject accumulate(String key, Object value) throws JSONException {
        testValidity(value);
        Object object = this.opt(key);
        if (object == null) {
            this.put(key,
                    value instanceof JSONArray ? new JSONArray().put(value)
                            : value);
        } else if (object instanceof JSONArray) {
            ((JSONArray) object).put(value);
        } else {
            this.put(key, new JSONArray().put(object).put(value));
        }
        return this;
    }

    /**
     * Append values to the array under a key. If the key does not exist in the
     * JSONObject, then the key is put in the JSONObject with its value being a
     * JSONArray containing the value parameter. If the key was already
     * associated with a JSONArray, then the value parameter is appended to it.
     *
     * @param key
     *            A key string.
     * @param value
     *            An object to be accumulated under the key.
     * @return this.
     * @throws JSONException
     *            If the value is non-finite number or if the current value associated with
     *             the key is not a JSONArray.
     * @throws NullPointerException
     *            If the key is <code>null</code>.
     */
    public JSONObject append(String key, Object value) throws JSONException {
        testValidity(value);
        Object object = this.opt(key);
        if (object == null) {
            this.put(key, new JSONArray().put(value));
        } else if (object instanceof JSONArray) {
            this.put(key, ((JSONArray) object).put(value));
        } else {
            throw new JSONException("JSONObject[" + key
                    + "] is not a JSONArray.");
        }
        return this;
    }

    /**
     * Produce a string from a double. The string "null" will be returned if the
     * number is not finite.
     *
     * @param d
     *            A double.
     * @return A String.
     */
    public static String doubleToString(double d) {
        if (Double.isInfinite(d) || Double.isNaN(d)) {
            return "null";
        }

// Shave off trailing zeros and decimal point, if possible.

        String string = Double.toString(d);
        if (string.indexOf('.') > 0 && string.indexOf('e') < 0
                && string.indexOf('E') < 0) {
            while (string.endsWith("0")) {
                string = string.substring(0, string.length() - 1);
            }
            if (string.endsWith(".")) {
                string = string.substring(0, string.length() - 1);
            }
        }
        return string;
    }

    /**
     * Get the value object associated with a key.
     *
     * @param key
     *            A key string.
     * @return The object associated with the key.
     * @throws JSONException
     *             if the key is not found.
     */
    public Object get(String key) throws JSONException {
        if (key == null) {
            throw new JSONException("Null key.");
        }
        Object object = this.opt(key);
        if (object == null) {
            throw new JSONException("JSONObject[" + quote(key) + "] not found.");
        }
        return object;
    }

    /**
    * Get the enum value associated with a key.
    * 
    * @param clazz
    *           The type of enum to retrieve.
    * @param key
    *           A key string.
    * @return The enum value associated with the key
    * @throws JSONException
    *             if the key is not found or if the value cannot be converted
    *             to an enum.
    */
    public <E extends Enum<E>> E getEnum(Class<E> clazz, String key) throws JSONException {
        E val = optEnum(clazz, key);
        if(val==null) {
            // JSONException should really take a throwable argument.
            // If it did, I would re-implement this with the Enum.valueOf
            // method and place any thrown exception in the JSONException
            throw new JSONException("JSONObject[" + quote(key)
                    + "] is not an enum of type " + quote(clazz.getSimpleName())
                    + ".");
        }
        return val;
    }

    /**
     * Get the boolean value associated with a key.
     *
     * @param key
     *            A key string.
     * @return The truth.
     * @throws JSONException
     *             if the value is not a Boolean or the String "true" or
     *             "false".
     */
    public boolean getBoolean(String key) throws JSONException {
        Object object = this.get(key);
        if (object.equals(Boolean.FALSE)
                || (object instanceof String && ((String) object)
                        .equalsIgnoreCase("false"))) {
            return false;
        } else if (object.equals(Boolean.TRUE)
                || (object instanceof String && ((String) object)
                        .equalsIgnoreCase("true"))) {
            return true;
        }
        throw new JSONException("JSONObject[" + quote(key)
                + "] is not a Boolean.");
    }

    /**
     * Get the BigInteger value associated with a key.
     *
     * @param key
     *            A key string.
     * @return The numeric value.
     * @throws JSONException
     *             if the key is not found or if the value cannot 
     *             be converted to BigInteger.
     */
    public BigInteger getBigInteger(String key) throws JSONException {
        Object object = this.get(key);
        try {
            return new BigInteger(object.toString());
        } catch (Exception e) {
            throw new JSONException("JSONObject[" + quote(key)
                    + "] could not be converted to BigInteger.", e);
        }
    }

    /**
     * Get the BigDecimal value associated with a key.
     *
     * @param key
     *            A key string.
     * @return The numeric value.
     * @throws JSONException
     *             if the key is not found or if the value
     *             cannot be converted to BigDecimal.
     */
    public BigDecimal getBigDecimal(String key) throws JSONException {
        Object object = this.get(key);
        if (object instanceof BigDecimal) {
            return (BigDecimal)object;
        }
        try {
            return new BigDecimal(object.toString());
        } catch (Exception e) {
            throw new JSONException("JSONObject[" + quote(key)
                    + "] could not be converted to BigDecimal.", e);
        }
    }

    /**
     * Get the double value associated with a key.
     *
     * @param key
     *            A key string.
     * @return The numeric value.
     * @throws JSONException
     *             if the key is not found or if the value is not a Number
     *             object and cannot be converted to a number.
     */
    public double getDouble(String key) throws JSONException {
        Object object = this.get(key);
        try {
            return object instanceof Number ? ((Number) object).doubleValue()
                    : Double.parseDouble(object.toString());
        } catch (Exception e) {
            throw new JSONException("JSONObject[" + quote(key)
                    + "] is not a number.", e);
        }
    }

    /**
     * Get the float value associated with a key.
     *
     * @param key
     *            A key string.
     * @return The numeric value.
     * @throws JSONException
     *             if the key is not found or if the value is not a Number
     *             object and cannot be converted to a number.
     */
    public float getFloat(String key) throws JSONException {
        Object object = this.get(key);
        try {
            return object instanceof Number ? ((Number) object).floatValue()
                    : Float.parseFloat(object.toString());
        } catch (Exception e) {
            throw new JSONException("JSONObject[" + quote(key)
                    + "] is not a number.", e);
        }
    }

    /**
     * Get the Number value associated with a key.
     *
     * @param key
     *            A key string.
     * @return The numeric value.
     * @throws JSONException
     *             if the key is not found or if the value is not a Number
     *             object and cannot be converted to a number.
     */
    public Number getNumber(String key) throws JSONException {
        Object object = this.get(key);
        try {
            if (object instanceof Number) {
                return (Number)object;
            }
            return stringToNumber(object.toString());
        } catch (Exception e) {
            throw new JSONException("JSONObject[" + quote(key)
                    + "] is not a number.", e);
        }
    }

    /**
     * Get the int value associated with a key.
     *
     * @param key
     *            A key string.
     * @return The integer value.
     * @throws JSONException
     *             if the key is not found or if the value cannot be converted
     *             to an integer.
     */
    public int getInt(String key) throws JSONException {
        Object object = this.get(key);
        try {
            return object instanceof Number ? ((Number) object).intValue()
                    : Integer.parseInt((String) object);
        } catch (Exception e) {
            throw new JSONException("JSONObject[" + quote(key)
                    + "] is not an int.", e);
        }
    }

    /**
     * Get the JSONArray value associated with a key.
     *
     * @param key
     *            A key string.
     * @return A JSONArray which is the value.
     * @throws JSONException
     *             if the key is not found or if the value is not a JSONArray.
     */
    public JSONArray getJSONArray(String key) throws JSONException {
        Object object = this.get(key);
        if (object instanceof JSONArray) {
            return (JSONArray) object;
        }
        throw new JSONException("JSONObject[" + quote(key)
                + "] is not a JSONArray.");
    }

    /**
     * Get the JSONObject value associated with a key.
     *
     * @param key
     *            A key string.
     * @return A JSONObject which is the value.
     * @throws JSONException
     *             if the key is not found or if the value is not a JSONObject.
     */
    public JSONObject getJSONObject(String key) throws JSONException {
        Object object = this.get(key);
        if (object instanceof JSONObject) {
            return (JSONObject) object;
        }
        throw new JSONException("JSONObject[" + quote(key)
                + "] is not a JSONObject.");
    }

    /**
     * Get the long value associated with a key.
     *
     * @param key
     *            A key string.
     * @return The long value.
     * @throws JSONException
     *             if the key is not found or if the value cannot be converted
     *             to a long.
     */
    public long getLong(String key) throws JSONException {
        Object object = this.get(key);
        try {
            return object instanceof Number ? ((Number) object).longValue()
                    : Long.parseLong((String) object);
        } catch (Exception e) {
            throw new JSONException("JSONObject[" + quote(key)
                    + "] is not a long.", e);
        }
    }

    /**
     * Get an array of field names from a JSONObject.
     *
     * @return An array of field names, or null if there are no names.
     */
    public static String[] getNames(JSONObject jo) {
        int length = jo.length();
        if (length == 0) {
            return null;
        }
        return jo.keySet().toArray(new String[length]);
    }

    /**
     * Get an array of field names from an Object.
     *
     * @return An array of field names, or null if there are no names.
     */
    public static String[] getNames(Object object) {
        if (object == null) {
            return null;
        }
        Class<?> klass = object.getClass();
        Field[] fields = klass.getFields();
        int length = fields.length;
        if (length == 0) {
            return null;
        }
        String[] names = new String[length];
        for (int i = 0; i < length; i += 1) {
            names[i] = fields[i].getName();
        }
        return names;
    }

    /**
     * Get the string associated with a key.
     *
     * @param key
     *            A key string.
     * @return A string which is the value.
     * @throws JSONException
     *             if there is no string value for the key.
     */
    public String getString(String key) throws JSONException {
        Object object = this.get(key);
        if (object instanceof String) {
            return (String) object;
        }
        throw new JSONException("JSONObject[" + quote(key) + "] not a string.");
    }

    /**
     * Determine if the JSONObject contains a specific key.
     *
     * @param key
     *            A key string.
     * @return true if the key exists in the JSONObject.
     */
    public boolean has(String key) {
        return this.map.containsKey(key);
    }

    /**
     * Increment a property of a JSONObject. If there is no such property,
     * create one with a value of 1. If there is such a property, and if it is
     * an Integer, Long, Double, or Float, then add one to it.
     *
     * @param key
     *            A key string.
     * @return this.
     * @throws JSONException
     *             If there is already a property with this name that is not an
     *             Integer, Long, Double, or Float.
     */
    public JSONObject increment(String key) throws JSONException {
        Object value = this.opt(key);
        if (value == null) {
            this.put(key, 1);
        } else if (value instanceof BigInteger) {
            this.put(key, ((BigInteger)value).add(BigInteger.ONE));
        } else if (value instanceof BigDecimal) {
            this.put(key, ((BigDecimal)value).add(BigDecimal.ONE));
        } else if (value instanceof Integer) {
            this.put(key, ((Integer) value).intValue() + 1);
        } else if (value instanceof Long) {
            this.put(key, ((Long) value).longValue() + 1L);
        } else if (value instanceof Double) {
            this.put(key, ((Double) value).doubleValue() + 1.0d);
        } else if (value instanceof Float) {
            this.put(key, ((Float) value).floatValue() + 1.0f);
        } else {
            throw new JSONException("Unable to increment [" + quote(key) + "].");
        }
        return this;
    }

    /**
     * Determine if the value associated with the key is <code>null</code> or if there is no
     * value.
     *
     * @param key
     *            A key string.
     * @return true if there is no value associated with the key or if the value
     *        is the JSONObject.NULL object.
     */
    public boolean isNull(String key) {
        return JSONObject.NULL.equals(this.opt(key));
    }

    /**
     * Get an enumeration of the keys of the JSONObject. Modifying this key Set will also
     * modify the JSONObject. Use with caution.
     *
     * @see Set#iterator()
     * 
     * @return An iterator of the keys.
     */
    public Iterator<String> keys() {
        return this.keySet().iterator();
    }

    /**
     * Get a set of keys of the JSONObject. Modifying this key Set will also modify the
     * JSONObject. Use with caution.
     *
     * @see Map#keySet()
     *
     * @return A keySet.
     */
    public Set<String> keySet() {
        return this.map.keySet();
    }

    /**
     * Get a set of entries of the JSONObject. These are raw values and may not
     * match what is returned by the JSONObject get* and opt* functions. Modifying 
     * the returned EntrySet or the Entry objects contained therein will modify the
     * backing JSONObject. This does not return a clone or a read-only view.
     * 
     * Use with caution.
     *
     * @see Map#entrySet()
     *
     * @return An Entry Set
     */
    protected Set<Entry<String, Object>> entrySet() {
        return this.map.entrySet();
    }

    /**
     * Get the number of keys stored in the JSONObject.
     *
     * @return The number of keys in the JSONObject.
     */
    public int length() {
        return this.map.size();
    }

    /**
     * Produce a JSONArray containing the names of the elements of this
     * JSONObject.
     *
     * @return A JSONArray containing the key strings, or null if the JSONObject
     *        is empty.
     */
    public JSONArray names() {
    	if(this.map.isEmpty()) {
    		return null;
    	}
        return new JSONArray(this.map.keySet());
    }

    /**
     * Produce a string from a Number.
     *
     * @param number
     *            A Number
     * @return A String.
     * @throws JSONException
     *             If n is a non-finite number.
     */
    public static String numberToString(Number number) throws JSONException {
        if (number == null) {
            throw new JSONException("Null pointer");
        }
        testValidity(number);

        // Shave off trailing zeros and decimal point, if possible.

        String string = number.toString();
        if (string.indexOf('.') > 0 && string.indexOf('e') < 0
                && string.indexOf('E') < 0) {
            while (string.endsWith("0")) {
                string = string.substring(0, string.length() - 1);
            }
            if (string.endsWith(".")) {
                string = string.substring(0, string.length() - 1);
            }
        }
        return string;
    }

    /**
     * Get an optional value associated with a key.
     *
     * @param key
     *            A key string.
     * @return An object which is the value, or null if there is no value.
     */
    public Object opt(String key) {
        return key == null ? null : this.map.get(key);
    }

    /**
     * Get the enum value associated with a key.
     * 
     * @param clazz
     *            The type of enum to retrieve.
     * @param key
     *            A key string.
     * @return The enum value associated with the key or null if not found
     */
    public <E extends Enum<E>> E optEnum(Class<E> clazz, String key) {
        return this.optEnum(clazz, key, null);
    }

    /**
     * Get the enum value associated with a key.
     * 
     * @param clazz
     *            The type of enum to retrieve.
     * @param key
     *            A key string.
     * @param defaultValue
     *            The default in case the value is not found
     * @return The enum value associated with the key or defaultValue
     *            if the value is not found or cannot be assigned to <code>clazz</code>
     */
    public <E extends Enum<E>> E optEnum(Class<E> clazz, String key, E defaultValue) {
        try {
            Object val = this.opt(key);
            if (NULL.equals(val)) {
                return defaultValue;
            }
            if (clazz.isAssignableFrom(val.getClass())) {
                // we just checked it!
                @SuppressWarnings("unchecked")
                E myE = (E) val;
                return myE;
            }
            return Enum.valueOf(clazz, val.toString());
        } catch (IllegalArgumentException e) {
            return defaultValue;
        } catch (NullPointerException e) {
            return defaultValue;
        }
    }

    /**
     * Get an optional boolean associated with a key. It returns false if there
     * is no such key, or if the value is not Boolean.TRUE or the String "true".
     *
     * @param key
     *            A key string.
     * @return The truth.
     */
    public boolean optBoolean(String key) {
        return this.optBoolean(key, false);
    }

    /**
     * Get an optional boolean associated with a key. It returns the
     * defaultValue if there is no such key, or if it is not a Boolean or the
     * String "true" or "false" (case insensitive).
     *
     * @param key
     *            A key string.
     * @param defaultValue
     *            The default.
     * @return The truth.
     */
    public boolean optBoolean(String key, boolean defaultValue) {
        Object val = this.opt(key);
        if (NULL.equals(val)) {
            return defaultValue;
        }
        if (val instanceof Boolean){
            return ((Boolean) val).booleanValue();
        }
        try {
            // we'll use the get anyway because it does string conversion.
            return this.getBoolean(key);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    /**
     * Get an optional BigDecimal associated with a key, or the defaultValue if
     * there is no such key or if its value is not a number. If the value is a
     * string, an attempt will be made to evaluate it as a number.
     *
     * @param key
     *            A key string.
     * @param defaultValue
     *            The default.
     * @return An object which is the value.
     */
    public BigDecimal optBigDecimal(String key, BigDecimal defaultValue) {
        Object val = this.opt(key);
        if (NULL.equals(val)) {
            return defaultValue;
        }
        if (val instanceof BigDecimal){
            return (BigDecimal) val;
        }
        if (val instanceof BigInteger){
            return new BigDecimal((BigInteger) val);
        }
        if (val instanceof Double || val instanceof Float){
            return new BigDecimal(((Number) val).doubleValue());
        }
        if (val instanceof Long || val instanceof Integer
                || val instanceof Short || val instanceof Byte){
            return new BigDecimal(((Number) val).longValue());
        }
        // don't check if it's a string in case of unchecked Number subclasses
        try {
            return new BigDecimal(val.toString());
        } catch (Exception e) {
            return defaultValue;
        }
    }

    /**
     * Get an optional BigInteger associated with a key, or the defaultValue if
     * there is no such key or if its value is not a number. If the value is a
     * string, an attempt will be made to evaluate it as a number.
     *
     * @param key
     *            A key string.
     * @param defaultValue
     *            The default.
     * @return An object which is the value.
     */
    public BigInteger optBigInteger(String key, BigInteger defaultValue) {
        Object val = this.opt(key);
        if (NULL.equals(val)) {
            return defaultValue;
        }
        if (val instanceof BigInteger){
            return (BigInteger) val;
        }
        if (val instanceof BigDecimal){
            return ((BigDecimal) val).toBigInteger();
        }
        if (val instanceof Double || val instanceof Float){
            return new BigDecimal(((Number) val).doubleValue()).toBigInteger();
        }
        if (val instanceof Long || val instanceof Integer
                || val instanceof Short || val instanceof Byte){
            return BigInteger.valueOf(((Number) val).longValue());
        }
        // don't check if it's a string in case of unchecked Number subclasses
        try {
            // the other opt functions handle implicit conversions, i.e. 
            // jo.put("double",1.1d);
            // jo.optInt("double"); -- will return 1, not an error
            // this conversion to BigDecimal then to BigInteger is to maintain
            // that type cast support that may truncate the decimal.
            final String valStr = val.toString();
            if(isDecimalNotation(valStr)) {
                return new BigDecimal(valStr).toBigInteger();
            }
            return new BigInteger(valStr);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    /**
     * Get an optional double associated with a key, or NaN if there is no such
     * key or if its value is not a number. If the value is a string, an attempt
     * will be made to evaluate it as a number.
     *
     * @param key
     *            A string which is the key.
     * @return An object which is the value.
     */
    public double optDouble(String key) {
        return this.optDouble(key, Double.NaN);
    }

    /**
     * Get an optional double associated with a key, or the defaultValue if
     * there is no such key or if its value is not a number. If the value is a
     * string, an attempt will be made to evaluate it as a number.
     *
     * @param key
     *            A key string.
     * @param defaultValue
     *            The default.
     * @return An object which is the value.
     */
    public double optDouble(String key, double defaultValue) {
        Object val = this.opt(key);
        if (NULL.equals(val)) {
            return defaultValue;
        }
        if (val instanceof Number){
            return ((Number) val).doubleValue();
        }
        if (val instanceof String) {
            try {
                return Double.parseDouble((String) val);
            } catch (Exception e) {
                return defaultValue;
            }
        }
        return defaultValue;
    }

    /**
     * Get the optional double value associated with an index. NaN is returned
     * if there is no value for the index, or if the value is not a number and
     * cannot be converted to a number.
     *
     * @param key
     *            A key string.
     * @return The value.
     */
    public float optFloat(String key) {
        return this.optFloat(key, Float.NaN);
    }

    /**
     * Get the optional double value associated with an index. The defaultValue
     * is returned if there is no value for the index, or if the value is not a
     * number and cannot be converted to a number.
     *
     * @param key
     *            A key string.
     * @param defaultValue
     *            The default value.
     * @return The value.
     */
    public float optFloat(String key, float defaultValue) {
        Object val = this.opt(key);
        if (JSONObject.NULL.equals(val)) {
            return defaultValue;
        }
        if (val instanceof Number){
            return ((Number) val).floatValue();
        }
        if (val instanceof String) {
            try {
                return Float.parseFloat((String) val);
            } catch (Exception e) {
                return defaultValue;
            }
        }
        return defaultValue;
    }

    /**
     * Get an optional int value associated with a key, or zero if there is no
     * such key or if the value is not a number. If the value is a string, an
     * attempt will be made to evaluate it as a number.
     *
     * @param key
     *            A key string.
     * @return An object which is the value.
     */
    public int optInt(String key) {
        return this.optInt(key, 0);
    }

    /**
     * Get an optional int value associated with a key, or the default if there
     * is no such key or if the value is not a number. If the value is a string,
     * an attempt will be made to evaluate it as a number.
     *
     * @param key
     *            A key string.
     * @param defaultValue
     *            The default.
     * @return An object which is the value.
     */
    public int optInt(String key, int defaultValue) {
        Object val = this.opt(key);
        if (NULL.equals(val)) {
            return defaultValue;
        }
        if (val instanceof Number){
            return ((Number) val).intValue();
        }
        
        if (val instanceof String) {
            try {
                return new BigDecimal((String) val).intValue();
            } catch (Exception e) {
                return defaultValue;
            }
        }
        return defaultValue;
    }

    /**
     * Get an optional JSONArray associated with a key. It returns null if there
     * is no such key, or if its value is not a JSONArray.
     *
     * @param key
     *            A key string.
     * @return A JSONArray which is the value.
     */
    public JSONArray optJSONArray(String key) {
        Object o = this.opt(key);
        return o instanceof JSONArray ? (JSONArray) o : null;
    }

    /**
     * Get an optional JSONObject associated with a key. It returns null if
     * there is no such key, or if its value is not a JSONObject.
     *
     * @param key
     *            A key string.
     * @return A JSONObject which is the value.
     */
    public JSONObject optJSONObject(String key) {
        Object object = this.opt(key);
        return object instanceof JSONObject ? (JSONObject) object : null;
    }

    /**
     * Get an optional long value associated with a key, or zero if there is no
     * such key or if the value is not a number. If the value is a string, an
     * attempt will be made to evaluate it as a number.
     *
     * @param key
     *            A key string.
     * @return An object which is the value.
     */
    public long optLong(String key) {
        return this.optLong(key, 0);
    }

    /**
     * Get an optional long value associated with a key, or the default if there
     * is no such key or if the value is not a number. If the value is a string,
     * an attempt will be made to evaluate it as a number.
     *
     * @param key
     *            A key string.
     * @param defaultValue
     *            The default.
     * @return An object which is the value.
     */
    public long optLong(String key, long defaultValue) {
        Object val = this.opt(key);
        if (NULL.equals(val)) {
            return defaultValue;
        }
        if (val instanceof Number){
            return ((Number) val).longValue();
        }
        
        if (val instanceof String) {
            try {
                return new BigDecimal((String) val).longValue();
            } catch (Exception e) {
                return defaultValue;
            }
        }
        return defaultValue;
    }
    
    /**
     * Get an optional {@link Number} value associated with a key, or <code>null</code>
     * if there is no such key or if the value is not a number. If the value is a string,
     * an attempt will be made to evaluate it as a number ({@link BigDecimal}). This method
     * would be used in cases where type coercion of the number value is unwanted.
     *
     * @param key
     *            A key string.
     * @return An object which is the value.
     */
    public Number optNumber(String key) {
        return this.optNumber(key, null);
    }

    /**
     * Get an optional {@link Number} value associated with a key, or the default if there
     * is no such key or if the value is not a number. If the value is a string,
     * an attempt will be made to evaluate it as a number. This method
     * would be used in cases where type coercion of the number value is unwanted.
     *
     * @param key
     *            A key string.
     * @param defaultValue
     *            The default.
     * @return An object which is the value.
     */
    public Number optNumber(String key, Number defaultValue) {
        Object val = this.opt(key);
        if (NULL.equals(val)) {
            return defaultValue;
        }
        if (val instanceof Number){
            return (Number) val;
        }
        
        if (val instanceof String) {
            try {
                return stringToNumber((String) val);
            } catch (Exception e) {
                return defaultValue;
            }
        }
        return defaultValue;
    }
    
    /**
     * Get an optional string associated with a key. It returns an empty string
     * if there is no such key. If the value is not a string and is not null,
     * then it is converted to a string.
     *
     * @param key
     *            A key string.
     * @return A string which is the value.
     */
    public String optString(String key) {
        return this.optString(key, "");
    }

    /**
     * Get an optional string associated with a key. It returns the defaultValue
     * if there is no such key.
     *
     * @param key
     *            A key string.
     * @param defaultValue
     *            The default.
     * @return A string which is the value.
     */
    public String optString(String key, String defaultValue) {
        Object object = this.opt(key);
        return NULL.equals(object) ? defaultValue : object.toString();
    }

    /**
     * Populates the internal map of the JSONObject with the bean properties. The
     * bean can not be recursive.
     *
     * @see JSONObject#JSONObject(Object)
     *
     * @param bean
     *            the bean
     */
    private void populateMap(Object bean) {
        Class<?> klass = bean.getClass();

        // If klass is a System class then set includeSuperClass to false.

        boolean includeSuperClass = klass.getClassLoader() != null;

        Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods();
        for (final Method method : methods) {
            final int modifiers = method.getModifiers();
            if (Modifier.isPublic(modifiers)
                    && !Modifier.isStatic(modifiers)
                    && method.getParameterTypes().length == 0
                    && !method.isBridge()
                    && method.getReturnType() != Void.TYPE
                    && isValidMethodName(method.getName())) {
                final String key = getKeyNameFromMethod(method);
                if (key != null && !key.isEmpty()) {
                    try {
                        final Object result = method.invoke(bean);
                        if (result != null) {
                            this.map.put(key, wrap(result));
                            // we don't use the result anywhere outside of wrap
                            // if it's a resource we should be sure to close it
                            // after calling toString
                            if (result instanceof Closeable) {
                                try {
                                    ((Closeable) result).close();
                                } catch (IOException ignore) {
                                }
                            }
                        }
                    } catch (IllegalAccessException ignore) {
                    } catch (IllegalArgumentException ignore) {
                    } catch (InvocationTargetException ignore) {
                    }
                }
            }
        }
    }

    private boolean isValidMethodName(String name) {
        return !"getClass".equals(name) && !"getDeclaringClass".equals(name);
    }

    private String getKeyNameFromMethod(Method method) {
        final int ignoreDepth = getAnnotationDepth(method, JSONPropertyIgnore.class);
        if (ignoreDepth > 0) {
            final int forcedNameDepth = getAnnotationDepth(method, JSONPropertyName.class);
            if (forcedNameDepth < 0 || ignoreDepth <= forcedNameDepth) {
                // the hierarchy asked to ignore, and the nearest name override
                // was higher or non-existent
                return null;
            }
        }
        JSONPropertyName annotation = getAnnotation(method, JSONPropertyName.class);
        if (annotation != null && annotation.value() != null && !annotation.value().isEmpty()) {
            return annotation.value();
        }
        String key;
        final String name = method.getName();
        if (name.startsWith("get") && name.length() > 3) {
            key = name.substring(3);
        } else if (name.startsWith("is") && name.length() > 2) {
            key = name.substring(2);
        } else {
            return null;
        }
        // if the first letter in the key is not uppercase, then skip.
        // This is to maintain backwards compatibility before PR406
        // (https://github.com/stleary/JSON-java/pull/406/)
        if (Character.isLowerCase(key.charAt(0))) {
            return null;
        }
        if (key.length() == 1) {
            key = key.toLowerCase(Locale.ROOT);
        } else if (!Character.isUpperCase(key.charAt(1))) {
            key = key.substring(0, 1).toLowerCase(Locale.ROOT) + key.substring(1);
        }
        return key;
    }

    /**
     * Searches the class hierarchy to see if the method or it's super
     * implementations and interfaces has the annotation.
     *
     * @param <A>
     *            type of the annotation
     *
     * @param m
     *            method to check
     * @param annotationClass
     *            annotation to look for
     * @return the {@link Annotation} if the annotation exists on the current method
     *         or one of it's super class definitions
     */
    private static <A extends Annotation> A getAnnotation(final Method m, final Class<A> annotationClass) {
        // if we have invalid data the result is null
        if (m == null || annotationClass == null) {
            return null;
        }

        if (m.isAnnotationPresent(annotationClass)) {
            return m.getAnnotation(annotationClass);
        }

        // if we've already reached the Object class, return null;
        Class<?> c = m.getDeclaringClass();
        if (c.getSuperclass() == null) {
            return null;
        }

        // check directly implemented interfaces for the method being checked
        for (Class<?> i : c.getInterfaces()) {
            try {
                Method im = i.getMethod(m.getName(), m.getParameterTypes());
                return getAnnotation(im, annotationClass);
            } catch (final SecurityException ex) {
                continue;
            } catch (final NoSuchMethodException ex) {
                continue;
            }
        }

        try {
            return getAnnotation(
                    c.getSuperclass().getMethod(m.getName(), m.getParameterTypes()),
                    annotationClass);
        } catch (final SecurityException ex) {
            return null;
        } catch (final NoSuchMethodException ex) {
            return null;
        }
    }

    /**
     * Searches the class hierarchy to see if the method or it's super
     * implementations and interfaces has the annotation. Returns the depth of the
     * annotation in the hierarchy.
     *
     * @param <A>
     *            type of the annotation
     *
     * @param m
     *            method to check
     * @param annotationClass
     *            annotation to look for
     * @return Depth of the annotation or -1 if the annotation is not on the method.
     */
    private static int getAnnotationDepth(final Method m, final Class<? extends Annotation> annotationClass) {
        // if we have invalid data the result is -1
        if (m == null || annotationClass == null) {
            return -1;
        }

        if (m.isAnnotationPresent(annotationClass)) {
            return 1;
        }

        // if we've already reached the Object class, return -1;
        Class<?> c = m.getDeclaringClass();
        if (c.getSuperclass() == null) {
            return -1;
        }

        // check directly implemented interfaces for the method being checked
        for (Class<?> i : c.getInterfaces()) {
            try {
                Method im = i.getMethod(m.getName(), m.getParameterTypes());
                int d = getAnnotationDepth(im, annotationClass);
                if (d > 0) {
                    // since the annotation was on the interface, add 1
                    return d + 1;
                }
            } catch (final SecurityException ex) {
                continue;
            } catch (final NoSuchMethodException ex) {
                continue;
            }
        }

        try {
            int d = getAnnotationDepth(
                    c.getSuperclass().getMethod(m.getName(), m.getParameterTypes()),
                    annotationClass);
            if (d > 0) {
                // since the annotation was on the superclass, add 1
                return d + 1;
            }
            return -1;
        } catch (final SecurityException ex) {
            return -1;
        } catch (final NoSuchMethodException ex) {
            return -1;
        }
    }

    /**
     * Put a key/boolean pair in the JSONObject.
     *
     * @param key
     *            A key string.
     * @param value
     *            A boolean which is the value.
     * @return this.
     * @throws JSONException
     *            If the value is non-finite number.
     * @throws NullPointerException
     *            If the key is <code>null</code>.
     */
    public JSONObject put(String key, boolean value) throws JSONException {
        return this.put(key, value ? Boolean.TRUE : Boolean.FALSE);
    }

    /**
     * Put a key/value pair in the JSONObject, where the value will be a
     * JSONArray which is produced from a Collection.
     *
     * @param key
     *            A key string.
     * @param value
     *            A Collection value.
     * @return this.
     * @throws JSONException
     *            If the value is non-finite number.
     * @throws NullPointerException
     *            If the key is <code>null</code>.
     */
    public JSONObject put(String key, Collection<?> value) throws JSONException {
        return this.put(key, new JSONArray(value));
    }

    /**
     * Put a key/double pair in the JSONObject.
     *
     * @param key
     *            A key string.
     * @param value
     *            A double which is the value.
     * @return this.
     * @throws JSONException
     *            If the value is non-finite number.
     * @throws NullPointerException
     *            If the key is <code>null</code>.
     */
    public JSONObject put(String key, double value) throws JSONException {
        return this.put(key, Double.valueOf(value));
    }
    
    /**
     * Put a key/float pair in the JSONObject.
     *
     * @param key
     *            A key string.
     * @param value
     *            A float which is the value.
     * @return this.
     * @throws JSONException
     *            If the value is non-finite number.
     * @throws NullPointerException
     *            If the key is <code>null</code>.
     */
    public JSONObject put(String key, float value) throws JSONException {
        return this.put(key, Float.valueOf(value));
    }

    /**
     * Put a key/int pair in the JSONObject.
     *
     * @param key
     *            A key string.
     * @param value
     *            An int which is the value.
     * @return this.
     * @throws JSONException
     *            If the value is non-finite number.
     * @throws NullPointerException
     *            If the key is <code>null</code>.
     */
    public JSONObject put(String key, int value) throws JSONException {
        return this.put(key, Integer.valueOf(value));
    }

    /**
     * Put a key/long pair in the JSONObject.
     *
     * @param key
     *            A key string.
     * @param value
     *            A long which is the value.
     * @return this.
     * @throws JSONException
     *            If the value is non-finite number.
     * @throws NullPointerException
     *            If the key is <code>null</code>.
     */
    public JSONObject put(String key, long value) throws JSONException {
        return this.put(key, Long.valueOf(value));
    }

    /**
     * Put a key/value pair in the JSONObject, where the value will be a
     * JSONObject which is produced from a Map.
     *
     * @param key
     *            A key string.
     * @param value
     *            A Map value.
     * @return this.
     * @throws JSONException
     *            If the value is non-finite number.
     * @throws NullPointerException
     *            If the key is <code>null</code>.
     */
    public JSONObject put(String key, Map<?, ?> value) throws JSONException {
        return this.put(key, new JSONObject(value));
    }

    /**
     * Put a key/value pair in the JSONObject. If the value is <code>null</code>, then the
     * key will be removed from the JSONObject if it is present.
     *
     * @param key
     *            A key string.
     * @param value
     *            An object which is the value. It should be of one of these
     *            types: Boolean, Double, Integer, JSONArray, JSONObject, Long,
     *            String, or the JSONObject.NULL object.
     * @return this.
     * @throws JSONException
     *            If the value is non-finite number.
     * @throws NullPointerException
     *            If the key is <code>null</code>.
     */
    public JSONObject put(String key, Object value) throws JSONException {
        if (key == null) {
            throw new NullPointerException("Null key.");
        }
        if (value != null) {
            testValidity(value);
            this.map.put(key, value);
        } else {
            this.remove(key);
        }
        return this;
    }

    /**
     * Put a key/value pair in the JSONObject, but only if the key and the value
     * are both non-null, and only if there is not already a member with that
     * name.
     *
     * @param key string
     * @param value object
     * @return this.
     * @throws JSONException
     *             if the key is a duplicate
     */
    public JSONObject putOnce(String key, Object value) throws JSONException {
        if (key != null && value != null) {
            if (this.opt(key) != null) {
                throw new JSONException("Duplicate key \"" + key + "\"");
            }
            return this.put(key, value);
        }
        return this;
    }

    /**
     * Put a key/value pair in the JSONObject, but only if the key and the value
     * are both non-null.
     *
     * @param key
     *            A key string.
     * @param value
     *            An object which is the value. It should be of one of these
     *            types: Boolean, Double, Integer, JSONArray, JSONObject, Long,
     *            String, or the JSONObject.NULL object.
     * @return this.
     * @throws JSONException
     *             If the value is a non-finite number.
     */
    public JSONObject putOpt(String key, Object value) throws JSONException {
        if (key != null && value != null) {
            return this.put(key, value);
        }
        return this;
    }

    /**
     * Creates a JSONPointer using an initialization string and tries to 
     * match it to an item within this JSONObject. For example, given a
     * JSONObject initialized with this document:
     * <pre>
     * {
     *     "a":{"b":"c"}
     * }
     * </pre>
     * and this JSONPointer string: 
     * <pre>
     * "/a/b"
     * </pre>
     * Then this method will return the String "c".
     * A JSONPointerException may be thrown from code called by this method.
     *   
     * @param jsonPointer string that can be used to create a JSONPointer
     * @return the item matched by the JSONPointer, otherwise null
     */
    public Object query(String jsonPointer) {
        return query(new JSONPointer(jsonPointer));
    }
    /**
     * Uses a user initialized JSONPointer  and tries to 
     * match it to an item within this JSONObject. For example, given a
     * JSONObject initialized with this document:
     * <pre>
     * {
     *     "a":{"b":"c"}
     * }
     * </pre>
     * and this JSONPointer: 
     * <pre>
     * "/a/b"
     * </pre>
     * Then this method will return the String "c".
     * A JSONPointerException may be thrown from code called by this method.
     *   
     * @param jsonPointer string that can be used to create a JSONPointer
     * @return the item matched by the JSONPointer, otherwise null
     */
    public Object query(JSONPointer jsonPointer) {
        return jsonPointer.queryFrom(this);
    }
    
    /**
     * Queries and returns a value from this object using {@code jsonPointer}, or
     * returns null if the query fails due to a missing key.
     * 
     * @param jsonPointer the string representation of the JSON pointer
     * @return the queried value or {@code null}
     * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax
     */
    public Object optQuery(String jsonPointer) {
    	return optQuery(new JSONPointer(jsonPointer));
    }
    
    /**
     * Queries and returns a value from this object using {@code jsonPointer}, or
     * returns null if the query fails due to a missing key.
     * 
     * @param jsonPointer The JSON pointer
     * @return the queried value or {@code null}
     * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax
     */
    public Object optQuery(JSONPointer jsonPointer) {
        try {
            return jsonPointer.queryFrom(this);
        } catch (JSONPointerException e) {
            return null;
        }
    }

    /**
     * Produce a string in double quotes with backslash sequences in all the
     * right places. A backslash will be inserted within </, producing <\/,
     * allowing JSON text to be delivered in HTML. In JSON text, a string cannot
     * contain a control character or an unescaped quote or backslash.
     *
     * @param string
     *            A String
     * @return A String correctly formatted for insertion in a JSON text.
     */
    public static String quote(String string) {
        StringWriter sw = new StringWriter();
        synchronized (sw.getBuffer()) {
            try {
                return quote(string, sw).toString();
            } catch (IOException ignored) {
                // will never happen - we are writing to a string writer
                return "";
            }
        }
    }

    public static Writer quote(String string, Writer w) throws IOException {
        if (string == null || string.length() == 0) {
            w.write("\"\"");
            return w;
        }

        char b;
        char c = 0;
        String hhhh;
        int i;
        int len = string.length();

        w.write('"');
        for (i = 0; i < len; i += 1) {
            b = c;
            c = string.charAt(i);
            switch (c) {
            case '\\':
            case '"':
                w.write('\\');
                w.write(c);
                break;
            case '/':
                if (b == '<') {
                    w.write('\\');
                }
                w.write(c);
                break;
            case '\b':
                w.write("\\b");
                break;
            case '\t':
                w.write("\\t");
                break;
            case '\n':
                w.write("\\n");
                break;
            case '\f':
                w.write("\\f");
                break;
            case '\r':
                w.write("\\r");
                break;
            default:
                if (c < ' ' || (c >= '\u0080' && c < '\u00a0')
                        || (c >= '\u2000' && c < '\u2100')) {
                    w.write("\\u");
                    hhhh = Integer.toHexString(c);
                    w.write("0000", 0, 4 - hhhh.length());
                    w.write(hhhh);
                } else {
                    w.write(c);
                }
            }
        }
        w.write('"');
        return w;
    }

    /**
     * Remove a name and its value, if present.
     *
     * @param key
     *            The name to be removed.
     * @return The value that was associated with the name, or null if there was
     *         no value.
     */
    public Object remove(String key) {
        return this.map.remove(key);
    }

    /**
     * Determine if two JSONObjects are similar.
     * They must contain the same set of names which must be associated with
     * similar values.
     *
     * @param other The other JSONObject
     * @return true if they are equal
     */
    public boolean similar(Object other) {
        try {
            if (!(other instanceof JSONObject)) {
                return false;
            }
            if (!this.keySet().equals(((JSONObject)other).keySet())) {
                return false;
            }
            for (final Entry<String,?> entry : this.entrySet()) {
                String name = entry.getKey();
                Object valueThis = entry.getValue();
                Object valueOther = ((JSONObject)other).get(name);
                if(valueThis == valueOther) {
                	continue;
                }
                if(valueThis == null) {
                	return false;
                }
                if (valueThis instanceof JSONObject) {
                    if (!((JSONObject)valueThis).similar(valueOther)) {
                        return false;
                    }
                } else if (valueThis instanceof JSONArray) {
                    if (!((JSONArray)valueThis).similar(valueOther)) {
                        return false;
                    }
                } else if (!valueThis.equals(valueOther)) {
                    return false;
                }
            }
            return true;
        } catch (Throwable exception) {
            return false;
        }
    }
    
    /**
     * Tests if the value should be tried as a decimal. It makes no test if there are actual digits.
     * 
     * @param val value to test
     * @return true if the string is "-0" or if it contains '.', 'e', or 'E', false otherwise.
     */
    protected static boolean isDecimalNotation(final String val) {
        return val.indexOf('.') > -1 || val.indexOf('e') > -1
                || val.indexOf('E') > -1 || "-0".equals(val);
    }
    
    /**
     * Converts a string to a number using the narrowest possible type. Possible 
     * returns for this function are BigDecimal, Double, BigInteger, Long, and Integer.
     * When a Double is returned, it should always be a valid Double and not NaN or +-infinity.
     * 
     * @param val value to convert
     * @return Number representation of the value.
     * @throws NumberFormatException thrown if the value is not a valid number. A public
     *      caller should catch this and wrap it in a {@link JSONException} if applicable.
     */
    protected static Number stringToNumber(final String val) throws NumberFormatException {
        char initial = val.charAt(0);
        if ((initial >= '0' && initial <= '9') || initial == '-') {
            // decimal representation
            if (isDecimalNotation(val)) {
                // quick dirty way to see if we need a BigDecimal instead of a Double
                // this only handles some cases of overflow or underflow
                if (val.length()>14) {
                    return new BigDecimal(val);
                }
                final Double d = Double.valueOf(val);
                if (d.isInfinite() || d.isNaN()) {
                    // if we can't parse it as a double, go up to BigDecimal
                    // this is probably due to underflow like 4.32e-678
                    // or overflow like 4.65e5324. The size of the string is small
                    // but can't be held in a Double.
                    return new BigDecimal(val);
                }
                return d;
            }
            // integer representation.
            // This will narrow any values to the smallest reasonable Object representation
            // (Integer, Long, or BigInteger)
            
            // string version
            // The compare string length method reduces GC,
            // but leads to smaller integers being placed in larger wrappers even though not
            // needed. i.e. 1,000,000,000 -> Long even though it's an Integer
            // 1,000,000,000,000,000,000 -> BigInteger even though it's a Long
            //if(val.length()<=9){
            //    return Integer.valueOf(val);
            //}
            //if(val.length()<=18){
            //    return Long.valueOf(val);
            //}
            //return new BigInteger(val);
            
            // BigInteger version: We use a similar bitLenth compare as
            // BigInteger#intValueExact uses. Increases GC, but objects hold
            // only what they need. i.e. Less runtime overhead if the value is
            // long lived. Which is the better tradeoff? This is closer to what's
            // in stringToValue.
            BigInteger bi = new BigInteger(val);
            if(bi.bitLength()<=31){
                return Integer.valueOf(bi.intValue());
            }
            if(bi.bitLength()<=63){
                return Long.valueOf(bi.longValue());
            }
            return bi;
        }
        throw new NumberFormatException("val ["+val+"] is not a valid number.");
    }

    /**
     * Try to convert a string into a number, boolean, or null. If the string
     * can't be converted, return the string.
     *
     * @param string
     *            A String.
     * @return A simple JSON value.
     */
    // Changes to this method must be copied to the corresponding method in
    // the XML class to keep full support for Android
    public static Object stringToValue(String string) {
        if (string.equals("")) {
            return string;
        }
        if (string.equalsIgnoreCase("true")) {
            return Boolean.TRUE;
        }
        if (string.equalsIgnoreCase("false")) {
            return Boolean.FALSE;
        }
        if (string.equalsIgnoreCase("null")) {
            return JSONObject.NULL;
        }

        /*
         * If it might be a number, try converting it. If a number cannot be
         * produced, then the value will just be a string.
         */

        char initial = string.charAt(0);
        if ((initial >= '0' && initial <= '9') || initial == '-') {
            try {
                // if we want full Big Number support this block can be replaced with:
                // return stringToNumber(string);
                if (isDecimalNotation(string)) {
                    Double d = Double.valueOf(string);
                    if (!d.isInfinite() && !d.isNaN()) {
                        return d;
                    }
                } else {
                    Long myLong = Long.valueOf(string);
                    if (string.equals(myLong.toString())) {
                        if (myLong.longValue() == myLong.intValue()) {
                            return Integer.valueOf(myLong.intValue());
                        }
                        return myLong;
                    }
                }
            } catch (Exception ignore) {
            }
        }
        return string;
    }

    /**
     * Throw an exception if the object is a NaN or infinite number.
     *
     * @param o
     *            The object to test.
     * @throws JSONException
     *             If o is a non-finite number.
     */
    public static void testValidity(Object o) throws JSONException {
        if (o != null) {
            if (o instanceof Double) {
                if (((Double) o).isInfinite() || ((Double) o).isNaN()) {
                    throw new JSONException(
                            "JSON does not allow non-finite numbers.");
                }
            } else if (o instanceof Float) {
                if (((Float) o).isInfinite() || ((Float) o).isNaN()) {
                    throw new JSONException(
                            "JSON does not allow non-finite numbers.");
                }
            }
        }
    }

    /**
     * Produce a JSONArray containing the values of the members of this
     * JSONObject.
     *
     * @param names
     *            A JSONArray containing a list of key strings. This determines
     *            the sequence of the values in the result.
     * @return A JSONArray of values.
     * @throws JSONException
     *             If any of the values are non-finite numbers.
     */
    public JSONArray toJSONArray(JSONArray names) throws JSONException {
        if (names == null || names.length() == 0) {
            return null;
        }
        JSONArray ja = new JSONArray();
        for (int i = 0; i < names.length(); i += 1) {
            ja.put(this.opt(names.getString(i)));
        }
        return ja;
    }

    /**
     * Make a JSON text of this JSONObject. For compactness, no whitespace is
     * added. If this would not result in a syntactically correct JSON text,
     * then null will be returned instead.
     * <p><b>
     * Warning: This method assumes that the data structure is acyclical.
     * </b>
     * 
     * @return a printable, displayable, portable, transmittable representation
     *         of the object, beginning with <code>{</code>&nbsp;<small>(left
     *         brace)</small> and ending with <code>}</code>&nbsp;<small>(right
     *         brace)</small>.
     */
    @Override
    public String toString() {
        try {
            return this.toString(0);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * Make a pretty-printed JSON text of this JSONObject.
     * 
     * <p>If <code>indentFactor > 0</code> and the {@link JSONObject}
     * has only one key, then the object will be output on a single line:
     * <pre>{@code {"key": 1}}</pre>
     * 
     * <p>If an object has 2 or more keys, then it will be output across
     * multiple lines: <code><pre>{
     *  "key1": 1,
     *  "key2": "value 2",
     *  "key3": 3
     * }</pre></code>
     * <p><b>
     * Warning: This method assumes that the data structure is acyclical.
     * </b>
     *
     * @param indentFactor
     *            The number of spaces to add to each level of indentation.
     * @return a printable, displayable, portable, transmittable representation
     *         of the object, beginning with <code>{</code>&nbsp;<small>(left
     *         brace)</small> and ending with <code>}</code>&nbsp;<small>(right
     *         brace)</small>.
     * @throws JSONException
     *             If the object contains an invalid number.
     */
    public String toString(int indentFactor) throws JSONException {
        StringWriter w = new StringWriter();
        synchronized (w.getBuffer()) {
            return this.write(w, indentFactor, 0).toString();
        }
    }

    /**
     * Make a JSON text of an Object value. If the object has an
     * value.toJSONString() method, then that method will be used to produce the
     * JSON text. The method is required to produce a strictly conforming text.
     * If the object does not contain a toJSONString method (which is the most
     * common case), then a text will be produced by other means. If the value
     * is an array or Collection, then a JSONArray will be made from it and its
     * toJSONString method will be called. If the value is a MAP, then a
     * JSONObject will be made from it and its toJSONString method will be
     * called. Otherwise, the value's toString method will be called, and the
     * result will be quoted.
     *
     * <p>
     * Warning: This method assumes that the data structure is acyclical.
     *
     * @param value
     *            The value to be serialized.
     * @return a printable, displayable, transmittable representation of the
     *         object, beginning with <code>{</code>&nbsp;<small>(left
     *         brace)</small> and ending with <code>}</code>&nbsp;<small>(right
     *         brace)</small>.
     * @throws JSONException
     *             If the value is or contains an invalid number.
     */
    public static String valueToString(Object value) throws JSONException {
    	// moves the implementation to JSONWriter as:
    	// 1. It makes more sense to be part of the writer class
    	// 2. For Android support this method is not available. By implementing it in the Writer
    	//    Android users can use the writer with the built in Android JSONObject implementation.
        return JSONWriter.valueToString(value);
    }

    /**
     * Wrap an object, if necessary. If the object is <code>null</code>, return the NULL
     * object. If it is an array or collection, wrap it in a JSONArray. If it is
     * a map, wrap it in a JSONObject. If it is a standard property (Double,
     * String, et al) then it is already wrapped. Otherwise, if it comes from
     * one of the java packages, turn it into a string. And if it doesn't, try
     * to wrap it in a JSONObject. If the wrapping fails, then null is returned.
     *
     * @param object
     *            The object to wrap
     * @return The wrapped value
     */
    public static Object wrap(Object object) {
        try {
            if (object == null) {
                return NULL;
            }
            if (object instanceof JSONObject || object instanceof JSONArray
                    || NULL.equals(object) || object instanceof JSONString
                    || object instanceof Byte || object instanceof Character
                    || object instanceof Short || object instanceof Integer
                    || object instanceof Long || object instanceof Boolean
                    || object instanceof Float || object instanceof Double
                    || object instanceof String || object instanceof BigInteger
                    || object instanceof BigDecimal || object instanceof Enum) {
                return object;
            }

            if (object instanceof Collection) {
                Collection<?> coll = (Collection<?>) object;
                return new JSONArray(coll);
            }
            if (object.getClass().isArray()) {
                return new JSONArray(object);
            }
            if (object instanceof Map) {
                Map<?, ?> map = (Map<?, ?>) object;
                return new JSONObject(map);
            }
            Package objectPackage = object.getClass().getPackage();
            String objectPackageName = objectPackage != null ? objectPackage
                    .getName() : "";
            if (objectPackageName.startsWith("java.")
                    || objectPackageName.startsWith("javax.")
                    || object.getClass().getClassLoader() == null) {
                return object.toString();
            }
            return new JSONObject(object);
        } catch (Exception exception) {
            return null;
        }
    }

    /**
     * Write the contents of the JSONObject as JSON text to a writer. For
     * compactness, no whitespace is added.
     * <p><b>
     * Warning: This method assumes that the data structure is acyclical.
     * </b>
     * 
     * @return The writer.
     * @throws JSONException
     */
    public Writer write(Writer writer) throws JSONException {
        return this.write(writer, 0, 0);
    }

    static final Writer writeValue(Writer writer, Object value,
            int indentFactor, int indent) throws JSONException, IOException {
        if (value == null || value.equals(null)) {
            writer.write("null");
        } else if (value instanceof JSONString) {
            Object o;
            try {
                o = ((JSONString) value).toJSONString();
            } catch (Exception e) {
                throw new JSONException(e);
            }
            writer.write(o != null ? o.toString() : quote(value.toString()));
        } else if (value instanceof Number) {
            // not all Numbers may match actual JSON Numbers. i.e. fractions or Imaginary
            final String numberAsString = numberToString((Number) value);
            try {
                // Use the BigDecimal constructor for its parser to validate the format.
                @SuppressWarnings("unused")
                BigDecimal testNum = new BigDecimal(numberAsString);
                // Close enough to a JSON number that we will use it unquoted
                writer.write(numberAsString);
            } catch (NumberFormatException ex){
                // The Number value is not a valid JSON number.
                // Instead we will quote it as a string
                quote(numberAsString, writer);
            }
        } else if (value instanceof Boolean) {
            writer.write(value.toString());
        } else if (value instanceof Enum<?>) {
            writer.write(quote(((Enum<?>)value).name()));
        } else if (value instanceof JSONObject) {
            ((JSONObject) value).write(writer, indentFactor, indent);
        } else if (value instanceof JSONArray) {
            ((JSONArray) value).write(writer, indentFactor, indent);
        } else if (value instanceof Map) {
            Map<?, ?> map = (Map<?, ?>) value;
            new JSONObject(map).write(writer, indentFactor, indent);
        } else if (value instanceof Collection) {
            Collection<?> coll = (Collection<?>) value;
            new JSONArray(coll).write(writer, indentFactor, indent);
        } else if (value.getClass().isArray()) {
            new JSONArray(value).write(writer, indentFactor, indent);
        } else {
            quote(value.toString(), writer);
        }
        return writer;
    }

    static final void indent(Writer writer, int indent) throws IOException {
        for (int i = 0; i < indent; i += 1) {
            writer.write(' ');
        }
    }

    /**
     * Write the contents of the JSONObject as JSON text to a writer.
     * 
     * <p>If <code>indentFactor > 0</code> and the {@link JSONObject}
     * has only one key, then the object will be output on a single line:
     * <pre>{@code {"key": 1}}</pre>
     * 
     * <p>If an object has 2 or more keys, then it will be output across
     * multiple lines: <code><pre>{
     *  "key1": 1,
     *  "key2": "value 2",
     *  "key3": 3
     * }</pre></code>
     * <p><b>
     * Warning: This method assumes that the data structure is acyclical.
     * </b>
     *
     * @param writer
     *            Writes the serialized JSON
     * @param indentFactor
     *            The number of spaces to add to each level of indentation.
     * @param indent
     *            The indentation of the top level.
     * @return The writer.
     * @throws JSONException
     */
    public Writer write(Writer writer, int indentFactor, int indent)
            throws JSONException {
        try {
            boolean commanate = false;
            final int length = this.length();
            writer.write('{');

            if (length == 1) {
            	final Entry<String,?> entry = this.entrySet().iterator().next();
                final String key = entry.getKey();
                writer.write(quote(key));
                writer.write(':');
                if (indentFactor > 0) {
                    writer.write(' ');
                }
                try{
                    writeValue(writer, entry.getValue(), indentFactor, indent);
                } catch (Exception e) {
                    throw new JSONException("Unable to write JSONObject value for key: " + key, e);
                }
            } else if (length != 0) {
                final int newindent = indent + indentFactor;
                for (final Entry<String,?> entry : this.entrySet()) {
                    if (commanate) {
                        writer.write(',');
                    }
                    if (indentFactor > 0) {
                        writer.write('\n');
                    }
                    indent(writer, newindent);
                    final String key = entry.getKey();
                    writer.write(quote(key));
                    writer.write(':');
                    if (indentFactor > 0) {
                        writer.write(' ');
                    }
                    try {
                        writeValue(writer, entry.getValue(), indentFactor, newindent);
                    } catch (Exception e) {
                        throw new JSONException("Unable to write JSONObject value for key: " + key, e);
                    }
                    commanate = true;
                }
                if (indentFactor > 0) {
                    writer.write('\n');
                }
                indent(writer, indent);
            }
            writer.write('}');
            return writer;
        } catch (IOException exception) {
            throw new JSONException(exception);
        }
    }

    /**
     * Returns a java.util.Map containing all of the entries in this object.
     * If an entry in the object is a JSONArray or JSONObject it will also
     * be converted.
     * <p>
     * Warning: This method assumes that the data structure is acyclical.
     *
     * @return a java.util.Map containing the entries of this object
     */
    public Map<String, Object> toMap() {
        Map<String, Object> results = new HashMap<String, Object>();
        for (Entry<String, Object> entry : this.entrySet()) {
            Object value;
            if (entry.getValue() == null || NULL.equals(entry.getValue())) {
                value = null;
            } else if (entry.getValue() instanceof JSONObject) {
                value = ((JSONObject) entry.getValue()).toMap();
            } else if (entry.getValue() instanceof JSONArray) {
                value = ((JSONArray) entry.getValue()).toList();
            } else {
                value = entry.getValue();
            }
            results.put(entry.getKey(), value);
        }
        return results;
    }
}
import javafx.application.HostServices;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.image.Image;
import javafx.scene.image.PixelReader;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import kml.auth.Authentication;
import kml.game.GameLauncher;
import kml.game.download.Downloader;
import kml.game.profile.Profiles;
import kml.game.version.Versions;
import kml.gui.BrowserFX;
import kml.gui.MainFX;
import kml.gui.lang.Language;
import kml.utils.Utils;
import org.json.JSONException;
import org.json.JSONObject;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
package kml;




/**
 * @author DarkLBP
 * website https://krothium.com
 */

public final class Kernel {
    private final Console console;
    private final Profiles profiles;