/*************************************************************/
/**   Gentherm.c - used for generating thermistor transfer  **/
/**   function files for MegaSquirt.                        **/
/**                                                         **/
/**   Generates thermfactor.inc and airdenfactor.inc        **/
/**                                                         **/
/**   Bruce Bowling, July 2001                              **/
/*************************************************************/


#include <stdio.h>
#include <math.h>

/* User-defined area here */

/* Thermistor transfer function:
    NTEMPS = Number of temperature-resistance pairs
    temp   = temperature array of values (degrees F)
    res    = corresponding resistance values (ascending order)
 */

#define NTEMPS 15
double temp[NTEMPS] = { 210, 194, 176, 158, 140, 122,  104,   86,   68,   50,   32,    14,    -4,   -22,    -40 };
double  res[NTEMPS] = { 177, 241, 332, 467, 667, 973, 1459, 2238, 3520, 5670, 9420, 16180, 28681, 52700, 100700 };

/* End user-defined area */

void main()
{
   double         rescalc, tempcalc, ad, adp;
   FILE          *cts, *mat;
   int            i, count;

   cts = fopen("./thermfactor.inb", "w");
   fprintf(cts, "THERMFACTOR:\n");

   mat = fopen("./airdenfactor.inb", "w");
   fprintf(mat, "AIRDENFACTOR:\n");

   /* Loop over all of the A/D range (0 to 255 for 8 bits). */
   for (count = 0; count < 256; count++) {
      if (count < 1 || count > 254) {
         fprintf(cts, "\tDB\t210T\n");  /* This is the end-point limp-home value. */
         fprintf(mat, "\tDB\t100T\n");  /* This is the end-point limp-home value. */
      }
      else {
         /* determine resistance for corresponding count */
         rescalc = 2490.0 / ((255.0 / (double)count) - 1.0);

         /* Find where resistance value lies in res[] array */
         i = 1;
         while (i < (NTEMPS - 1) && rescalc > res[i]) i++;

         /* Linear interpolate */
         tempcalc = temp[i] + ((temp[i] - temp[i - 1]) * (rescalc - res[i])) / (res[i] - res[i - 1]);

         /* Limit range and write (add 40 degree offset in write */
         if (tempcalc > 215.0) tempcalc = 215.0;
         if (tempcalc < -40.0) tempcalc = -40.0;
         fprintf(cts, "\tDB\t%dT\t; %3d\n", (int) (tempcalc + 40), count);

         /* Determine air density correction factor and write */
         ad = 37.943 / ((tempcalc + 459.7) * 1728.0);
         adp = 100.0 * (ad / 4.157E-5);
         fprintf(mat, "\tDB\t%dT\t; %3d\n", (int) (adp), count);

      }
   }

   fclose(cts);
   fclose(mat);
}

