class Gb extends f_xj
{
 Gas1 g[]; //Gas properties
 double A[][]; //Atom
 double b0[];
 int NS;//Gas species number
 int l;//element number
 double n0[];
 double t0[];
 double P;
 double T;
 
public Gb(String gi[],double n0i[],double t0i[],double Pi)
{
 		NS=gi.length;
 		g=new Gas1[NS];
 		n0=new double[NS];
 		t0=new double[NS];
 		for(int i=0;i<NS;i++)
		{g[i]=new Gas1(gi[i]);
		 n0[i]=n0i[i];
		 t0[i]=t0i[i];
		}
		P=Pi;
		int nat=110;
		double B[][]=new double[nat][NS];		
		int nk=0;		
		for(int i=0;i<NS;i++)
		{ for(nk=0;nk<g[i].atomList.length;nk++){B[g[i].atomList[nk].number-1][i]=g[i].atomList[nk].N;}}		
		int natcount=0;
		boolean zeroflag[]=new boolean[110];
		for(int j=0;j<nat;j++)
		{zeroflag[j]=false;for(int i=0;i<NS;i++){if(B[j][i]!=0){zeroflag[j]=true;}};if(zeroflag[j]) natcount++;}
		A=new double[natcount][NS];	
		l=A.length;
		int k=0;
		for(int j=0;j<nat;j++)
		{if(zeroflag[j]){A[k]=B[j];k++;}}
		b0=new double[l];
		for(int ii=0;ii<l;ii++)
		{ for(int ij=0;ij<NS;ij++)
		  { b0[ii]+=A[ii][ij]*n0[ij];}		
        }
        //System.out.println("A="+Matrix.toString(A));
        //System.out.println("B="+Matrix.toString(b0));
        
 }
 
 public void Tgir(double Ti)
 {T=Ti;}
 public void Pgir(double Pi)
 {P=Pi;} 	
 
 double func(double x[])
 {  
	//P bar
	//T degree K
	//nj ,n kmol
	//lambda coefficients of lagrangian multipliers 
    double R=8.3145;
    double P0=1.01325; 
	double n=0;
	double nj[]=new double[NS];
	double lambda[]=new double[l];
	boolean zeroflag[]=new boolean[NS]; 
    for(int i=0;i<NS;i++)
    {nj[i]=x[i];n+=x[i];
    if(nj[i]==0) zeroflag[i]=true;
    else zeroflag[i]=false;
    //System.out.println("nj["+i+"]="+nj[i]+"n="+n);
    }
    for(int i=0;i<l;i++)
    {lambda[i]=x[i+NS];
    //System.out.println("lambda["+(i)+"]="+lambda[i]);
    }   
    double mu[]=new double[NS];
    for(int i=0;i<NS;i++)
    {mu[i]=g[i].gt(T)+R*T*Math.log(P/P0);
     double value=Math.abs(nj[i]/n)<1e-15? 0 :Math.log(nj[i]/n);
    mu[i]+=R*T*value;
    System.out.println("mu["+i+"]="+mu[i]);
    }        
	double G=0;
	for(int j=0;j<NS;j++)
    {G+=mu[j]*nj[j];
    System.out.println("G["+j+"]="+G);
    }
	for(int i=0;i<l;i++)
    { double y=0;
      for(int j=0;j<NS;j++)
      {y+=A[i][j]*nj[j]-b0[i];}
      G+=lambda[i]*y;
      //System.out.println("G="+G);
    }
    //System.out.println("G="+G);
    return G;
 }
}
