--- a/net/minecraft/server/MinecraftServer.java
+++ b/net/minecraft/server/MinecraftServer.java
@@ -176,13 +176,38 @@
 import net.minecraft.world.phys.Vec3D;
 import org.slf4j.Logger;
 
+// CraftBukkit start
+import com.mojang.serialization.Dynamic;
+import com.mojang.serialization.Lifecycle;
+import java.io.File;
+import java.util.Random;
+import jline.console.ConsoleReader;
+import joptsimple.OptionSet;
+import net.minecraft.nbt.NbtException;
+import net.minecraft.nbt.ReportedNbtException;
+import net.minecraft.server.dedicated.DedicatedServer;
+import net.minecraft.server.dedicated.DedicatedServerProperties;
+import net.minecraft.util.datafix.DataConverterRegistry;
+import net.minecraft.world.level.levelgen.WorldDimensions;
+import net.minecraft.world.level.levelgen.presets.WorldPresets;
+import net.minecraft.world.level.storage.LevelDataAndDimensions;
+import net.minecraft.world.level.storage.WorldDataServer;
+import net.minecraft.world.level.storage.WorldInfo;
+import net.minecraft.world.level.validation.ContentValidationException;
+import org.bukkit.Bukkit;
+import org.bukkit.craftbukkit.CraftRegistry;
+import org.bukkit.craftbukkit.CraftServer;
+import org.bukkit.craftbukkit.Main;
+import org.bukkit.event.server.ServerLoadEvent;
+// CraftBukkit end
+
 public abstract class MinecraftServer extends IAsyncTaskHandlerReentrant<TickTask> implements ServerInfo, ChunkIOErrorReporter, ICommandListener {
 
     public static final Logger LOGGER = LogUtils.getLogger();
     public static final String VANILLA_BRAND = "vanilla";
     private static final float AVERAGE_TICK_TIME_SMOOTHING = 0.8F;
     private static final int TICK_STATS_SPAN = 100;
-    private static final long OVERLOADED_THRESHOLD_NANOS = 20L * TimeRange.NANOSECONDS_PER_SECOND / 20L;
+    private static final long OVERLOADED_THRESHOLD_NANOS = 30L * TimeRange.NANOSECONDS_PER_SECOND / 20L; // CraftBukkit
     private static final int OVERLOADED_TICKS_THRESHOLD = 20;
     private static final long OVERLOADED_WARNING_INTERVAL_NANOS = 10L * TimeRange.NANOSECONDS_PER_SECOND;
     private static final int OVERLOADED_TICKS_WARNING_INTERVAL = 100;
@@ -273,6 +298,19 @@
     private final SuppressedExceptionCollector suppressedExceptions;
     private final DiscontinuousFrame tickFrame;
 
+    // CraftBukkit start
+    public final WorldLoader.a worldLoader;
+    public org.bukkit.craftbukkit.CraftServer server;
+    public OptionSet options;
+    public org.bukkit.command.ConsoleCommandSender console;
+    public ConsoleReader reader;
+    public static int currentTick = (int) (System.currentTimeMillis() / 50);
+    public java.util.Queue<Runnable> processQueue = new java.util.concurrent.ConcurrentLinkedQueue<Runnable>();
+    public int autosavePeriod;
+    public CommandDispatcher vanillaCommandDispatcher;
+    private boolean forceTicks;
+    // CraftBukkit end
+
     public static <S extends MinecraftServer> S spin(Function<Thread, S> function) {
         AtomicReference<S> atomicreference = new AtomicReference();
         Thread thread = new Thread(() -> {
@@ -293,7 +331,7 @@
         return s0;
     }
 
-    public MinecraftServer(Thread thread, Convertable.ConversionSession convertable_conversionsession, ResourcePackRepository resourcepackrepository, WorldStem worldstem, Proxy proxy, DataFixer datafixer, Services services, WorldLoadListenerFactory worldloadlistenerfactory) {
+    public MinecraftServer(OptionSet options, WorldLoader.a worldLoader, Thread thread, Convertable.ConversionSession convertable_conversionsession, ResourcePackRepository resourcepackrepository, WorldStem worldstem, Proxy proxy, DataFixer datafixer, Services services, WorldLoadListenerFactory worldloadlistenerfactory) {
         super("Server");
         this.metricsRecorder = InactiveMetricsRecorder.INSTANCE;
         this.onMetricsRecordingStopped = (methodprofilerresults) -> {
@@ -317,7 +355,7 @@
         this.suppressedExceptions = new SuppressedExceptionCollector();
         this.registries = worldstem.registries();
         this.worldData = worldstem.worldData();
-        if (!this.registries.compositeAccess().lookupOrThrow(Registries.LEVEL_STEM).containsKey(WorldDimension.OVERWORLD)) {
+        if (false && !this.registries.compositeAccess().lookupOrThrow(Registries.LEVEL_STEM).containsKey(WorldDimension.OVERWORLD)) { // CraftBukkit - initialised later
             throw new IllegalStateException("Missing Overworld dimension data");
         } else {
             this.proxy = proxy;
@@ -345,6 +383,33 @@
             this.fuelValues = FuelValues.vanillaBurnTimes(this.registries.compositeAccess(), this.worldData.enabledFeatures());
             this.tickFrame = TracyClient.createDiscontinuousFrame("Server Tick");
         }
+        // CraftBukkit start
+        this.options = options;
+        this.worldLoader = worldLoader;
+        this.vanillaCommandDispatcher = worldstem.dataPackResources().commands; // CraftBukkit
+        // Try to see if we're actually running in a terminal, disable jline if not
+        if (System.console() == null && System.getProperty("jline.terminal") == null) {
+            System.setProperty("jline.terminal", "jline.UnsupportedTerminal");
+            Main.useJline = false;
+        }
+
+        try {
+            reader = new ConsoleReader(System.in, System.out);
+            reader.setExpandEvents(false); // Avoid parsing exceptions for uncommonly used event designators
+        } catch (Throwable e) {
+            try {
+                // Try again with jline disabled for Windows users without C++ 2008 Redistributable
+                System.setProperty("jline.terminal", "jline.UnsupportedTerminal");
+                System.setProperty("user.language", "en");
+                Main.useJline = false;
+                reader = new ConsoleReader(System.in, System.out);
+                reader.setExpandEvents(false);
+            } catch (IOException ex) {
+                LOGGER.warn((String) null, ex);
+            }
+        }
+        Runtime.getRuntime().addShutdownHook(new org.bukkit.craftbukkit.util.ServerShutdownThread(this));
+        // CraftBukkit end
     }
 
     private void readScoreboard(WorldPersistentData worldpersistentdata) {
@@ -353,7 +418,7 @@
 
     protected abstract boolean initServer() throws IOException;
 
-    protected void loadLevel() {
+    protected void loadLevel(String s) { // CraftBukkit
         if (!JvmProfiler.INSTANCE.isRunning()) {
             ;
         }
@@ -361,12 +426,8 @@
         boolean flag = false;
         ProfiledDuration profiledduration = JvmProfiler.INSTANCE.onWorldLoadedStarted();
 
-        this.worldData.setModdedInfo(this.getServerModName(), this.getModdedStatus().shouldReportAsModified());
-        WorldLoadListener worldloadlistener = this.progressListenerFactory.create(this.worldData.getGameRules().getInt(GameRules.RULE_SPAWN_CHUNK_RADIUS));
+        loadWorld0(s); // CraftBukkit
 
-        this.createLevels(worldloadlistener);
-        this.forceDifficulty();
-        this.prepareLevels(worldloadlistener);
         if (profiledduration != null) {
             profiledduration.finish(true);
         }
@@ -383,23 +444,217 @@
 
     protected void forceDifficulty() {}
 
-    protected void createLevels(WorldLoadListener worldloadlistener) {
-        IWorldDataServer iworlddataserver = this.worldData.overworldData();
-        boolean flag = this.worldData.isDebugWorld();
-        IRegistry<WorldDimension> iregistry = this.registries.compositeAccess().lookupOrThrow(Registries.LEVEL_STEM);
-        WorldOptions worldoptions = this.worldData.worldGenOptions();
-        long i = worldoptions.seed();
-        long j = BiomeManager.obfuscateSeed(i);
-        List<MobSpawner> list = ImmutableList.of(new MobSpawnerPhantom(), new MobSpawnerPatrol(), new MobSpawnerCat(), new VillageSiege(), new MobSpawnerTrader(iworlddataserver));
-        WorldDimension worlddimension = (WorldDimension) iregistry.getValue(WorldDimension.OVERWORLD);
-        WorldServer worldserver = new WorldServer(this, this.executor, this.storageSource, iworlddataserver, World.OVERWORLD, worlddimension, worldloadlistener, flag, j, list, true, (RandomSequences) null);
+    // CraftBukkit start
+    private void loadWorld0(String s) {
+        Convertable.ConversionSession worldSession = this.storageSource;
 
-        this.levels.put(World.OVERWORLD, worldserver);
-        WorldPersistentData worldpersistentdata = worldserver.getDataStorage();
+        IRegistryCustom.Dimension iregistrycustom_dimension = this.registries.compositeAccess();
+        IRegistry<WorldDimension> dimensions = iregistrycustom_dimension.lookupOrThrow(Registries.LEVEL_STEM);
+        for (WorldDimension worldDimension : dimensions) {
+            ResourceKey<WorldDimension> dimensionKey = dimensions.getResourceKey(worldDimension).get();
 
-        this.readScoreboard(worldpersistentdata);
-        this.commandStorage = new PersistentCommandStorage(worldpersistentdata);
+            WorldServer world;
+            int dimension = 0;
+
+            if (dimensionKey == WorldDimension.NETHER) {
+                if (server.getAllowNether()) {
+                    dimension = -1;
+                } else {
+                    continue;
+                }
+            } else if (dimensionKey == WorldDimension.END) {
+                if (server.getAllowEnd()) {
+                    dimension = 1;
+                } else {
+                    continue;
+                }
+            } else if (dimensionKey != WorldDimension.OVERWORLD) {
+                dimension = -999;
+            }
+
+            String worldType = (dimension == -999) ? dimensionKey.location().getNamespace() + "_" + dimensionKey.location().getPath() : org.bukkit.World.Environment.getEnvironment(dimension).toString().toLowerCase(Locale.ROOT);
+            String name = (dimensionKey == WorldDimension.OVERWORLD) ? s : s + "_" + worldType;
+            if (dimension != 0) {
+                File newWorld = Convertable.getStorageFolder(new File(name).toPath(), dimensionKey).toFile();
+                File oldWorld = Convertable.getStorageFolder(new File(s).toPath(), dimensionKey).toFile();
+                File oldLevelDat = new File(new File(s), "level.dat"); // The data folders exist on first run as they are created in the PersistentCollection constructor above, but the level.dat won't
+
+                if (!newWorld.isDirectory() && oldWorld.isDirectory() && oldLevelDat.isFile()) {
+                    MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder required ----");
+                    MinecraftServer.LOGGER.info("Unfortunately due to the way that Minecraft implemented multiworld support in 1.6, Bukkit requires that you move your " + worldType + " folder to a new location in order to operate correctly.");
+                    MinecraftServer.LOGGER.info("We will move this folder for you, but it will mean that you need to move it back should you wish to stop using Bukkit in the future.");
+                    MinecraftServer.LOGGER.info("Attempting to move " + oldWorld + " to " + newWorld + "...");
+
+                    if (newWorld.exists()) {
+                        MinecraftServer.LOGGER.warn("A file or folder already exists at " + newWorld + "!");
+                        MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder failed ----");
+                    } else if (newWorld.getParentFile().mkdirs()) {
+                        if (oldWorld.renameTo(newWorld)) {
+                            MinecraftServer.LOGGER.info("Success! To restore " + worldType + " in the future, simply move " + newWorld + " to " + oldWorld);
+                            // Migrate world data too.
+                            try {
+                                com.google.common.io.Files.copy(oldLevelDat, new File(new File(name), "level.dat"));
+                                org.apache.commons.io.FileUtils.copyDirectory(new File(new File(s), "data"), new File(new File(name), "data"));
+                            } catch (IOException exception) {
+                                MinecraftServer.LOGGER.warn("Unable to migrate world data.");
+                            }
+                            MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder complete ----");
+                        } else {
+                            MinecraftServer.LOGGER.warn("Could not move folder " + oldWorld + " to " + newWorld + "!");
+                            MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder failed ----");
+                        }
+                    } else {
+                        MinecraftServer.LOGGER.warn("Could not create path for " + newWorld + "!");
+                        MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder failed ----");
+                    }
+                }
+
+                try {
+                    worldSession = Convertable.createDefault(server.getWorldContainer().toPath()).validateAndCreateAccess(name, dimensionKey);
+                } catch (IOException | ContentValidationException ex) {
+                    throw new RuntimeException(ex);
+                }
+            }
+
+            Dynamic<?> dynamic;
+            if (worldSession.hasWorldData()) {
+                WorldInfo worldinfo;
+
+                try {
+                    dynamic = worldSession.getDataTag();
+                    worldinfo = worldSession.getSummary(dynamic);
+                } catch (NbtException | ReportedNbtException | IOException ioexception) {
+                    Convertable.b convertable_b = worldSession.getLevelDirectory();
+
+                    MinecraftServer.LOGGER.warn("Failed to load world data from {}", convertable_b.dataFile(), ioexception);
+                    MinecraftServer.LOGGER.info("Attempting to use fallback");
+
+                    try {
+                        dynamic = worldSession.getDataTagFallback();
+                        worldinfo = worldSession.getSummary(dynamic);
+                    } catch (NbtException | ReportedNbtException | IOException ioexception1) {
+                        MinecraftServer.LOGGER.error("Failed to load world data from {}", convertable_b.oldDataFile(), ioexception1);
+                        MinecraftServer.LOGGER.error("Failed to load world data from {} and {}. World files may be corrupted. Shutting down.", convertable_b.dataFile(), convertable_b.oldDataFile());
+                        return;
+                    }
+
+                    worldSession.restoreLevelDataFromOld();
+                }
+
+                if (worldinfo.requiresManualConversion()) {
+                    MinecraftServer.LOGGER.info("This world must be opened in an older version (like 1.6.4) to be safely converted");
+                    return;
+                }
+
+                if (!worldinfo.isCompatible()) {
+                    MinecraftServer.LOGGER.info("This world was created by an incompatible version.");
+                    return;
+                }
+            } else {
+                dynamic = null;
+            }
+
+            org.bukkit.generator.ChunkGenerator gen = this.server.getGenerator(name);
+            org.bukkit.generator.BiomeProvider biomeProvider = this.server.getBiomeProvider(name);
+
+            WorldDataServer worlddata;
+            WorldLoader.a worldloader_a = this.worldLoader;
+            IRegistry<WorldDimension> iregistry = worldloader_a.datapackDimensions().lookupOrThrow(Registries.LEVEL_STEM);
+            if (dynamic != null) {
+                LevelDataAndDimensions leveldataanddimensions = Convertable.getLevelDataAndDimensions(dynamic, worldloader_a.dataConfiguration(), iregistry, worldloader_a.datapackWorldgen());
+
+                worlddata = (WorldDataServer) leveldataanddimensions.worldData();
+            } else {
+                WorldSettings worldsettings;
+                WorldOptions worldoptions;
+                WorldDimensions worlddimensions;
+
+                if (this.isDemo()) {
+                    worldsettings = MinecraftServer.DEMO_SETTINGS;
+                    worldoptions = WorldOptions.DEMO_OPTIONS;
+                    worlddimensions = WorldPresets.createNormalWorldDimensions(worldloader_a.datapackWorldgen());
+                } else {
+                    DedicatedServerProperties dedicatedserverproperties = ((DedicatedServer) this).getProperties();
+
+                    worldsettings = new WorldSettings(dedicatedserverproperties.levelName, dedicatedserverproperties.gamemode, dedicatedserverproperties.hardcore, dedicatedserverproperties.difficulty, false, new GameRules(worldloader_a.dataConfiguration().enabledFeatures()), worldloader_a.dataConfiguration());
+                    worldoptions = options.has("bonusChest") ? dedicatedserverproperties.worldOptions.withBonusChest(true) : dedicatedserverproperties.worldOptions;
+                    worlddimensions = dedicatedserverproperties.createDimensions(worldloader_a.datapackWorldgen());
+                }
+
+                WorldDimensions.b worlddimensions_b = worlddimensions.bake(iregistry);
+                Lifecycle lifecycle = worlddimensions_b.lifecycle().add(worldloader_a.datapackWorldgen().allRegistriesLifecycle());
+
+                worlddata = new WorldDataServer(worldsettings, worldoptions, worlddimensions_b.specialWorldProperty(), lifecycle);
+            }
+            worlddata.checkName(name); // CraftBukkit - Migration did not rewrite the level.dat; This forces 1.8 to take the last loaded world as respawn (in this case the end)
+            if (options.has("forceUpgrade")) {
+                net.minecraft.server.Main.forceUpgrade(worldSession, worlddata, DataConverterRegistry.getDataFixer(), options.has("eraseCache"), () -> {
+                    return true;
+                }, iregistrycustom_dimension, options.has("recreateRegionFiles"));
+            }
+
+            WorldDataServer iworlddataserver = worlddata;
+            boolean flag = worlddata.isDebugWorld();
+            WorldOptions worldoptions = worlddata.worldGenOptions();
+            long i = worldoptions.seed();
+            long j = BiomeManager.obfuscateSeed(i);
+            List<MobSpawner> list = ImmutableList.of(new MobSpawnerPhantom(), new MobSpawnerPatrol(), new MobSpawnerCat(), new VillageSiege(), new MobSpawnerTrader(iworlddataserver));
+            WorldDimension worlddimension = (WorldDimension) dimensions.getValue(dimensionKey);
+
+            org.bukkit.generator.WorldInfo worldInfo = new org.bukkit.craftbukkit.generator.CraftWorldInfo(iworlddataserver, worldSession, org.bukkit.World.Environment.getEnvironment(dimension), worlddimension.type().value());
+            if (biomeProvider == null && gen != null) {
+                biomeProvider = gen.getDefaultBiomeProvider(worldInfo);
+            }
+
+            ResourceKey<World> worldKey = ResourceKey.create(Registries.DIMENSION, dimensionKey.location());
+
+            if (dimensionKey == WorldDimension.OVERWORLD) {
+                this.worldData = worlddata;
+                this.worldData.setGameType(((DedicatedServer) this).getProperties().gamemode); // From DedicatedServer.init
+
+                WorldLoadListener worldloadlistener = this.progressListenerFactory.create(this.worldData.getGameRules().getInt(GameRules.RULE_SPAWN_CHUNK_RADIUS));
+
+                world = new WorldServer(this, this.executor, worldSession, iworlddataserver, worldKey, worlddimension, worldloadlistener, flag, j, list, true, (RandomSequences) null, org.bukkit.World.Environment.getEnvironment(dimension), gen, biomeProvider);
+                WorldPersistentData worldpersistentdata = world.getDataStorage();
+                this.readScoreboard(worldpersistentdata);
+                this.server.scoreboardManager = new org.bukkit.craftbukkit.scoreboard.CraftScoreboardManager(this, world.getScoreboard());
+                this.commandStorage = new PersistentCommandStorage(worldpersistentdata);
+            } else {
+                WorldLoadListener worldloadlistener = this.progressListenerFactory.create(worldData.getGameRules().getInt(GameRules.RULE_SPAWN_CHUNK_RADIUS));
+                world = new WorldServer(this, this.executor, worldSession, iworlddataserver, worldKey, worlddimension, worldloadlistener, flag, j, ImmutableList.of(), true, this.overworld().getRandomSequences(), org.bukkit.World.Environment.getEnvironment(dimension), gen, biomeProvider);
+            }
+
+            worlddata.setModdedInfo(this.getServerModName(), this.getModdedStatus().shouldReportAsModified());
+            this.initWorld(world, worlddata, worldData, worldoptions);
+
+            this.addLevel(world);
+            this.getPlayerList().addWorldborderListener(world);
+
+            if (worlddata.getCustomBossEvents() != null) {
+                this.getCustomBossEvents().load(worlddata.getCustomBossEvents(), this.registryAccess());
+            }
+        }
+        this.forceDifficulty();
+        for (WorldServer worldserver : this.getAllLevels()) {
+            this.prepareLevels(worldserver.getChunkSource().chunkMap.progressListener, worldserver);
+            worldserver.entityManager.tick(); // SPIGOT-6526: Load pending entities so they are available to the API
+            this.server.getPluginManager().callEvent(new org.bukkit.event.world.WorldLoadEvent(worldserver.getWorld()));
+        }
+
+        this.server.enablePlugins(org.bukkit.plugin.PluginLoadOrder.POSTWORLD);
+        this.server.getPluginManager().callEvent(new ServerLoadEvent(ServerLoadEvent.LoadType.STARTUP));
+        this.connection.acceptConnections();
+    }
+
+    public void initWorld(WorldServer worldserver, IWorldDataServer iworlddataserver, SaveData saveData, WorldOptions worldoptions) {
+        boolean flag = saveData.isDebugWorld();
+        // CraftBukkit start
+        if (worldserver.generator != null) {
+            worldserver.getWorld().getPopulators().addAll(worldserver.generator.getDefaultPopulators(worldserver.getWorld()));
+        }
         WorldBorder worldborder = worldserver.getWorldBorder();
+        worldborder.applySettings(iworlddataserver.getWorldBorder()); // CraftBukkit - move up so that WorldBorder is set during WorldInitEvent
+        this.server.getPluginManager().callEvent(new org.bukkit.event.world.WorldInitEvent(worldserver.getWorld())); // CraftBukkit - SPIGOT-5569: Call WorldInitEvent before any chunks are generated
 
         if (!iworlddataserver.isInitialized()) {
             try {
@@ -423,28 +678,8 @@
             iworlddataserver.setInitialized(true);
         }
 
-        this.getPlayerList().addWorldborderListener(worldserver);
-        if (this.worldData.getCustomBossEvents() != null) {
-            this.getCustomBossEvents().load(this.worldData.getCustomBossEvents(), this.registryAccess());
-        }
-
-        RandomSequences randomsequences = worldserver.getRandomSequences();
-
-        for (Map.Entry<ResourceKey<WorldDimension>, WorldDimension> map_entry : iregistry.entrySet()) {
-            ResourceKey<WorldDimension> resourcekey = (ResourceKey) map_entry.getKey();
-
-            if (resourcekey != WorldDimension.OVERWORLD) {
-                ResourceKey<World> resourcekey1 = ResourceKey.create(Registries.DIMENSION, resourcekey.location());
-                SecondaryWorldData secondaryworlddata = new SecondaryWorldData(this.worldData, iworlddataserver);
-                WorldServer worldserver1 = new WorldServer(this, this.executor, this.storageSource, secondaryworlddata, resourcekey1, (WorldDimension) map_entry.getValue(), worldloadlistener, flag, j, ImmutableList.of(), false, randomsequences);
-
-                worldborder.addListener(new IWorldBorderListener.a(worldserver1.getWorldBorder()));
-                this.levels.put(resourcekey1, worldserver1);
-            }
-        }
-
-        worldborder.applySettings(iworlddataserver.getWorldBorder());
     }
+    // CraftBukkit end
 
     private static void setInitialSpawn(WorldServer worldserver, IWorldDataServer iworlddataserver, boolean flag, boolean flag1) {
         if (flag1) {
@@ -452,6 +687,21 @@
         } else {
             ChunkProviderServer chunkproviderserver = worldserver.getChunkSource();
             ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(chunkproviderserver.randomState().sampler().findSpawnPosition());
+            // CraftBukkit start
+            if (worldserver.generator != null) {
+                Random rand = new Random(worldserver.getSeed());
+                org.bukkit.Location spawn = worldserver.generator.getFixedSpawnLocation(worldserver.getWorld(), rand);
+
+                if (spawn != null) {
+                    if (spawn.getWorld() != worldserver.getWorld()) {
+                        throw new IllegalStateException("Cannot set spawn point for " + iworlddataserver.getLevelName() + " to be in another world (" + spawn.getWorld().getName() + ")");
+                    } else {
+                        iworlddataserver.setSpawn(new BlockPosition(spawn.getBlockX(), spawn.getBlockY(), spawn.getBlockZ()), spawn.getYaw());
+                        return;
+                    }
+                }
+            }
+            // CraftBukkit end
             int i = chunkproviderserver.getGenerator().getSpawnHeight(worldserver);
 
             if (i < worldserver.getMinY()) {
@@ -510,8 +760,11 @@
         iworlddataserver.setGameType(EnumGamemode.SPECTATOR);
     }
 
-    public void prepareLevels(WorldLoadListener worldloadlistener) {
-        WorldServer worldserver = this.overworld();
+    // CraftBukkit start
+    public void prepareLevels(WorldLoadListener worldloadlistener, WorldServer worldserver) {
+        // WorldServer worldserver = this.overworld();
+        this.forceTicks = true;
+        // CraftBukkit end
 
         MinecraftServer.LOGGER.info("Preparing start region for dimension {}", worldserver.dimension().location());
         BlockPosition blockposition = worldserver.getSharedSpawnPos();
@@ -521,18 +774,21 @@
 
         this.nextTickTimeNanos = SystemUtils.getNanos();
         worldserver.setDefaultSpawnPos(blockposition, worldserver.getSharedSpawnAngle());
-        int i = this.getGameRules().getInt(GameRules.RULE_SPAWN_CHUNK_RADIUS);
+        int i = worldserver.getGameRules().getInt(GameRules.RULE_SPAWN_CHUNK_RADIUS); // CraftBukkit - per-world
         int j = i > 0 ? MathHelper.square(WorldLoadListener.calculateDiameter(i)) : 0;
 
         while (chunkproviderserver.getTickingGenerated() < j) {
-            this.nextTickTimeNanos = SystemUtils.getNanos() + MinecraftServer.PREPARE_LEVELS_DEFAULT_DELAY_NANOS;
-            this.waitUntilNextTick();
+            // CraftBukkit start
+            // this.nextTickTimeNanos = SystemUtils.getNanos() + MinecraftServer.PREPARE_LEVELS_DEFAULT_DELAY_NANOS;
+            this.executeModerately();
         }
 
-        this.nextTickTimeNanos = SystemUtils.getNanos() + MinecraftServer.PREPARE_LEVELS_DEFAULT_DELAY_NANOS;
-        this.waitUntilNextTick();
+        // this.nextTickTimeNanos = SystemUtils.getNanos() + MinecraftServer.PREPARE_LEVELS_DEFAULT_DELAY_NANOS;
+        this.executeModerately();
 
-        for (WorldServer worldserver1 : this.levels.values()) {
+        if (true) {
+            WorldServer worldserver1 = worldserver;
+            // CraftBukkit end
             TicketStorage ticketstorage = (TicketStorage) worldserver1.getDataStorage().get(TicketStorage.TYPE);
 
             if (ticketstorage != null) {
@@ -540,10 +796,17 @@
             }
         }
 
-        this.nextTickTimeNanos = SystemUtils.getNanos() + MinecraftServer.PREPARE_LEVELS_DEFAULT_DELAY_NANOS;
-        this.waitUntilNextTick();
+        // CraftBukkit start
+        // this.nextTickTimeNanos = SystemUtils.getNanos() + MinecraftServer.PREPARE_LEVELS_DEFAULT_DELAY_NANOS;
+        this.executeModerately();
+        // CraftBukkit end
         worldloadlistener.stop();
-        this.updateMobSpawningFlags();
+        // CraftBukkit start
+        // this.updateMobSpawningFlags();
+        worldserver.setSpawnSettings(this.isSpawningMonsters());
+
+        this.forceTicks = false;
+        // CraftBukkit end
     }
 
     public EnumGamemode getDefaultGameType() {
@@ -572,12 +835,16 @@
             flag3 = true;
         }
 
+        // CraftBukkit start - moved to WorldServer.save
+        /*
         WorldServer worldserver1 = this.overworld();
         IWorldDataServer iworlddataserver = this.worldData.overworldData();
 
         iworlddataserver.setWorldBorder(worldserver1.getWorldBorder().createSettings());
         this.worldData.setCustomBossEvents(this.getCustomBossEvents().save(this.registryAccess()));
         this.storageSource.saveDataTag(this.registryAccess(), this.worldData, this.getPlayerList().getSingleplayerData());
+        */
+        // CraftBukkit end
         if (flag1) {
             for (WorldServer worldserver2 : this.getAllLevels()) {
                 MinecraftServer.LOGGER.info("ThreadedAnvilChunkStorage ({}): All chunks are saved", worldserver2.getChunkSource().chunkMap.getStorageName());
@@ -608,18 +875,40 @@
         this.stopServer();
     }
 
+    // CraftBukkit start
+    private boolean hasStopped = false;
+    private final Object stopLock = new Object();
+    public final boolean hasStopped() {
+        synchronized (stopLock) {
+            return hasStopped;
+        }
+    }
+    // CraftBukkit end
+
     public void stopServer() {
+        // CraftBukkit start - prevent double stopping on multiple threads
+        synchronized(stopLock) {
+            if (hasStopped) return;
+            hasStopped = true;
+        }
+        // CraftBukkit end
         if (this.metricsRecorder.isRecording()) {
             this.cancelRecordingMetrics();
         }
 
         MinecraftServer.LOGGER.info("Stopping server");
+        // CraftBukkit start
+        if (this.server != null) {
+            this.server.disablePlugins();
+        }
+        // CraftBukkit end
         this.getConnection().stop();
         this.isSaving = true;
         if (this.playerList != null) {
             MinecraftServer.LOGGER.info("Saving players");
             this.playerList.saveAll();
             this.playerList.removeAll();
+            try { Thread.sleep(100); } catch (InterruptedException ex) {} // CraftBukkit - SPIGOT-625 - give server at least a chance to send packets
         }
 
         MinecraftServer.LOGGER.info("Saving worlds");
@@ -699,7 +988,7 @@
             }
 
             this.nextTickTimeNanos = SystemUtils.getNanos();
-            this.statusIcon = (ServerPing.a) this.loadStatusIcon().orElse((Object) null);
+            this.statusIcon = (ServerPing.a) this.loadStatusIcon().orElse(null); // CraftBukkit - decompile error
             this.status = this.buildServerStatus();
 
             while (this.running) {
@@ -716,6 +1005,7 @@
                     if (j > MinecraftServer.OVERLOADED_THRESHOLD_NANOS + 20L * i && this.nextTickTimeNanos - this.lastOverloadWarningNanos >= MinecraftServer.OVERLOADED_WARNING_INTERVAL_NANOS + 100L * i) {
                         long k = j / i;
 
+                        if (server.getWarnOnOverload()) // CraftBukkit
                         MinecraftServer.LOGGER.warn("Can't keep up! Is the server overloaded? Running {}ms or {} ticks behind", j / TimeRange.NANOSECONDS_PER_MILLISECOND, k);
                         this.nextTickTimeNanos += k * i;
                         this.lastOverloadWarningNanos = this.nextTickTimeNanos;
@@ -729,6 +1019,7 @@
                     this.debugCommandProfiler = new MinecraftServer.TimeProfiler(SystemUtils.getNanos(), this.tickCount);
                 }
 
+                MinecraftServer.currentTick = (int) (System.currentTimeMillis() / 50); // CraftBukkit
                 this.nextTickTimeNanos += i;
 
                 try {
@@ -802,6 +1093,12 @@
                     this.services.profileCache().clearExecutor();
                 }
 
+                // CraftBukkit start - Restore terminal to original settings
+                try {
+                    reader.getTerminal().restore();
+                } catch (Exception ignored) {
+                }
+                // CraftBukkit end
                 this.onServerExit();
             }
 
@@ -861,7 +1158,14 @@
     }
 
     private boolean haveTime() {
-        return this.runningTask() || SystemUtils.getNanos() < (this.mayHaveDelayedTasks ? this.delayedTasksMaxNextTickTimeNanos : this.nextTickTimeNanos);
+        // CraftBukkit start
+        return this.forceTicks || this.runningTask() || SystemUtils.getNanos() < (this.mayHaveDelayedTasks ? this.delayedTasksMaxNextTickTimeNanos : this.nextTickTimeNanos);
+    }
+
+    private void executeModerately() {
+        this.runAllTasks();
+        java.util.concurrent.locks.LockSupport.parkNanos("executing tasks", 1000L);
+        // CraftBukkit end
     }
 
     public static boolean throwIfFatalException() {
@@ -875,7 +1179,7 @@
     }
 
     public static void setFatalException(RuntimeException runtimeexception) {
-        MinecraftServer.fatalException.compareAndSet((Object) null, runtimeexception);
+        MinecraftServer.fatalException.compareAndSet(null, runtimeexception); // CraftBukkit - decompile error
     }
 
     @Override
@@ -945,7 +1249,7 @@
         }
     }
 
-    protected void doRunTask(TickTask ticktask) {
+    public void doRunTask(TickTask ticktask) { // CraftBukkit - decompile error
         Profiler.get().incrementCounter("runTask");
         super.doRunTask(ticktask);
     }
@@ -1009,6 +1313,7 @@
                     this.autoSave();
                 }
 
+                this.server.getScheduler().mainThreadHeartbeat(); // CraftBukkit
                 this.tickConnection();
                 return;
             }
@@ -1023,7 +1328,7 @@
         }
 
         --this.ticksUntilAutosave;
-        if (this.ticksUntilAutosave <= 0) {
+        if (this.autosavePeriod > 0 && this.ticksUntilAutosave <= 0) { // CraftBukkit
             this.autoSave();
         }
 
@@ -1042,7 +1347,7 @@
     }
 
     private void autoSave() {
-        this.ticksUntilAutosave = this.computeNextAutosaveInterval();
+        this.ticksUntilAutosave = this.autosavePeriod; // CraftBukkit
         MinecraftServer.LOGGER.debug("Autosave started");
         GameProfilerFiller gameprofilerfiller = Profiler.get();
 
@@ -1122,21 +1427,38 @@
         this.getPlayerList().getPlayers().forEach((entityplayer) -> {
             entityplayer.connection.suspendFlushing();
         });
+        this.server.getScheduler().mainThreadHeartbeat(); // CraftBukkit
         gameprofilerfiller.push("commandFunctions");
         this.getFunctions().tick();
         gameprofilerfiller.popPush("levels");
 
+        // CraftBukkit start
+        // Run tasks that are waiting on processing
+        while (!processQueue.isEmpty()) {
+            processQueue.remove().run();
+        }
+
+        // Send time updates to everyone, it will get the right time from the world the player is in.
+        if (this.tickCount % 20 == 0) {
+            for (int i = 0; i < this.getPlayerList().players.size(); ++i) {
+                EntityPlayer entityplayer = (EntityPlayer) this.getPlayerList().players.get(i);
+                entityplayer.connection.send(new PacketPlayOutUpdateTime(entityplayer.level().getGameTime(), entityplayer.getPlayerTime(), entityplayer.serverLevel().getGameRules().getBoolean(GameRules.RULE_DAYLIGHT))); // Add support for per player time
+            }
+        }
+
         for (WorldServer worldserver : this.getAllLevels()) {
             gameprofilerfiller.push(() -> {
                 String s = String.valueOf(worldserver);
 
                 return s + " " + String.valueOf(worldserver.dimension().location());
             });
+            /* Drop global time updates
             if (this.tickCount % 20 == 0) {
                 gameprofilerfiller.push("timeSync");
                 this.synchronizeTime(worldserver);
                 gameprofilerfiller.pop();
             }
+            // CraftBukkit end */
 
             gameprofilerfiller.push("tick");
 
@@ -1226,6 +1548,22 @@
         return (WorldServer) this.levels.get(resourcekey);
     }
 
+    // CraftBukkit start
+    public void addLevel(WorldServer level) {
+        Map<ResourceKey<World>, WorldServer> oldLevels = this.levels;
+        Map<ResourceKey<World>, WorldServer> newLevels = Maps.newLinkedHashMap(oldLevels);
+        newLevels.put(level.dimension(), level);
+        this.levels = Collections.unmodifiableMap(newLevels);
+    }
+
+    public void removeLevel(WorldServer level) {
+        Map<ResourceKey<World>, WorldServer> oldLevels = this.levels;
+        Map<ResourceKey<World>, WorldServer> newLevels = Maps.newLinkedHashMap(oldLevels);
+        newLevels.remove(level.dimension());
+        this.levels = Collections.unmodifiableMap(newLevels);
+    }
+    // CraftBukkit end
+
     public Set<ResourceKey<World>> levelKeys() {
         return this.levels.keySet();
     }
@@ -1255,7 +1593,7 @@
 
     @DontObfuscate
     public String getServerModName() {
-        return "vanilla";
+        return server.getName(); // CraftBukkit - cb > vanilla!
     }
 
     public SystemReport fillSystemReport(SystemReport systemreport) {
@@ -1589,11 +1927,11 @@
 
     public CompletableFuture<Void> reloadResources(Collection<String> collection) {
         CompletableFuture<Void> completablefuture = CompletableFuture.supplyAsync(() -> {
-            Stream stream = collection.stream();
+            Stream<String> stream = collection.stream(); // CraftBukkit - decompile error
             ResourcePackRepository resourcepackrepository = this.packRepository;
 
             Objects.requireNonNull(this.packRepository);
-            return (ImmutableList) stream.map(resourcepackrepository::getPack).filter(Objects::nonNull).map(ResourcePackLoader::open).collect(ImmutableList.toImmutableList());
+            return stream.map(resourcepackrepository::getPack).filter(Objects::nonNull).map(ResourcePackLoader::open).collect(ImmutableList.toImmutableList()); // CraftBukkit - decompile error
         }, this).thenCompose((immutablelist) -> {
             IReloadableResourceManager ireloadableresourcemanager = new ResourceManager(EnumResourcePackType.SERVER_DATA, immutablelist);
             List<IRegistry.a<?>> list = TagDataPack.loadTagsForExistingRegistries(ireloadableresourcemanager, this.registries.compositeAccess());
@@ -1609,6 +1947,7 @@
         }).thenAcceptAsync((minecraftserver_reloadableresources) -> {
             this.resources.close();
             this.resources = minecraftserver_reloadableresources;
+            this.server.syncCommands(); // SPIGOT-5884: Lost on reload
             this.packRepository.setSelected(collection);
             WorldDataConfiguration worlddataconfiguration = new WorldDataConfiguration(getSelectedPacks(this.packRepository, true), this.worldData.enabledFeatures());
 
@@ -1938,6 +2277,22 @@
         }
     }
 
+    // CraftBukkit start
+    public boolean isDebugging() {
+        return false;
+    }
+
+    @Deprecated
+    public static MinecraftServer getServer() {
+        return (Bukkit.getServer() instanceof CraftServer) ? ((CraftServer) Bukkit.getServer()).getServer() : null;
+    }
+
+    @Deprecated
+    public static IRegistryCustom getDefaultRegistryAccess() {
+        return CraftRegistry.getMinecraftRegistry();
+    }
+    // CraftBukkit end
+
     private GameProfilerFiller createProfiler() {
         if (this.willStartRecordingMetrics) {
             this.metricsRecorder = ActiveMetricsRecorder.createStarted(new ServerMetricsSamplersProvider(SystemUtils.timeSource, this.isDedicatedServer()), SystemUtils.timeSource, SystemUtils.ioPool(), new MetricsPersister("server"), this.onMetricsRecordingStopped, (path) -> {
@@ -2065,6 +2420,11 @@
 
     }
 
+    // CraftBukkit start
+    public final java.util.concurrent.ExecutorService chatExecutor = java.util.concurrent.Executors.newCachedThreadPool(
+            new com.google.common.util.concurrent.ThreadFactoryBuilder().setDaemon(true).setNameFormat("Async Chat Thread - #%d").build());
+    // CraftBukkit end
+
     public ChatDecorator getChatDecorator() {
         return ChatDecorator.PLAIN;
     }