// tpgen.cpp : implementation file
//

#include "stdafx.h"
#include "megatune.h"
#include "tpgen.h"
#include "veconst.h"
#include "msDatabase.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

extern msDatabase mdb;

//------------------------------------------------------------------------------

tpgen::tpgen(CWnd* pParent /*=NULL*/)
	: CDialog(tpgen::IDD, pParent)
{
	//{{AFX_DATA_INIT(tpgen)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
}

void tpgen::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(tpgen)
      DDX_Control(pDX, IDC_TP_LO, m_tp_lo);
      DDX_Control(pDX, IDC_TP_HI, m_tp_hi);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(tpgen, CDialog)
	//{{AFX_MSG_MAP(tpgen)
      ON_BN_CLICKED(IDC_GET_LO, OnGetLo)
      ON_BN_CLICKED(IDC_GET_HI, OnGetHi)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

//------------------------------------------------------------------------------

void tpgen::getVal(CEdit &fld)
{
   unsigned char runtimevars[Rget];
   if (mdb.getRuntime(runtimevars)) {
      char wText[10];
      sprintf(wText, "%d", runtimevars[Rtps]);
      fld.SetWindowText(wText);
   }
}

void tpgen::OnGetLo() 
{
   getVal(m_tp_lo);
}

void tpgen::OnGetHi() 
{
   getVal(m_tp_hi);
}

//------------------------------------------------------------------------------

int tpgen::pctFromAdc(int adc)
{
   if (adc <= lo) return   0;
   if (adc >= hi) return 100;
   return (adc-lo) * 100 / (hi-lo);
}

FILE *cfgOpen(const char *fileName, const char *mode);

void tpgen::writeFile()
{
   FILE *tp = cfgOpen("throttlefactor.inc", "w");
   fprintf(tp, "; MegaSquirt throttle factor file, low ADC = %d, high ADC = %d\n", lo, hi);
   fprintf(tp, "THROTTLEFACTOR:\n\t\t\t; ADC\n");
   for (int adc = 0; adc < 256; adc++) {
      fprintf(tp, "\tDB\t%3dT\t; %3d\n", pctFromAdc(adc), adc);
      mdb.tpsf[adc] = pctFromAdc(adc);
   }
   fclose(tp);
}

//------------------------------------------------------------------------------

void tpgen::OnOK() 
{
   char wText[10];
   
   m_tp_lo.GetWindowText(wText, sizeof(wText)-1);
   lo = strtol(wText, NULL, 10);
   if (lo < 0 || lo > 128) {
      if (MessageBox(CString("Low value ") +wText+" looks funny, should be 0 <= x <<= 255, use it anyhow?", "TP Inc Generator", MB_YESNO | MB_DEFBUTTON2 | MB_ICONQUESTION) != IDYES) {
         return;
      }
   }

   m_tp_hi.GetWindowText(wText, sizeof(wText)-1);
   hi = strtol(wText, NULL, 10);
   if(hi < 128 || hi > 255) {
      if (MessageBox(CString("High value ") +wText+" looks funny, should be 0 <<= x <= 255, use it anyhow?", "TP Inc Generator", MB_YESNO | MB_DEFBUTTON2 | MB_ICONQUESTION) != IDYES) {
         return;
      }
   }

   writeFile();
   CDialog::OnOK();
}

//------------------------------------------------------------------------------

