--- a/net/minecraft/server/Main.java
+++ b/net/minecraft/server/Main.java
@@ -16,6 +16,8 @@
 import java.util.Optional;
 import java.util.UUID;
 import java.util.function.BooleanSupplier;
+import io.papermc.paper.world.ThreadedWorldUpgrader;
+import joptsimple.NonOptionArgumentSpec;
 import joptsimple.OptionParser;
 import joptsimple.OptionSet;
 import joptsimple.OptionSpec;
@@ -38,6 +40,7 @@
 import net.minecraft.server.packs.repository.FolderRepositorySource;
 import net.minecraft.server.packs.repository.PackRepository;
 import net.minecraft.server.packs.repository.PackSource;
+import net.minecraft.server.packs.repository.RepositorySource;
 import net.minecraft.server.packs.repository.ServerPacksSource;
 import net.minecraft.util.Mth;
 import net.minecraft.util.datafix.DataFixers;
@@ -46,48 +49,62 @@
 import net.minecraft.util.worldupdate.WorldUpgrader;
 import net.minecraft.world.level.DataPackConfig;
 import net.minecraft.world.level.GameRules;
-import net.minecraft.world.level.LevelSettings;
+import net.minecraft.world.level.dimension.LevelStem;
 import net.minecraft.world.level.levelgen.WorldGenSettings;
 import net.minecraft.world.level.levelgen.presets.WorldPresets;
 import net.minecraft.world.level.storage.LevelResource;
 import net.minecraft.world.level.storage.LevelStorageSource;
 import net.minecraft.world.level.storage.LevelSummary;
-import net.minecraft.world.level.storage.PrimaryLevelData;
-import net.minecraft.world.level.storage.WorldData;
 import org.slf4j.Logger;
 
+// CraftBukkit start
+import com.google.common.base.Charsets;
+import java.io.InputStreamReader;
+import java.util.concurrent.atomic.AtomicReference;
+import net.minecraft.SharedConstants;
+import org.bukkit.configuration.file.YamlConfiguration;
+// CraftBukkit end
+
 public class Main {
+
     private static final Logger LOGGER = LogUtils.getLogger();
 
+    public Main() {}
+
     @DontObfuscate
-    public static void main(String[] args) {
+    public static void main(final OptionSet optionset) { // CraftBukkit - replaces main(String[] astring)
         SharedConstants.tryDetectVersion();
-        OptionParser optionParser = new OptionParser();
-        OptionSpec<Void> optionSpec = optionParser.accepts("nogui");
-        OptionSpec<Void> optionSpec2 = optionParser.accepts("initSettings", "Initializes 'server.properties' and 'eula.txt', then quits");
-        OptionSpec<Void> optionSpec3 = optionParser.accepts("demo");
-        OptionSpec<Void> optionSpec4 = optionParser.accepts("bonusChest");
-        OptionSpec<Void> optionSpec5 = optionParser.accepts("forceUpgrade");
-        OptionSpec<Void> optionSpec6 = optionParser.accepts("eraseCache");
-        OptionSpec<Void> optionSpec7 = optionParser.accepts("safeMode", "Loads level with vanilla datapack only");
-        OptionSpec<Void> optionSpec8 = optionParser.accepts("help").forHelp();
-        OptionSpec<String> optionSpec9 = optionParser.accepts("singleplayer").withRequiredArg();
-        OptionSpec<String> optionSpec10 = optionParser.accepts("universe").withRequiredArg().defaultsTo(".");
-        OptionSpec<String> optionSpec11 = optionParser.accepts("world").withRequiredArg();
-        OptionSpec<Integer> optionSpec12 = optionParser.accepts("port").withRequiredArg().ofType(Integer.class).defaultsTo(-1);
-        OptionSpec<String> optionSpec13 = optionParser.accepts("serverId").withRequiredArg();
-        OptionSpec<Void> optionSpec14 = optionParser.accepts("jfrProfile");
-        OptionSpec<String> optionSpec15 = optionParser.nonOptions();
+        /* CraftBukkit start - Replace everything
+        OptionParser optionparser = new OptionParser();
+        OptionSpec<Void> optionspec = optionparser.accepts("nogui");
+        OptionSpec<Void> optionspec1 = optionparser.accepts("initSettings", "Initializes 'server.properties' and 'eula.txt', then quits");
+        OptionSpec<Void> optionspec2 = optionparser.accepts("demo");
+        OptionSpec<Void> optionspec3 = optionparser.accepts("bonusChest");
+        OptionSpec<Void> optionspec4 = optionparser.accepts("forceUpgrade");
+        OptionSpec<Void> optionspec5 = optionparser.accepts("eraseCache");
+        OptionSpec<Void> optionspec6 = optionparser.accepts("safeMode", "Loads level with vanilla datapack only");
+        OptionSpec<Void> optionspec7 = optionparser.accepts("help").forHelp();
+        OptionSpec<String> optionspec8 = optionparser.accepts("singleplayer").withRequiredArg();
+        OptionSpec<String> optionspec9 = optionparser.accepts("universe").withRequiredArg().defaultsTo(".", new String[0]);
+        OptionSpec<String> optionspec10 = optionparser.accepts("world").withRequiredArg();
+        OptionSpec<Integer> optionspec11 = optionparser.accepts("port").withRequiredArg().ofType(Integer.class).defaultsTo(-1, new Integer[0]);
+        OptionSpec<String> optionspec12 = optionparser.accepts("serverId").withRequiredArg();
+        OptionSpec<Void> optionspec13 = optionparser.accepts("jfrProfile");
+        NonOptionArgumentSpec nonoptionargumentspec = optionparser.nonOptions();
 
         try {
-            OptionSet optionSet = optionParser.parse(args);
-            if (optionSet.has(optionSpec8)) {
-                optionParser.printHelpOn(System.err);
+            OptionSet optionset = optionparser.parse(astring);
+
+            if (optionset.has(optionspec7)) {
+                optionparser.printHelpOn(System.err);
                 return;
             }
+            */ // CraftBukkit end
+
+        try {
 
             CrashReport.preload();
-            if (optionSet.has(optionSpec14)) {
+            if (optionset.has("jfrProfile")) { // CraftBukkit
                 JvmProfiler.INSTANCE.start(Environment.SERVER);
             }
 
@@ -95,140 +112,255 @@
             Bootstrap.validate();
             Util.startTimerHackThread();
             Path path = Paths.get("server.properties");
-            DedicatedServerSettings dedicatedServerSettings = new DedicatedServerSettings(path);
-            dedicatedServerSettings.forceSave();
-            Path path2 = Paths.get("eula.txt");
-            Eula eula = new Eula(path2);
-            if (optionSet.has(optionSpec2)) {
-                LOGGER.info("Initialized '{}' and '{}'", path.toAbsolutePath(), path2.toAbsolutePath());
+            DedicatedServerSettings dedicatedserversettings = new DedicatedServerSettings(optionset); // CraftBukkit - CLI argument support
+
+            dedicatedserversettings.forceSave();
+            // Paper start - load config files for access below if needed
+            org.bukkit.configuration.file.YamlConfiguration bukkitConfiguration = io.papermc.paper.configuration.PaperConfigurations.loadLegacyConfigFile((File) optionset.valueOf("bukkit-settings"));
+            org.bukkit.configuration.file.YamlConfiguration spigotConfiguration = io.papermc.paper.configuration.PaperConfigurations.loadLegacyConfigFile((File) optionset.valueOf("spigot-settings"));
+            // Paper end
+
+            Path path1 = Paths.get("eula.txt");
+            Eula eula = new Eula(path1);
+
+            if (optionset.has("initSettings")) { // CraftBukkit
+                // CraftBukkit start - SPIGOT-5761: Create bukkit.yml and commands.yml if not present
+                File configFile = (File) optionset.valueOf("bukkit-settings");
+                YamlConfiguration configuration = YamlConfiguration.loadConfiguration(configFile);
+                configuration.options().copyDefaults(true);
+                configuration.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(Main.class.getClassLoader().getResourceAsStream("configurations/bukkit.yml"), Charsets.UTF_8)));
+                configuration.save(configFile);
+
+                File commandFile = (File) optionset.valueOf("commands-settings");
+                YamlConfiguration commandsConfiguration = YamlConfiguration.loadConfiguration(commandFile);
+                commandsConfiguration.options().copyDefaults(true);
+                commandsConfiguration.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(Main.class.getClassLoader().getResourceAsStream("configurations/commands.yml"), Charsets.UTF_8)));
+                commandsConfiguration.save(commandFile);
+                // CraftBukkit end
+                Main.LOGGER.info("Initialized '{}' and '{}'", path.toAbsolutePath(), path1.toAbsolutePath());
                 return;
             }
 
-            if (!eula.hasAgreedToEULA()) {
-                LOGGER.info("You need to agree to the EULA in order to run the server. Go to eula.txt for more info.");
+            // Spigot Start
+            boolean eulaAgreed = Boolean.getBoolean( "com.mojang.eula.agree" );
+            if ( eulaAgreed )
+            {
+                System.err.println( "You have used the Spigot command line EULA agreement flag." );
+                System.err.println( "By using this setting you are indicating your agreement to Mojang's EULA (https://account.mojang.com/documents/minecraft_eula)." );
+                System.err.println( "If you do not agree to the above EULA please stop your server and remove this flag immediately." );
+            }
+            // Spigot End
+            if (!eula.hasAgreedToEULA() && !eulaAgreed) { // Spigot
+                Main.LOGGER.info("You need to agree to the EULA in order to run the server. Go to eula.txt for more info.");
                 return;
             }
 
-            File file = new File(optionSet.valueOf(optionSpec10));
-            Services services = Services.create(new YggdrasilAuthenticationService(Proxy.NO_PROXY), file);
-            String string = Optional.ofNullable(optionSet.valueOf(optionSpec11)).orElse(dedicatedServerSettings.getProperties().levelName);
-            LevelStorageSource levelStorageSource = LevelStorageSource.createDefault(file.toPath());
-            LevelStorageSource.LevelStorageAccess levelStorageAccess = levelStorageSource.createAccess(string);
-            LevelSummary levelSummary = levelStorageAccess.getSummary();
-            if (levelSummary != null) {
-                if (levelSummary.requiresManualConversion()) {
-                    LOGGER.info("This world must be opened in an older version (like 1.6.4) to be safely converted");
+            // Paper start - Warn on headless
+            if (io.papermc.paper.util.ServerEnvironment.isMissingAWTDependency()) {
+                Main.LOGGER.error("You are using a headless JRE distribution.");
+                Main.LOGGER.error("This distribution is missing certain graphic libraries that the Minecraft server needs to function.");
+                Main.LOGGER.error("For instructions on how to install the non-headless JRE, see https://docs.papermc.io/misc/java-install");
+                return;
+            }
+            // Paper end
+
+            org.spigotmc.SpigotConfig.disabledAdvancements = spigotConfiguration.getStringList("advancements.disabled"); // Paper - fix SPIGOT-5885, must be set early in init
+            // Paper start - fix SPIGOT-5824
+            File file;
+            File userCacheFile = new File(Services.USERID_CACHE_FILE);
+            if (optionset.has("universe")) {
+                file = (File) optionset.valueOf("universe"); // CraftBukkit
+                userCacheFile = new File(file, Services.USERID_CACHE_FILE);
+            } else {
+                file = new File(bukkitConfiguration.getString("settings.world-container", "."));
+            }
+            // Paper end - fix SPIGOT-5824
+            Services services = Services.create(new com.destroystokyo.paper.profile.PaperAuthenticationService(Proxy.NO_PROXY), file, userCacheFile, optionset); // Paper
+            // CraftBukkit start
+            String s = (String) Optional.ofNullable((String) optionset.valueOf("world")).orElse(dedicatedserversettings.getProperties().levelName);
+            LevelStorageSource convertable = LevelStorageSource.createDefault(file.toPath());
+            LevelStorageSource.LevelStorageAccess convertable_conversionsession = convertable.createAccess(s, LevelStem.OVERWORLD);
+            LevelSummary worldinfo = convertable_conversionsession.getSummary();
+
+            if (worldinfo != null) {
+                if (worldinfo.requiresManualConversion()) {
+                    Main.LOGGER.info("This world must be opened in an older version (like 1.6.4) to be safely converted");
                     return;
                 }
 
-                if (!levelSummary.isCompatible()) {
-                    LOGGER.info("This world was created by an incompatible version.");
+                if (!worldinfo.isCompatible()) {
+                    Main.LOGGER.info("This world was created by an incompatible version.");
                     return;
                 }
             }
 
-            boolean bl = optionSet.has(optionSpec7);
-            if (bl) {
-                LOGGER.warn("Safe mode active, only vanilla datapack will be loaded");
+            boolean flag = optionset.has("safeMode");
+
+            if (flag) {
+                Main.LOGGER.warn("Safe mode active, only vanilla datapack will be loaded");
             }
 
-            PackRepository packRepository = new PackRepository(PackType.SERVER_DATA, new ServerPacksSource(), new FolderRepositorySource(levelStorageAccess.getLevelPath(LevelResource.DATAPACK_DIR).toFile(), PackSource.WORLD));
+            PackRepository resourcepackrepository = new PackRepository(PackType.SERVER_DATA, new RepositorySource[]{new ServerPacksSource(), new FolderRepositorySource(convertable_conversionsession.getLevelPath(LevelResource.DATAPACK_DIR).toFile(), PackSource.WORLD)});
+            // CraftBukkit start
+            File bukkitDataPackFolder = new File(convertable_conversionsession.getLevelPath(LevelResource.DATAPACK_DIR).toFile(), "bukkit");
+            if (!bukkitDataPackFolder.exists()) {
+                bukkitDataPackFolder.mkdirs();
+            }
+            File mcMeta = new File(bukkitDataPackFolder, "pack.mcmeta");
+            try {
+                com.google.common.io.Files.write("{\n"
+                        + "    \"pack\": {\n"
+                        + "        \"description\": \"Data pack for resources provided by Bukkit plugins\",\n"
+                        + "        \"pack_format\": " + SharedConstants.getCurrentVersion().getPackVersion() + "\n"
+                        + "    }\n"
+                        + "}\n", mcMeta, com.google.common.base.Charsets.UTF_8);
+            } catch (java.io.IOException ex) {
+                throw new RuntimeException("Could not initialize Bukkit datapack", ex);
+            }
+            AtomicReference<DataPackConfig> config = new AtomicReference<>();
+            AtomicReference<DynamicOps<Tag>> ops = new AtomicReference<>();
+            // CraftBukkit end
+
+            WorldStem worldstem;
 
-            WorldStem worldStem;
             try {
-                DataPackConfig dataPackConfig = Objects.requireNonNullElse(levelStorageAccess.getDataPacks(), DataPackConfig.DEFAULT);
-                WorldLoader.PackConfig packConfig = new WorldLoader.PackConfig(packRepository, dataPackConfig, bl);
-                WorldLoader.InitConfig initConfig = new WorldLoader.InitConfig(packConfig, Commands.CommandSelection.DEDICATED, dedicatedServerSettings.getProperties().functionPermissionLevel);
-                worldStem = Util.blockUntilDone((applyExecutor) -> {
-                    return WorldStem.load(initConfig, (resourceManager, dataPackSettings) -> {
-                        RegistryAccess.Writable writable = RegistryAccess.builtinCopy();
-                        DynamicOps<Tag> dynamicOps = RegistryOps.createAndLoad(NbtOps.INSTANCE, writable, resourceManager);
-                        WorldData worldData = levelStorageAccess.getDataTag(dynamicOps, dataPackSettings, writable.allElementsLifecycle());
-                        if (worldData != null) {
-                            return Pair.of(worldData, writable.freeze());
+                DataPackConfig datapackconfiguration = (DataPackConfig) Objects.requireNonNullElse(convertable_conversionsession.getDataPacks(), DataPackConfig.DEFAULT);
+                WorldLoader.PackConfig worldloader_b = new WorldLoader.PackConfig(resourcepackrepository, datapackconfiguration, flag);
+                WorldLoader.InitConfig worldloader_a = new WorldLoader.InitConfig(worldloader_b, Commands.CommandSelection.DEDICATED, dedicatedserversettings.getProperties().functionPermissionLevel);
+
+                worldstem = (WorldStem) Util.blockUntilDone((executor) -> {
+                    return WorldStem.load(worldloader_a, (iresourcemanager, datapackconfiguration1) -> {
+                        RegistryAccess.Writable iregistrycustom_e = RegistryAccess.builtinCopy();
+                        DynamicOps<Tag> dynamicops = RegistryOps.createAndLoad(NbtOps.INSTANCE, iregistrycustom_e, iresourcemanager);
+                        // CraftBukkit start
+                        config.set(datapackconfiguration1);
+                        ops.set(dynamicops);
+                        return Pair.of(null, iregistrycustom_e.freeze());
+                        // CraftBukkit end
+                        /*
+                        SaveData savedata = convertable_conversionsession.getDataTag(dynamicops, datapackconfiguration1, iregistrycustom_e.allElementsLifecycle());
+
+                        if (savedata != null) {
+                            return Pair.of(savedata, iregistrycustom_e.freeze());
                         } else {
-                            LevelSettings levelSettings;
-                            WorldGenSettings worldGenSettings;
-                            if (optionSet.has(optionSpec3)) {
-                                levelSettings = MinecraftServer.DEMO_SETTINGS;
-                                worldGenSettings = WorldPresets.demoSettings(writable);
+                            WorldSettings worldsettings;
+                            GeneratorSettings generatorsettings;
+
+                            if (optionset.has(optionspec2)) {
+                                worldsettings = MinecraftServer.DEMO_SETTINGS;
+                                generatorsettings = WorldPresets.demoSettings(iregistrycustom_e);
                             } else {
-                                DedicatedServerProperties dedicatedServerProperties = dedicatedServerSettings.getProperties();
-                                levelSettings = new LevelSettings(dedicatedServerProperties.levelName, dedicatedServerProperties.gamemode, dedicatedServerProperties.hardcore, dedicatedServerProperties.difficulty, false, new GameRules(), dataPackSettings);
-                                worldGenSettings = optionSet.has(optionSpec4) ? dedicatedServerProperties.getWorldGenSettings(writable).withBonusChest() : dedicatedServerProperties.getWorldGenSettings(writable);
+                                DedicatedServerProperties dedicatedserverproperties = dedicatedserversettings.getProperties();
+
+                                worldsettings = new WorldSettings(dedicatedserverproperties.levelName, dedicatedserverproperties.gamemode, dedicatedserverproperties.hardcore, dedicatedserverproperties.difficulty, false, new GameRules(), datapackconfiguration1);
+                                generatorsettings = optionset.has(optionspec3) ? dedicatedserverproperties.getWorldGenSettings(iregistrycustom_e).withBonusChest() : dedicatedserverproperties.getWorldGenSettings(iregistrycustom_e);
                             }
 
-                            PrimaryLevelData primaryLevelData = new PrimaryLevelData(levelSettings, worldGenSettings, Lifecycle.stable());
-                            return Pair.of(primaryLevelData, writable.freeze());
+                            WorldDataServer worlddataserver = new WorldDataServer(worldsettings, generatorsettings, Lifecycle.stable());
+
+                            return Pair.of(worlddataserver, iregistrycustom_e.freeze());
                         }
-                    }, Util.backgroundExecutor(), applyExecutor);
+                         */
+                    }, Util.backgroundExecutor(), executor);
                 }).get();
-            } catch (Exception var35) {
-                LOGGER.warn("Failed to load datapacks, can't proceed with server load. You can either fix your datapacks or reset to vanilla with --safeMode", (Throwable)var35);
+            } catch (Exception exception) {
+                Main.LOGGER.warn("Failed to load datapacks, can't proceed with server load. You can either fix your datapacks or reset to vanilla with --safeMode", exception);
                 return;
             }
 
-            RegistryAccess.Frozen frozen = worldStem.registryAccess();
-            dedicatedServerSettings.getProperties().getWorldGenSettings(frozen);
-            WorldData worldData = worldStem.worldData();
-            if (optionSet.has(optionSpec5)) {
-                forceUpgrade(levelStorageAccess, DataFixers.getDataFixer(), optionSet.has(optionSpec6), () -> {
+            /*
+            IRegistryCustom.Dimension iregistrycustom_dimension = worldstem.registryAccess();
+
+            dedicatedserversettings.getProperties().getWorldGenSettings(iregistrycustom_dimension);
+            SaveData savedata = worldstem.worldData();
+
+            if (optionset.has(optionspec4)) {
+                forceUpgrade(convertable_conversionsession, DataConverterRegistry.getDataFixer(), optionset.has(optionspec5), () -> {
                     return true;
-                }, worldData.worldGenSettings());
+                }, savedata.worldGenSettings());
             }
 
-            levelStorageAccess.saveDataTag(frozen, worldData);
-            final DedicatedServer dedicatedServer = MinecraftServer.spin((threadx) -> {
-                DedicatedServer dedicatedServer = new DedicatedServer(threadx, levelStorageAccess, packRepository, worldStem, dedicatedServerSettings, DataFixers.getDataFixer(), services, LoggerChunkProgressListener::new);
-                dedicatedServer.setSingleplayerProfile(optionSet.has(optionSpec9) ? new GameProfile((UUID)null, optionSet.valueOf(optionSpec9)) : null);
-                dedicatedServer.setPort(optionSet.valueOf(optionSpec12));
-                dedicatedServer.setDemo(optionSet.has(optionSpec3));
-                dedicatedServer.setId(optionSet.valueOf(optionSpec13));
-                boolean bl = !optionSet.has(optionSpec) && !optionSet.valuesOf(optionSpec15).contains("nogui");
-                if (bl && !GraphicsEnvironment.isHeadless()) {
-                    dedicatedServer.showGui();
+            convertable_conversionsession.saveDataTag(iregistrycustom_dimension, savedata);
+            */
+            Class.forName(net.minecraft.world.entity.npc.VillagerTrades.class.getName());// Paper - load this sync so it won't fail later async
+            final DedicatedServer dedicatedserver = (DedicatedServer) MinecraftServer.spin((thread) -> {
+                DedicatedServer dedicatedserver1 = new DedicatedServer(optionset, config.get(), ops.get(), thread, convertable_conversionsession, resourcepackrepository, worldstem, dedicatedserversettings, DataFixers.getDataFixer(), services, LoggerChunkProgressListener::new);
+
+                /*
+                dedicatedserver1.setSingleplayerProfile(optionset.has(optionspec8) ? new GameProfile((UUID) null, (String) optionset.valueOf(optionspec8)) : null);
+                dedicatedserver1.setPort((Integer) optionset.valueOf(optionspec11));
+                dedicatedserver1.setDemo(optionset.has(optionspec2));
+                dedicatedserver1.setId((String) optionset.valueOf(optionspec12));
+                */
+                boolean flag1 = !optionset.has("nogui") && !optionset.nonOptionArguments().contains("nogui");
+
+                if(!Boolean.parseBoolean(System.getenv().getOrDefault("PAPER_DISABLE_SERVER_GUI", String.valueOf(false)))) // Paper
+                if (flag1 && !GraphicsEnvironment.isHeadless()) {
+                    dedicatedserver1.showGui();
                 }
 
-                return dedicatedServer;
+                if (optionset.has("port")) {
+                    int port = (Integer) optionset.valueOf("port");
+                    if (port > 0) {
+                        dedicatedserver1.setPort(port);
+                    }
+                }
+
+                return dedicatedserver1;
             });
+            /* CraftBukkit start
             Thread thread = new Thread("Server Shutdown Thread") {
-                @Override
                 public void run() {
-                    dedicatedServer.halt(true);
+                    dedicatedserver.halt(true);
                 }
             };
-            thread.setUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler(LOGGER));
+
+            thread.setUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler(Main.LOGGER));
             Runtime.getRuntime().addShutdownHook(thread);
-        } catch (Exception var36) {
-            LOGGER.error(LogUtils.FATAL_MARKER, "Failed to start the minecraft server", (Throwable)var36);
+            */ // CraftBukkit end
+        } catch (Exception exception1) {
+            Main.LOGGER.error(LogUtils.FATAL_MARKER, "Failed to start the minecraft server", exception1);
         }
 
     }
 
+    // Paper start - fix and optimise world upgrading
+    public static void convertWorldButItWorks(net.minecraft.resources.ResourceKey<net.minecraft.world.level.dimension.LevelStem> dimensionType, net.minecraft.world.level.storage.LevelStorageSource.LevelStorageAccess worldSession,
+                                              DataFixer dataFixer, Optional<net.minecraft.resources.ResourceKey<com.mojang.serialization.Codec<? extends net.minecraft.world.level.chunk.ChunkGenerator>>> generatorKey, boolean removeCaches) {
+        int threads = Runtime.getRuntime().availableProcessors() * 3 / 8;
+        final ThreadedWorldUpgrader worldUpgrader = new ThreadedWorldUpgrader(dimensionType, worldSession.getLevelId(), worldSession.levelDirectory.path().toFile(), threads, dataFixer, generatorKey, removeCaches);
+        worldUpgrader.convert();
+    }
+    // Paper end - fix and optimise world upgrading
+
     public static void forceUpgrade(LevelStorageSource.LevelStorageAccess session, DataFixer dataFixer, boolean eraseCache, BooleanSupplier continueCheck, WorldGenSettings generatorOptions) {
-        LOGGER.info("Forcing world upgrade!");
-        WorldUpgrader worldUpgrader = new WorldUpgrader(session, dataFixer, generatorOptions, eraseCache);
-        Component component = null;
+        Main.LOGGER.info("Forcing world upgrade! {}", session.getLevelId()); // CraftBukkit
+        WorldUpgrader worldupgrader = new WorldUpgrader(session, dataFixer, generatorOptions, eraseCache);
+        Component ichatbasecomponent = null;
 
-        while(!worldUpgrader.isFinished()) {
-            Component component2 = worldUpgrader.getStatus();
-            if (component != component2) {
-                component = component2;
-                LOGGER.info(worldUpgrader.getStatus().getString());
+        while (!worldupgrader.isFinished()) {
+            Component ichatbasecomponent1 = worldupgrader.getStatus();
+
+            if (ichatbasecomponent != ichatbasecomponent1) {
+                ichatbasecomponent = ichatbasecomponent1;
+                Main.LOGGER.info(worldupgrader.getStatus().getString());
             }
 
-            int i = worldUpgrader.getTotalChunks();
+            int i = worldupgrader.getTotalChunks();
+
             if (i > 0) {
-                int j = worldUpgrader.getConverted() + worldUpgrader.getSkipped();
-                LOGGER.info("{}% completed ({} / {} chunks)...", Mth.floor((float)j / (float)i * 100.0F), j, i);
+                int j = worldupgrader.getConverted() + worldupgrader.getSkipped();
+
+                Main.LOGGER.info("{}% completed ({} / {} chunks)...", new Object[]{Mth.floor((float) j / (float) i * 100.0F), j, i});
             }
 
             if (!continueCheck.getAsBoolean()) {
-                worldUpgrader.cancel();
+                worldupgrader.cancel();
             } else {
                 try {
                     Thread.sleep(1000L);
-                } catch (InterruptedException var10) {
+                } catch (InterruptedException interruptedexception) {
+                    ;
                 }
             }
         }
