Creating valid FIT files for complex gym workouts

I wanted to share this, because it took me forever to find an answer and there may be other people in a similar situation.

I needed to create a FIT file to import gym workout data into Garmin connect. 
For historical reasons (understandably), the FIT protocol is optimized for activities like running/cycling/swimming, so creating a valid solution for in-door gym workouts was tricky. Especially, when there are several workouts, containing several exercises, each - in turn - containing several sets. It required working around several poorly documented requirements and dealing with practically non-existent error info during import in Garmin Connect.

Here is a tool that demonstrates how this can be done correctly:

https://github.com/macrogreg/Just6Weeks-to-GarminFIT