///////////////////////////BACKCALCULATION OF METAL ION CONCENTRATION AND POTENTIAL IN FFEM++ ///////

*/
verbosity=0;
include "constants.txt"; //constants used: PixToM, Dm


int dn=5;

//string base = "e:\\46\\n5\\xy304_20_46_a_";
//string base = "e:\\23\\processed\\xy304_20_23_a_";
//string base = "c:\\Program Files\\ImageJ\\xy304_20_12_a_";
//string base = "e:\\46\\n5\\xy304_20_46_a_";
//string base = "e:\\37\\xy316_25_37_a_";
//string base = "c:\\Program Files\\ImageJ\\37\\xy316_25_37_a_";
//string base = "e:\\46\\n5\\xy304_20_46_a_";
string base = "c:\\Program Files (x86)\\ImageJ\\27\\xy304_20_27_a_";


string id="27";

int wfno;
real[int] wmouth(1000);
{
ifstream f(id+"mouth.txt");
	for(int i=0; i<1000; i++)
	f >> wfno >> wmouth[wfno];
}


ofstream foo1(id+"BackCalc72Results.txt");

int fno1,fno2;


real maxconc=0;


for(int fno=528; fno<1000; fno++) {

cout<< "fno="<<fno<<endl;
string s1 = base+"0"+fno+".txt";
string s2 = base+fno+".txt";
string filename = fno < 100 ? s1:s2;


fno1 = fno + dn;

s1 = base+"0"+fno1+".txt";
s2 = base+fno1+".txt";
string filename1 = fno1 < 100 ? s1:s2;



fno2 = fno + 1;

s1 = base+"0"+fno2+".txt";
s2 = base+fno2+".txt";
string filename2 = fno2 < 100 ? s1:s2;


real dt = dn/frameRate; //time interval, s
/*********************************************************************/

real PixToM=0.37e-6;

int n, n1, n2;

/* read in first file */
{
ifstream f(filename);
 f >> n;
}

//add starting point to the end

real[int] xx(n+1), yy(n+1);


{
 ifstream f(filename);
 f >> n;
 for(int i=0; i<n; i++) f >> xx[i] >> yy[i];
}

xx[n]=xx[0]; yy[n]=yy[0];

/* read in the second file */

{
ifstream f(filename1);
 f >> n1;
}

//add starting point to the end

real[int] xx1(n1+1), yy1(n1+1);


{
 ifstream f(filename1);
 f >> n1;
 for(int i=0; i<n1; i++) f >> xx1[i] >> yy1[i];
}

xx1[n1]=xx1[0]; yy1[n1]=yy1[0];



/* read in the third file */

{
ifstream f(filename2);
 f >> n2;
}

//add starting point to the end

real[int] xx2(n2+1), yy2(n2+1);


{
 ifstream f(filename2);
 f >> n2;
 for(int i=0; i<n2; i++) f >> xx2[i] >> yy2[i];
}

xx2[n2]=xx2[0]; yy2[n2]=yy2[0];



xx[0] -= sOffset; xx[n-1] -= sOffset;
xx[n-3] += sOffset; xx[n-2] += sOffset;

xx1[0] -= sOffset; xx1[n1-1] -= sOffset;
xx1[n1-3] += sOffset; xx1[n1-2] += sOffset;

xx2[0] -= sOffset; xx2[n2-1] -= sOffset;
xx2[n2-3] += sOffset; xx2[n2-2] += sOffset;


yy[n-1] += topOffset; yy[n-2] += topOffset;
yy1[n1-1] += topOffset; yy1[n1-2] += topOffset;
yy2[n2-1] += topOffset; yy2[n2-2] += topOffset;


xx[n]=xx[0]; yy[n]=yy[0];
xx1[n1]=xx1[0]; yy1[n1]=yy1[0];
xx2[n2]=xx2[0]; yy2[n2]=yy2[0];


xx *= PixToM; yy *= PixToM; 
xx1 *= PixToM; yy1 *= PixToM; 
xx2 *= PixToM; yy2 *= PixToM;


/* parameterise the first boundary and mesh the region */


func real g(real[int] &p,real t)
{
 int k=floor(n*t), k1=k+1;
 if(k1>n) k1=0;
 real w = n*t-k;
 return(p[k]*(1-w)+w*p[k1]);
}


int pitSide=2, bulkSide=7;
real t1=1.0/n, t2=1.0-4.0/n;

border S1(t=0,1.0/n) {x=g(xx,t); y=g(yy,t); label=1;} //left surface
border S2(t=t1,t2) {x=g(xx,t); y=g(yy,t); label=2;} //pit
border S3(t=1.0-4.0/n,1-3.0/n) {x=g(xx,t); y=g(yy,t); label=3;} //right surface
border S4(t=1.0-3.0/n,1.0-2.0/n) {x=g(xx,t); y=g(yy,t); label=4;} //right side
border S5(t=1.0-2.0/n,1.0-1.0/n) {x=g(xx,t); y=g(yy,t); label=5;} //top
border S6(t=1.0-1.0/n,1.0) {x=g(xx,t); y=g(yy,t); label=6;} //left side

int np=n-4;

border S7(t=0,1) {x=g(xx,t1)*t+g(xx,t2)*(1-t); y=g(yy,t1)*t+g(yy,t2)*(1-t); label=7;}//pit mouth

mesh Th = buildmesh(S2(multnp*(np-1))+S7(ninf));


/* get the pit boundary points */
real[int] px(np), py(np);
real t, t0=1.0/n, delt=(1.0-5.0/n)/(np-1);
px[0]=g(xx,t0); py[0]=g(yy,t0);
for(int i=1; i<np; i++) {t=t0+i*delt; px[i]=g(xx,t); py[i]=g(yy,t);}


/* calculate the boundary velocity */

real[int] vel(np-1);

real[int] dxy(2), normal(2), PP(2), p1(2), p2(2), b(2);
real r, rmin, ar, armin, ss, Det, w;
real[int,int] A(2,2);
bool found;
int jmin;

for(int nn=0; nn<(np-1); nn++) {



	vel[nn]=0;

	
	PP[0] = (px[nn+1]+px[nn])/2.0;
	PP[1] = (py[nn+1]+py[nn])/2.0;
	
	//normal
	dxy[0] = px[nn+1]-px[nn];
	dxy[1] = py[nn+1]-py[nn];
        normal[0] = dxy[1]; normal[1]= -dxy[0];
	ss = 0;
	for(int i=0; i<2; i++) ss += normal[i]^2; ss = sqrt(ss);
  	for(int i=0; i<2; i++) normal[i] /= ss;


	found = false;
	armin = Infinity;

       
	for(int j=2; j<(n1-3); j++)
	{


		p1[0] = xx1[j-1]; p1[1] = yy1[j-1];
		p2[0] = xx1[j]; p2[1] = yy1[j];

		
		A = [[normal[0],p2[0]-p1[0]],[normal[1],p2[1]-p1[1]]];
		b = [p2[0]-PP[0],p2[1]-PP[1]];
		Det = A(0,0)*A(1,1)-A(0,1)*A(1,0);
		if(Det!=0) {
			r = (A(1,1)*b[0]-A(0,1)*b[1])/Det;
			w = (-A(1,0)*b[0]+A(0,0)*b[1])/Det;

			if(w>=0 & w<=1) 
 				{
				found = true; ar = abs(r);
				if(ar<armin) {armin = ar; rmin = r; jmin=j;}
				}
			}

	}



if(found) if(rmin>0) vel[nn] = rmin/dt;

}



/*
Interpolate the boundary velocity...
*/
real tol=PixToM;
func real fv(real X, real Y)
{
 int k1= -1;
 bool okx,oky;
 for(int k=0; k<(np-1); k++) {
  okx = px[k]<= X+tol & X<= px[k+1]+tol;
  okx = okx | (tol+px[k]>= X & tol+X>= px[k+1]);
  oky = (py[k]<= Y+tol & Y<= py[k+1]+tol);
  oky = oky | (tol+py[k]>= Y & tol+Y>= py[k+1]);
  if(okx & oky) {k1=k; break;}
  }
 return k1<0 ? 0:vel[k1];
}



fespace Vh(Th,P1);
Vh phi, conc, conc0, v;


{
int m;
ifstream f0("conc0.txt");
f0 >> m;

real[int] c0(m);
for(int i=0; i<m; i++) f0 >> c0(i); 
conc0[]=c0;
}


//top of domain
real top=(yy[n-1]+yy[n-2])/2.0;

//these define the metal surface
real slope = (yy[n-3]-yy[0])/(xx[n-3]-xx[0]), intercept=yy[0]-slope*xx[0];
real midpoint = (yy[n-3]+yy[0])/2.0;

resistance = 1000/(0.025+0.21*wmouth[fno]*1e3)/BulkConductivity; //convert w to mm!!!!;

//resistance=10000*100e-6/wmouth[fno];

//resistance=4141.4590164+0.4346247/wmouth[fno];


real Current=ribbonThickness*int1d(Th,2)(velToi*fv(x,y));
real IR =resistance*Current;
cout<<"Resistance (Ohm)="<< resistance << " Current (uA)="<<Current*1e6<<" IR="<<IR<<endl;

conc=conc0;
real alpha=2e-2;//1e-2;
Vh Dc,c0,cb,delc;
//Vh tau=(y<midpoint)?ribbonThickness:(tauIntercept+tauSlope*(y-midpoint));
Vh tau=1;
Vh Nsalt;

//Dc=Dm*(1-(wmouth[fno]/(width[fno]*0.37e-6))); 

real fudge=0.418;
Dc=Dm*fudge;

real dt1=1/frameRate;

/********************* solve the coupled equations implicitly by iteration *****************/
for(int iter=1; iter<10; iter++) {
	c0=conc;

/* options for diffusion coefficient */
//Dc=1.29e-9/(1+0.312*conc); //Gaudet
//Dc=1.16e-9/(1+0.69*conc); //Steinsmo and Isaacs
//real Dc=4.18e-10;
//Dc=1.0e-9/(1+1.9*conc)/1.5;
//Dc=Dm/(1+0.312*conc);

/* options for conductivity */
//Vh sigma=(y< (0.999*(intercept + slope * x)))?PitConductivity:BulkConductivity; 
Vh sigma=(1+1/2.2)*Dm*zF2RT*conc*1e3+BulkConductivity; //cf White pot2.f
//Vh sigma=BulkConductivity;


problem potential(phi,v) =
int2d(Th)(tau*sigma*(dx(phi)*dx(v)+dy(phi)*dy(v)))
-int1d(Th,pitSide)(tau*velToi*fv(x,y)*v)
+ on(bulkSide,phi=IR);


potential;

//Nsalt = (conc0<Csat)? 0:alpha*(conc-Csat);
Nsalt = 0; //steady-state salt film

problem concentration(conc,v) =
int2d(Th)(tau*conc*v/dt1+Dc*tau*(dx(conc)*dx(v)+dy(conc)*dy(v)))
+int2d(Th)(tau*Dc*zF/RT*conc*(dx(phi)*dx(v)+dy(phi)*dy(v))) //migration term!
-int1d(Th,pitSide)(tau*1e-3*(velToN*fv(x,y)-Nsalt)*v)
-int2d(Th)(tau*conc0*v/dt1)
+ on(bulkSide,conc=0);

concentration;

delc=abs(conc-c0);

}
/****************************end of iterations *********************************/


if(conc[].max>maxconc) maxconc=conc[].max;

cout << "err=" << delc[].max <<endl;
cout << "total metal=" << int2d(Th)(1e3*tau*conc) << endl;


plot(conc,wait=0,value=true,fill=1,aspectratio=2,cmm="Frame No="+fno,ps=id+"_sf+migOn_"+fno+".eps");



/* parameterise the second boundary and mesh the region */


func real g2(real[int] &p,real t)
{
 int k=floor(n2*t), k1=k+1;
 if(k1>n2) k1=0;
 real w = n2*t-k;
 return(p[k]*(1-w)+w*p[k1]);
}





t1=1.0/n2; t2=1.0-4.0/n2;

border SS1(t=0,1.0/n2) {x=g2(xx2,t); y=g2(yy2,t); label=1;} //left surface
border SS2(t=t1,t2) {x=g2(xx2,t); y=g2(yy2,t); label=2;} //pit
border SS3(t=1.0-4.0/n2,1-3.0/n2) {x=g2(xx2,t); y=g2(yy2,t); label=3;} //right surface
border SS4(t=1.0-3.0/n2,1.0-2.0/n2) {x=g2(xx2,t); y=g2(yy2,t); label=4;} //right side
border SS5(t=1.0-2.0/n2,1.0-1.0/n2) {x=g2(xx2,t); y=g2(yy2,t); label=5;} //top
border SS6(t=1.0-1.0/n2,1.0) {x=g2(xx2,t); y=g2(yy2,t); label=6;} //left side

int np2=n2-4;

border SS7(t=0,1) {x=g2(xx2,t1)*t+g2(xx2,t2)*(1-t); y=g2(yy2,t1)*t+g2(yy2,t2)*(1-t); label=7;}//pit mouth

mesh Th2 = buildmesh(SS2(multnp*(np2-1))+SS7(ninf));

/* interpolate the concentration onto the mesh */



fespace Vh2(Th2,P1);


matrix IV=interpolate(Vh2,Vh);

Vh2 conc2;
conc2[] = IV*conc[];


//plot(conc2,value=true);

/* save the results for the next time step */

{
ofstream f1("conc0.txt");
f1 << conc2[] << endl;
}


/* output results */
real xp, yp;
for(int nn=0; nn<(np-1); nn++) {
	xp = (px[nn+1]+px[nn])/2.0;
	yp = (py[nn+1]+py[nn])/2.0;


foo1 <<  fno << " " << xp << " " << yp << " " << velToi*vel[nn] << " " << conc(xp,yp) << " " << phi(xp,yp) << endl;
}


}// end of loop

cout << "Maximum concentration=" << maxconc << endl;
