#include "peg_pic.h"


/*****************   Surface physics   ******************************/
/** Absorption of primary particles and injection of secondary ones */

void surfphys(int iisp, float sigmd, float dum, int k) {
	int   i, j, pp[MAXSRF], gg[MAXSRF]; 
	float mag, En, ew, vt;


	if (Nsec[iisp]>1) {
		/* Choosing randomly the sequence of secondaries */
		for (j=Nsec[iisp]-1; j>=0; j--) {
			gg[j]=j;
		}

		for (j=Nsec[iisp]-1; j>=0; j--) {
			i= frand()*(j + 1);
			pp[j] = gg[i];
			gg[i] = gg[j];
		}
	/* end of if (Nsec[iisp]>1) */
	} else  {
		pp[0]=0;
	}


	for(i=0; i < Nsec[iisp]; i++) {
		if (!sectype[iisp][pp[i]]) {
			/* electron/electron type */
			En = E0[iisp][pp[i]][k];
			ew = Ew[iisp][pp[i]][k]; 
			vt = Tseec[iisp][pp[i]][k];

			if (sigmd < 2) {
				sigmd *=seec[iisp][pp[i]][k];
			} else {
				sigmd = 2.*seec[iisp][pp[i]][k];   /* if 1/cos(Q) > 2 */
			}

			if (dum >= ew) {
				gamma_ee(&mag, dum, sigmd, En); 

				while ((mag > frand()) && (dum > ew)) {                                         /* injection of sec. particle */
					dum -= ew;
					secinj(iisp, secsp[iisp][pp[i]], injtype[iisp][pp[i]][k], &dum, vt, k);   
					mag -=1.;
					
					if (!k) {
						jwall[pp[i]] -= q[pp[i]];
					}
				}
			}
		/* end of the electron/electron type emission */
		} else if (sectype[iisp][pp[i]] == 1) {
			/* ion(H, D, T)/electron type */
			En = E0[iisp][pp[i]][k];
			ew = Ew[iisp][pp[i]][k]; 
			vt = Tseec[iisp][pp[i]][k];

			if (sigmd < 2) {
				sigmd *=seec[iisp][pp[i]][k];
			} else {
				sigmd = 2.*seec[iisp][pp[i]][k];    /* if 1/cos(Q) > 2 */
			}

			if (dum >= ew) {
				gamma_ie(&mag, dum, sigmd, En);

				while ((mag > frand()) && (dum >= ew)) {                                         /* injection of sec. particle */
					dum -= ew;
					secinj(iisp, secsp[iisp][pp[i]], injtype[iisp][pp[i]][k], &dum, vt, k); 
					mag -=1.;
					
					if (!k) {
						jwall[pp[i]] -= q[pp[i]];
					}
				}
			}
		/* end of the ion/electron type emission */
		} else {
			/* "gamma = const" type */
			mag=seec[iisp][pp[i]][k];
			ew = Ew[iisp][pp[i]][k];
			vt = Tseec[iisp][pp[i]][k];

			while ((mag > frand()) && (dum >= ew)) {
				/* injection of sec. particle */
				dum -= ew;
				secinj(iisp, secsp[iisp][pp[i]], injtype[iisp][pp[i]][k], &dum, vt, k);  
				mag -=1.;
				
				if (!k) {
					jwall[pp[i]] -= q[pp[i]];
				}
			}
		} /* end of the "gamma = const" type imission */
	} /* end of for(i=0; i < Nsec[iisp] ... */
}
/* END of SURFPHYS() */


/***********************************************************************/
