#include "peg_pic.h"


/**** Calculation of PSI parameters for species "isp" ****/

void srfpar(int isp) {
	int k, i, j;

	for (k=0; k < 2; k++) {
		srf[isp][k] =0;     /* initialization */
	}
	
	if (isp==0) {
		inj_max =0;
	}

	if (Nsec[isp]) {
		if (Nsec[isp]>MAXSRF) {
			puts("Too many types of secondaries (Nsec)\n");
			exit(1);
		}

		for (i=0; i < Nsec[isp]; i++) {
			for (k=0; k<2; k++) {
				Tseec[isp][i][k] /= vscale;
				Ew[isp][i][k] /= Escale[isp];
				E0[isp][i][k] /= Escale[isp];
			}
		}

		if (!reflux) {
			/* No reflection, or reinjection */
			srf[isp][0] =1;

			if (!i_t[isp]) {
				/* "Real" boundary at x=Lx */
				srf[isp][1] =1;
			}
		} else if ((reflux==1) && (!i_t[isp])) {
			srf[isp][1] =1;              /* No reflection, or reinjection at x=Lx */
		}

		for (k=0; k<2; k++) {
			if (srf[isp][k]) {
				j=0;
				
				for (i=0; i < Nsec[isp]; i++) {
					if (seec[isp][i][k] > 1.e-5) {
						j++;
					}
				}
				
				if (!j) {
					srf[isp][k]=0;         /* If gamma < 1e-5, there is no injection */
				}
			}
		}

		if ((!srf[isp][0]) && (!srf[isp][1])) {
			Nsec[isp]=0;
		}
	}

	if (Nsec[isp]) {
		for (i=0; i < Nsec[isp]-1; i++) {
			/* rescale Nsec if corresponding gammas are too low */

			if (((!srf[isp][0])||(seec[isp][i][0]<1.e-5))&&((!srf[isp][1])||(seec[isp][i][1]<1.e-5))) {
				j = Nsec[isp]-1;
				secsp[isp][i] = secsp[isp][j];
				sectype[isp][i]=sectype[isp][j];

				for (k=0; k<2; k++) {
					seec[isp][i][k] = seec[isp][j][k];
					E0[isp][i][k] = E0[isp][j][k];
					injtype[isp][i][k]=injtype[isp][j][k];
					Tseec[isp][i][k]  = Tseec[isp][j][k];
				}

				Nsec[isp]--;
				i--;
			} else {
				for (k=0; k<2; k++) {

					if (!sectype[isp][i]) {
						/* For electron induced secondaries (e->e) E0 > 1 eV */
						if (E0[isp][i][k]*Escale[isp] < 1.) {
							puts("Too low E0 for electron-like secondaries\n");
							exit(1);
						}
					} else if (sectype[isp][i]==1) {
						/* For ion induced secondaries E0= V m/s */
						E0[isp][i][k] = E0[isp][i][k]*Escale[isp]/vscale;
						seec[isp][i][k] *= (vscale*1.e-6);
					} else {
						printf("Code does not know this type of injection, check sectype for isp=%d\n", isp);
						exit(1);
					}
				}
			}  /* end of else */
		}  /* end of for (i=0; i < Nsec[isp]; i++) loop */
	}  /* end of if (Nsec[isp]) */

	for (i=0; i < Nsec[isp]-1; i++) {   /* fixing of the maximal number of */
		for (k=0; k<2; k++) {             /* sec. particle injection types */
			if (injtype[isp][i][k]>inj_max) {
				inj_max= injtype[isp][i][k];
			}
		}
	}

	if (inj_max>0) {
		printf("This type of injection is not known, check injection for isp=%d\n",isp);
		exit(1);
	}

	/* allocate array for sec. particle distribution */
	parvels= (float **)malloc((inj_max+1)*sizeof(float *));
	
	for (i=0; i <= inj_max; i++) {
		parvels[i]= (float *)malloc(VVMAX*sizeof(float));
	}

}
/* END of srfpar() */

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