/* FFEM++ script for calculating the initial concentration - see BackCalc4.txt

 The concentration is given by solving the diffusion equation with C=Csat on the pit boundary.

 Steps

 1. read the xy coordinates for the pit obtained using the ImageJ pit filter
 2. mesh the region defined by these coordinates
 3. solve the diffusion equation and write the result the file "conc0.txt"


*/

include "constants.txt"; //constants used: PixToM, Dm, Csat


//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 filename = base+"528.txt";


int n;

/* 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];



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

yy[n-1] += topOffset; yy[n-2] += topOffset;


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

xx *= PixToM; yy *= PixToM; 


/* parameterise the 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));

//plot(Th, wait=1);


/* solve the diffusion equation */


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

//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;

Vh tau=1; //(y<midpoint)?ribbonThickness:(tauIntercept+tauSlope*(y-midpoint));

Vh conc0=(y< (0.95*(intercept + slope * x)))?Csat:0; 

problem concentration(conc,v) =
int2d(Th)(1e3*tau*Dm*(dx(conc)*dx(v)+dy(conc)*dy(v)))
+ on(pitSide,conc=Csat)+on(bulkSide,conc=0);

concentration;
//conc=conc0;

{
ofstream f0("conc0.txt");
f0 << conc[] << endl;
}

plot(conc,wait=1,value=1);
