There were some errors in the calculation as well as an entire unnecessary loop to find the gain coefficient. Merge the two loops. Thanks to @ubitux for the suggestions and testing.
4b1f5e5090
26e8fa3b50