Could you perhaps use the 'More->Syntax Highlighter' so this doesn't look like an immense wall of code without indentation. For code of this size, consider providing a compilable attachment.
Macro's and front checking of TXE would also be recommended.
Tips, Buy me a coffee, or three.. PayPal Venmo (See Profile) Up vote any posts that you find helpful, it shows what's working..
Is there someone at ST I can refer this problem to as I need IAP and if that can't be achieved with this STM32 part I'll have to look for alternatives from other manufacturers