#include <stdio.h>
#include <windows.h>

BOOL error;
   

char Commandbuffer[200000];



/* A block of code to run a sub program and capture it's output in a buffer */
DWORD Execprocess()
{
SECURITY_ATTRIBUTES saAttr; 
	saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); 
	saAttr.bInheritHandle = TRUE; 
	saAttr.lpSecurityDescriptor = NULL; 

	HANDLE hWinEndStdOut,hConsoleEndStdOut;
	HANDLE hWinEndStdErr,hConsoleEndStdErr;
	HANDLE hWinEndStdIn,hConsoleEndStdIn;
	
   PROCESS_INFORMATION piProcInfo; 
   STARTUPINFO siStartInfo; 
   sprintf(Commandbuffer,"cpropep.exe -f Temp.pro ");

	// Set up members of STARTUPINFO structure. 
    ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
    ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
    siStartInfo.cb = sizeof(STARTUPINFO); 



	siStartInfo.dwFlags=STARTF_USESTDHANDLES;
	

	if (!CreatePipe(&hWinEndStdOut,&hConsoleEndStdOut,&saAttr,4000))
	{
		fprintf(stderr,"Failed to create pope\n");
		exit(-1);
	}

	if (!CreatePipe(&hWinEndStdErr,&hConsoleEndStdErr,&saAttr,4000))
	{
		fprintf(stderr,"Failed to create pope\n");
		exit(-1);
	}

	if (!CreatePipe(&hConsoleEndStdIn,&hWinEndStdIn,&saAttr,4000))
	{
 		fprintf(stderr,"Failed to create pope\n");
		exit(-1);
	}


	siStartInfo.hStdInput=hConsoleEndStdIn;
	siStartInfo.hStdOutput=hConsoleEndStdOut;
	siStartInfo.hStdError=hConsoleEndStdErr;
	siStartInfo.dwFlags=STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;
	siStartInfo.wShowWindow=SW_MINIMIZE;



 
// Create the child process. 
 
   BOOL rv=CreateProcess(NULL, 
      Commandbuffer,       // command line 
      NULL,          // process security attributes 
      NULL,          // primary thread security attributes 
      TRUE,          // handles are inherited 
      HIGH_PRIORITY_CLASS,             // creation flags 
      NULL,          // use parent's environment 
      NULL,          // use parent's current directory 
      &siStartInfo,  // STARTUPINFO pointer 
      &piProcInfo);  // receives PROCESS_INFORMATION 


  int wait=0;
  DWORD dwStdoutAvail=0;
  DWORD dwErrorAvail=0;

  while ((wait < 1000) && (dwStdoutAvail==0) && (dwErrorAvail==0))
  {
    PeekNamedPipe(hWinEndStdOut,NULL,0,NULL,&dwStdoutAvail,NULL); 
	PeekNamedPipe(hWinEndStdErr,NULL,0,NULL,&dwErrorAvail,NULL); 
    if ((dwStdoutAvail==0) && (dwErrorAvail==0))
	{
	 wait+=20;
	 Sleep(20);
	}
  }

  DWORD dwBytesAvail=0;
  
  if (dwErrorAvail)
  {
	ReadFile(hWinEndStdErr,Commandbuffer,2000,&dwBytesAvail,NULL);
	Commandbuffer[dwBytesAvail]=0;
	error=true;
  }
  else
  if (dwStdoutAvail)
  {
	ReadFile(hWinEndStdOut,Commandbuffer,2000,&dwBytesAvail,NULL);
	Commandbuffer[dwBytesAvail]=0;
	for (DWORD i=0; i<dwBytesAvail; i++)
		{
		}
	
	error=false;
  }
    
	

  DWORD exitcode;
  GetExitCodeProcess(piProcInfo.hProcess,&exitcode);
  
  CloseHandle(piProcInfo.hProcess);
  CloseHandle(hWinEndStdOut);
  CloseHandle(hConsoleEndStdOut);
  CloseHandle(hWinEndStdErr);
  CloseHandle(hConsoleEndStdErr);
  CloseHandle(hWinEndStdIn);
  CloseHandle(hConsoleEndStdIn);
return exitcode;
}



/* Run cpropep and get the ISP for a given state */
double GetIsp(int ox, int fuel, double cambp, double fmole, double omole)
{
 FILE * fout = fopen("TEmp.pro", "w" );
 fprintf(fout,"Propellant X/Y\n");
 fprintf(fout,"+%d %4.2f m\n",ox,omole);
 fprintf(fout,"+%d %4.2f m\n\n",fuel,fmole);
 fprintf(fout,"FR \n");
 fprintf(fout,"+chamber_pressure      %4.2f atm \n",cambp/14.7);
 fprintf(fout,"+exit_pressure         1   atm  \n");
 fclose(fout);
Execprocess();  
char * cp=strstr(Commandbuffer,"Isp/g");
if (cp!=NULL)
{
cp+=6;
while ((*cp) && (*cp!=':')) cp++;
while ((*cp) && (isspace(*cp) || (*cp==':'))) cp++;
while ((*cp) && (!isspace(*cp))) cp++;
while ((*cp) && (isspace(*cp))) cp++;
float ispr=atof(cp);
return ispr;
}

return 0;
}




/* Run cpropep over and over to find the best performing mixture */

double findbestmixture(int Oxidizer, int fuel, double cp)
{
double omole=1.0;
double fmole=1.0;
double dmole=0.5;
double ispl;
double ispm;
double isph;

while (dmole>=0.01) 
{
ispl=GetIsp(Oxidizer,fuel,cp,fmole*(1.0-dmole),omole);
ispm=GetIsp(Oxidizer,fuel,cp,fmole,omole);
isph=GetIsp(Oxidizer,fuel,cp,fmole*(1.0+dmole),omole);
//printf("fmole = %4.6f l=%4.2f m=%4.2f h=%4.2f",fmole,ispl,ispm,isph);
//fprintf(stderr,"%d,%d %4.2f fm= %4.6f %4.2f %4.2f %4.2f",Oxidizer,fuel, cp,fmole,ispl,ispm,isph);


if ((ispl> ispm) && (ispl>isph)) 
 {
  fmole=fmole*(1.0-dmole);
  //fprintf(stderr,"Decrease\n");

 }
else
if ((isph> ispm) && (isph>ispl)) 
 {
  fmole=fmole*(1+dmole);
  //fprintf(stderr,"Increase\n");

 }
else
if ((ispm>=ispl) && (ispm>=isph))
 {
  dmole*=0.5;
  //fprintf(stderr,"Reduce delta= %4.3f\n",dmole);
 }
else
{
fprintf(stderr,"Strange case\n");
}

}

fprintf(stderr,"ox=%d fu = %d cp=%4.2f fmole = %4.6f l=%4.2f m=%4.2f h=%4.2f\n",Oxidizer,fuel, cp,fmole,ispl,ispm,isph);
return fmole;

}


/*
Chamber pressure Ideal Mixture ISP Vac ISP ISP off 5% Density Ae/At  Temp Chamber Temp Throat Temp Exit
*/

const double g=9.81;

void dumpfirst()
{
char * cp=strstr(Commandbuffer,"Code");
if (cp==NULL) return;
while ((*cp) && (*cp!='\n')) cp++;
while((*cp) && isspace(*cp)) cp++;
while((*cp) && isdigit(*cp)) cp++;
while((*cp) && isspace(*cp)) cp++;
for (int i=0; i<25; i++)
	  {
	   printf("%c",*cp);   
		  cp++;
	  }
printf("\n");
while ((*cp) && (*cp!='\n')) cp++;
while((*cp) && isspace(*cp)) cp++;
while((*cp) && isdigit(*cp)) cp++;
while((*cp) && isspace(*cp)) cp++;
for (i=0; i<25; i++)
	  {
	   printf("%c",*cp);   
		  cp++;
	  }
printf("\n");
printf("\"Chamber(psi)\",\"F/O moles\",\"S/L ISP\",\"Vac ISP\",\"5%% mix err Isp\",\"Density g/cm^3\",\"Ae/At\",\"Chamber T(K)\",\"Throat T(K)\",\"Exit T(K)\"\n"); 
}



/* Pull a vaule out of the command buffer , num indicates the 1,23 number etc.. */
double findvalue(const char * cpv, int num)
{
char * cp=strstr(Commandbuffer,cpv);
if (cp!=NULL)
{
cp+=strlen(cpv);
while ((*cp) && (*cp!=':')) cp++;
while ((*cp) && (isspace(*cp) || (*cp==':'))) cp++;

num--;
while(num)
{
while ((*cp) && (!isspace(*cp))) cp++;
while ((*cp) && (isspace(*cp))) cp++;
num--;
}

float ispr=atof(cp);
return ispr;
}
return -9999;
}



void dumpresult(double cp, double ispl, double best_mix)
{
printf("%4.0f,%8.2f,",cp,best_mix);
printf("%6.2f,",findvalue("Isp/g (s)",2));
printf("%6.2f,",findvalue("Ivac (m/s)",2)/g);
printf("%6.2f,",ispl);
printf("%6.2f,",findvalue("Density",1));
printf("%6.2f,",findvalue("Ae/At",2));
printf("%6.2f,",findvalue("Temperature (K)",1));
printf("%6.2f,",findvalue("Temperature (K)",2));
printf("%6.2f\n",findvalue("Temperature (K)",3));
}


/* chamber pressure sto try, 100 to 3000 psi in log steps */
const double cptrial[] = {100.0,140.0,197.0,277.0,389.0,547.0,769.0,1081.0,1519.0,2135.0,3000.0,0.0};

/* cpropep oxidizer numbers to try */
const int oxtrial[] = {
                       686, /*OXYGEN (LIQUID)           */
					   657, /*NITROUS OXIDE             */
					   466, /*H202 100%*/
					   469,	/*H2O2 90%*/
					   467,	/*H20@ 50 %*/
					   630, /*Nitric Acid*/ 
						0};

/* cpropep fuel numbers to try */
const int futrial[] ={ 
					   797, /* RP1 */
					   579,	/*METHANOL*/
					   578, /*Methane */
					   502,	/*ISOPROPYL ALCOHOL         */
					   352,	/*ETHANOL                   */
					   771, /*Propane */
					   457,	/* Hydrogen Liq Cyrogenic */
						0};




int main(int argc, const  char * * argv)
{
int Oxidizer=686;
int fuel = 457;
double cp=1400;

int nox=0;
int nfu=0; 

/* three nested while loops for ox, fuel and chamber pressure */
while(oxtrial[nox])
{
 Oxidizer=oxtrial[nox];
 nfu=0; 
 while(futrial[nfu])
 {
  fuel=futrial[nfu];


	int ncp=0;

	while(cptrial[ncp]!=0)
	{
		cp=cptrial[ncp++];
		double best_mix=findbestmixture(Oxidizer,fuel, cp);

		double ispl=GetIsp(Oxidizer,fuel,cp,best_mix*0.95,1.0);                                                                                              
		double isph=GetIsp(Oxidizer,fuel,cp,best_mix*1.05,1.0);                                                                                              
		double isp=GetIsp(Oxidizer,fuel,cp,best_mix,1.0);                                                                                              

		if (ispl>isph) ispl=isph;

		if (ncp==1) dumpfirst();
		dumpresult(cp,ispl,best_mix);
		//printf("cp = %4.2f Best mix = %4.6f ISP = %4.2f\n",cp,best_mix,isp);
	}
  nfu++;
 }
nox++;
}
return 0;
}


