From 06d3af671634779a640c15a3fe9f9c953635aaa6 Mon Sep 17 00:00:00 2001
From: Louis-Antoine <lamr@free.fr>
Date: Tue, 19 May 2020 15:16:51 +0200
Subject: [PATCH] Refactor Lua file transfer code

---
 src/blua/liolib.c | 11 +----------
 src/d_netfil.c    | 43 ++++++++++++++++++++++---------------------
 2 files changed, 23 insertions(+), 31 deletions(-)

diff --git a/src/blua/liolib.c b/src/blua/liolib.c
index b43052194..ce630a20b 100644
--- a/src/blua/liolib.c
+++ b/src/blua/liolib.c
@@ -314,16 +314,7 @@ void Got_LuaFile(UINT8 **cp, INT32 playernum)
 	RemoveLuaFileTransfer();
 
 	if (server && luafiletransfers)
-	{
-		if (FIL_FileOK(luafiletransfers->realfilename))
-			SV_PrepareSendLuaFileToNextNode();
-		else
-		{
-			// Send a net command with 0 as its first byte to indicate the file couldn't be opened
-			success = 0;
-			SendNetXCmd(XD_LUAFILE, &success, 1);
-		}
-	}
+		SV_PrepareSendLuaFile();
 }
 
 
diff --git a/src/d_netfil.c b/src/d_netfil.c
index b5647ebe2..2262a1f93 100644
--- a/src/d_netfil.c
+++ b/src/d_netfil.c
@@ -538,26 +538,9 @@ void AddLuaFileTransfer(const char *filename, const char *mode)
 
 	strlcpy(filetransfer->mode, mode, sizeof(filetransfer->mode));
 
-	if (server)
-	{
-		INT32 i;
-
-		// Set status to "waiting" for everyone
-		for (i = 0; i < MAXNETNODES; i++)
-			filetransfer->nodestatus[i] = LFTNS_WAITING;
-
-		if (!luafiletransfers->next) // Only if there is no transfer already going on
-		{
-			if (FIL_ReadFileOK(filetransfer->realfilename))
-				SV_PrepareSendLuaFileToNextNode();
-			else
-			{
-				// Send a net command with 0 as its first byte to indicate the file couldn't be opened
-				UINT8 success = 0;
-				SendNetXCmd(XD_LUAFILE, &success, 1);
-			}
-		}
-	}
+	// Only if there is no transfer already going on
+	if (server && filetransfer == luafiletransfers)
+		SV_PrepareSendLuaFile();
 
 	// Store the callback so it can be called once everyone has the file
 	filetransfer->id = id;
@@ -571,7 +554,7 @@ void AddLuaFileTransfer(const char *filename, const char *mode)
 	}
 }
 
-void SV_PrepareSendLuaFileToNextNode(void)
+static void SV_PrepareSendLuaFileToNextNode(void)
 {
 	INT32 i;
 	UINT8 success = 1;
@@ -595,6 +578,24 @@ void SV_PrepareSendLuaFileToNextNode(void)
 	SendNetXCmd(XD_LUAFILE, &success, 1);
 }
 
+void SV_PrepareSendLuaFile(void)
+{
+	INT32 i;
+
+	// Set status to "waiting" for everyone
+	for (i = 0; i < MAXNETNODES; i++)
+		luafiletransfers->nodestatus[i] = LFTNS_WAITING;
+
+	if (FIL_ReadFileOK(luafiletransfers->realfilename))
+		SV_PrepareSendLuaFileToNextNode();
+	else
+	{
+		// Send a net command with 0 as its first byte to indicate the file couldn't be opened
+		UINT8 success = 0;
+		SendNetXCmd(XD_LUAFILE, &success, 1);
+	}
+}
+
 void SV_HandleLuaFileSent(UINT8 node)
 {
 	luafiletransfers->nodestatus[node] = LFTNS_SENT;