From a3a21b3c27d709947acf7685402d4772267cda78 Mon Sep 17 00:00:00 2001
From: rswindell <>
Date: Mon, 5 Dec 2016 12:01:21 +0000
Subject: [PATCH] Created new function: smb_first_in_thread() which returns the
 number of the oldest *existing* message in the thread referenced by the
 specified msg.

---
 src/smblib/smbdefs.h |  2 +-
 src/smblib/smblib.c  | 28 ++++++++++++++++++++++++++++
 src/smblib/smblib.h  |  1 +
 3 files changed, 30 insertions(+), 1 deletion(-)

diff --git a/src/smblib/smbdefs.h b/src/smblib/smbdefs.h
index baf75c087d..61d3ea5b06 100644
--- a/src/smblib/smbdefs.h
+++ b/src/smblib/smbdefs.h
@@ -657,7 +657,7 @@ typedef struct {				/* Message base */
 	/* Private member variables (not initialized by or used by smblib) */
 	uint32_t	subnum;			/* Sub-board number */
 	uint32_t	msgs;			/* Number of messages loaded (for user) */
-	uint32_t	curmsg;			/* Current message number (for user) */
+	uint32_t	curmsg;			/* Current message number (for user, 0-based) */
 
 } smb_t;
 
diff --git a/src/smblib/smblib.c b/src/smblib/smblib.c
index ba19655137..4ad9b2ba26 100644
--- a/src/smblib/smblib.c
+++ b/src/smblib/smblib.c
@@ -2004,4 +2004,32 @@ int SMBCALL smb_updatethread(smb_t* smb, smbmsg_t* remsg, ulong newmsgnum)
 	return(retval);
 }
 
+long SMBCALL smb_first_in_thread(smb_t* smb, smbmsg_t* remsg)
+{
+	smbmsg_t msg;
+
+	if(!remsg->hdr.thread_back)
+		return remsg->hdr.number;
+
+	memset(&msg, 0, sizeof(msg));
+	msg.hdr.number = remsg->hdr.thread_id;
+	if(smb_getmsgidx(smb, &msg) == SMB_SUCCESS)
+		return msg.hdr.number;
+
+	/* Walk the thread backwards to find the oldest msg in thread */
+	long msgnum = msg.hdr.number = remsg->hdr.number;
+	msg.hdr.thread_back = remsg->hdr.thread_back;
+	while(msg.hdr.thread_back != 0 && msg.hdr.thread_back < msg.hdr.number) {
+		msg.hdr.number = msg.hdr.thread_back;
+		if(smb_getmsgidx(smb, &msg) != SMB_SUCCESS)
+			break;
+		if(smb_getmsghdr(smb, &msg) != SMB_SUCCESS)
+			break;
+		smb_freemsgmem(&msg);
+		msgnum = msg.hdr.number;
+	}
+
+	return msgnum;
+}
+
 /* End of SMBLIB.C */
diff --git a/src/smblib/smblib.h b/src/smblib/smblib.h
index 7e5e3d314a..eae371e7fa 100644
--- a/src/smblib/smblib.h
+++ b/src/smblib/smblib.h
@@ -186,6 +186,7 @@ SMBEXPORT BOOL		SMBCALL smb_valid_hdr_offset(smb_t* smb, ulong offset);
 SMBEXPORT int		SMBCALL smb_init_idx(smb_t* smb, smbmsg_t* msg);
 SMBEXPORT uint16_t	SMBCALL	smb_voted_already(smb_t*, uint32_t msgnum, const char* name, enum smb_net_type, void* net_addr);
 SMBEXPORT BOOL		SMBCALL smb_msg_is_from(smbmsg_t* msg, const char* name, enum smb_net_type net_type, const void* net_addr);
+SMBEXPORT long		SMBCALL smb_first_in_thread(smb_t*, smbmsg_t*);
 
 /* smbadd.c */
 SMBEXPORT int		SMBCALL smb_addmsg(smb_t* smb, smbmsg_t* msg, int storage, long dupechk_hashes
-- 
GitLab