
#include <nag.h>
#include <stdio.h>
#include <nag_stdlib.h>
#include <math.h>
#include <nagd01.h>
#include <nagx01.h>
#include <stdlib.h>
#include <string.h>
#include <nags.h>
#include <fcntl.h>
#define NDIM 2

static double QU1( Integer ndim,  double var[]);
static double QU2( Integer ndim,  double var[]);
static double QU3( Integer ndim,  double var[]);
static double QU4( Integer ndim,  double var[]);
static double GAU(double x);

const double pi=3.1415926;
const double qe=1.602177e-19*3e9;
double alpha, k, kx, ky, lam_e, xv, x0, theta, psi, beta, gam, dum, D;
double a, b, sigma_x, sigma_y;

typedef struct {double r, i;} complex;
typedef struct {complex x, y, z;} vector;

vector Vcreate(double xr, double xi, double yr, double yi, double zr, double zi);
vector Vadd(vector v1, vector v2);
vector Vmultiply(vector v, complex c);
vector Vconjugate(vector v);
complex Vdot(vector v1, vector v2);

complex Ccreate(double r, double i);
complex Cadd(complex a, complex b);
complex Cmultiply(complex a, complex b);
complex Cdivide(complex a, complex b);
complex Cconjugate(complex a);
vector G1,G2, G, nv, nvp, nvv;
complex G1x, G1y, G1z, G2x, G2y, G2z, Gx, Gy, Gz;
complex a1, a2, a1t, a2t, f5c;

double  xval[44], yval[44], wval[44], derval[44];

int main()
{
const double pi=3.1415926;
const double qe=1.602177e-19*3e9;
char line[200], ans, ans1, ans2;
char outfile_name[364];
char infile_name1[364];
char infile_name2[364];
char infile_name3[364];
char infile_name4[364];
char infile_name[364];
FILE *in_file;
FILE *out_file;
Integer ndim=NDIM, minpts, maxpts;
int i, ii, j, l, m, n, liw, ic, flag, ind, indend, iend, istart;
int fcount, fnum;
int jstart,jj,ij, kk, negcount;

/* grating parameters below */
int grat;
double lgr, frac, alpha1, alpha2, hi, el, el1, el2, wid;
double per1, per2, per3;    /* record of grating periods used */
/* beam parameters below  */ 
int philmt;
double y0, y0_av, charlen, nemit, emit, x_rad, n_e, n_e_t;
double sigma_tdum, x, apb, ssigma_x;
extern double A,B, x0, sigma_x, sigma_y, beta, gam;
/* optical system parameters below */ 
int n0, int_thet_1, int_thet_2, phistep;
double r, r2, domeg_m, thet_1, thet_2;
/* radiation parameters */
double theta, phi, phi0, lam, lam_e, aven, f_y_c, f_y_s;
/* general parametrs */  
double gg,ggh;
/* integration parameters below */
double ll[2], ul[2];                           /* limits for the y,z integral*/ 
double lol, upl, eps, acc, res1, res2, res3, res4 ;
double epsabs, epsrel, abserr;
double ff, f1, f2, f5, sf3, z;  
double incans, cohans, err;
double temp1, temp2, temp3, temp4, sum , percent, sum_th;
double x0_bin[50], inc_bin[50], coh_bin[50];
extern double xval[44], yval[44], wval[44], derval[44];
double  nustart, numin, numax, val0, rhomin, rhomax;
double  error, monocheck, normfactor, shiftfactor, tstart;
double slp[4], slph[4], dumm[3];
/* input-output arrays listed below */
double f4[179], f_t[179], thet[179], f_l_re[179];
double bin_inp[179][4], outbin_1[171][10], outbin_2[171][10];
double rbin_inc[179][10], rbin_coh[179][10], bin_1[179][10], bin_2[179][10];
double bin_11[179][5], bin_22[179][5];
double dum70[1010][2], plot_bin[1000][2];
double bin_f[1010][1010];
double x_cor[1010], y_cor[1010], nu_bin1[1010], res_bin1[1010];
double time[1010], timeprof[1010], timeerr[1010];

int goodpoints[4];                         /* counts valid points in each data file*/
Nag_QuadProgress QP;
Nag_QuadSubProgress QPSUB1,QPSUB2;
Nag_TrigTransform WT_FUNC;
static NagError fail;

printf("\n"); printf("\n"); printf("\n");
printf("                  NEW Kramers-Kronig reconstruction, based on a FINITE WIDTH grating          \n");
printf("\n");
printf("                 starting from a minimum of 11 MEASURED energy data points & max. of 44          \n");
printf("\n");
printf("                this version rejects any bad (negative) points             \n");
printf("\n");
printf(" NB. scale factor f1 DOES NOT include n_e, which has been moved to S_inc & S_coh \n");
printf("\n");
printf("       this version extrapolates over the region 0.1-50THz  \n");
printf("\n");
printf("                    This code is INTENSIVE in CPU time\n"); 
printf("\n"); printf("\n");

wid=20;             /* grating width, in mm*/
lgr=40;            /* grating length*/
r=230;          /* distance of Winston cone entrance from beam axis, in mm */
r2=21;         /* Winston cone entrance diameter, in mm. Max. entry angle for cone is 6.3 deg */

domeg_m=pi*(r2/2)*(r2/2)/pow(r,2); 
m=1;                                                                /*default order 1*/
flag=0;
if (!flag) printf("Default order is 1. Do you want to change it? yes(y) or no(n) \n");
line[0]= 'x';
do { 
	if (line[0] != 'x') printf(" ");
	if (fgets(line, 200, stdin) == NULL) { printf("\nErr: fgets.\n"); exit(1); }
	}
	while (line[0] != 'y' && line[0] != 'n'); 
ans = line[0];
if (ans=='y')
   {printf("Enter order required; default is order 1 \n");
    scanf("%d",&m);
    if (m<=0) m=1;  }
printf(" \n");

phistep=1;                                                        /* scan in steps of 1deg*/
philmt=6;                                            /* max. accepted azimuthal angle=5, hence 6 values*/

                              /*beam parameters  */
printf("Enter relativistic factor gamma \n");
scanf("%lf",&gam);
beta=sqrt(pow(gam,2)-1)/gam;
printf("Type normalized emittance of the beam in mm.mrad \n");
scanf("%lf",&nemit);
emit=1e-3*nemit/(beta*gam);                                  /*converted to mm.rad*/
esc20:printf("Enter nominal position of the beam above grating, in mm \n");
scanf("%lf",&x0);
printf("\n");
esc24:printf("Enter sigma_x(in mm) of Gaussian beam at waist, at the centre of grating \n");
scanf("%lf",&sigma_x);
printf(" For this sigma_x: \n");
printf(" 0.50 of the beam is within a radius of "); printf("%-4.3f",0.6749*sigma_x); printf(" mm \n");
printf(" 0.90 of the beam is within a radius of "); printf("%-4.3f",1.6450*sigma_x); printf(" mm \n");
printf(" 0.99 of the beam is within a radius of "); printf("%-4.3f",2.5733*sigma_x); printf(" mm \n");
printf(" I assume the x-radius to be "); printf("%-4.3f",1.6450*sigma_x); printf(" mm \n");
y0=1.6450*sigma_x;
charlen=pow(y0,2)/emit;
sf3=0;   
for (j=1; j<7; j++)                           /*first calculate beam profile over grating*/
    {z=(j-1)*lgr/10;
    x_rad=y0*sqrt(1+pow(z/charlen,2));                           /*varying beam half-width*/
    sf3=sf3+x_rad;}
y0_av=sf3/6;                                  /*average value of radius over 1/2 grating*/
printf("Average value of sigma_x from centre to effective edge of grating is "); printf("%-4.3f",y0_av/1.645); printf(" mm\n");
printf("Enter sigma_y(in mm) of Gaussian beam at waist, at the centre of grating \n");
scanf("%lf",&sigma_y);
printf(" For this sigma_y: \n");
printf(" 0.50 of the beam is within a radius of "); printf("%-4.3f",0.6749*sigma_y); printf(" mm \n");
printf(" 0.90 of the beam is within a radius of "); printf("%-4.3f",1.6450*sigma_y); printf(" mm \n");
printf(" 0.99 of the beam is within a radius of "); printf("%-4.3f",2.5733*sigma_y); printf(" mm \n");
printf(" I assume the y-radius to be "); printf("%-4.3f",1.6450*sigma_y); printf(" mm \n");

lol=x0-5*sigma_x;                                       /* GD modified 17/9/10*/
if (lol<0) lol=1.001*hi;
upl=x0+5*sigma_x;
epsabs=1.0e-12;
epsrel=1.0e-4;
liw=500;
d01ajc(GAU,lol,upl,epsabs,epsrel,liw,&res1,&abserr,&QP,&fail);
res1=res1/(sigma_x*sqrt(2*pi));
printf("For a sigma_x of "); printf("%-4.2e",sigma_x);
printf("mm and x0="); printf("%-4.3f",x0); printf("mm, "); printf("%-4.2f",100*res1);
printf(" percent of the beam is above the grating \n");
printf("\n");
NAG_FREE(QP.sub_int_beg_pts);
NAG_FREE(QP.sub_int_end_pts);
NAG_FREE(QP.sub_int_result);
NAG_FREE(QP.sub_int_error);

printf("Enter total number of electrons in the bunch \n");
scanf("%le",&n_e_t);
printf("since only "); printf("%-4.1f",100*res1); printf(" percent is above the grating, I am setting N_e=");
printf("%le",res1*n_e_t); printf("\n");
n_e=n_e_t*res1;

f1=2*pi*qe*qe*1e-7;
printf("For a bunched beam the  scale factor f1="); printf("%le",f1); printf(" J.cm \n");

printf(" How many files am I going to read; min=1, max=4, default=1 \n");
scanf("%1d", &fnum);
if (fnum>=5 || fnum<=0) fnum=1;
if (fnum==1)
{ printf(" name of file? \n"); scanf("%s",&infile_name1);
  in_file=fopen(infile_name1,"r");}
else
if (fnum==2)
{ printf(" name of first file? \n"); scanf("%s",&infile_name1);
  printf(" name of second file? \n"); scanf("%s",&infile_name2);}
else
if (fnum==3)
{ printf(" name of first file? \n"); scanf("%s",&infile_name1);
  printf(" name of second file? \n"); scanf("%s",&infile_name2);
  printf(" name of third file? \n"); scanf ("%s", &infile_name3);}
else
{ printf(" name of first file? \n"); scanf("%s",&infile_name1);
  printf(" name of second file? \n"); scanf("%s",&infile_name2);
  printf(" name of third file? \n"); scanf("%s", &infile_name3);
  printf(" name of fourth file? \n"); scanf("%s", &infile_name4);}

j=1;
for (j=1; j<5; j++)
{ goodpoints[j]=0;}  

fcount=1;                                              /*start counting files*/
ent1: printf("\n");
if (fcount==1)
{ in_file= fopen(infile_name1, "r");
  printf(" reading the file called "); printf("%s",infile_name1); printf("\n");}
else if (fcount==2)
{ in_file= fopen(infile_name2, "r");
  printf(" reading the file called "); printf("%s",infile_name2); printf("\n");}
else if (fcount==3)
{ in_file= fopen(infile_name3, "r");
  printf(" reading the file called "); printf("%s",infile_name3); printf("\n");}
else
{ in_file= fopen(infile_name4, "r");
  printf(" reading the file called "); printf("%s",infile_name4); printf("\n");}
if (in_file==NULL)
  {printf("this file does not exist \n");
   printf(" type 1 to try again, anything else to exit\n");
   scanf("%1d",&ans);
   if (ans==1) goto ent1;
   exit(8);
  };
                    /*read 12 lines of data */
i=0;
for ( i=0; i<12; i++)
{      ii=0;  
       for (ii=0; ii<3; ii++)
       { fscanf(in_file,"%lf ",&bin_inp[i][ii]);}           
}; 
fclose(in_file);
negcount=0;                            /*counts the negative values in data file, for rejection*/
printf("the following data were extracted:\n");
printf("theta\tenergy\t\tweight \n");
i=0;
for ( i=0; i<11; i++)
{        
   for (ii=0; ii<3; ii++)
   {if (ii==0) printf("%5.1f \t",bin_inp[i][ii]); 
    else  printf("%6.3e \t", bin_inp[i][ii]);}  
    printf("\n");
    if (i==10) printf("theta\tenergy\t\tweight \n");
    if (bin_inp[i][1]<=0) negcount=negcount+1;          /* detect negative values*/
} 
printf("\n");
el=bin_inp[11][0];
goodpoints[fcount]= 11-negcount;
printf("This file has "); printf("%2d", goodpoints[fcount]);
printf(" good data points"); printf("\n");
printf(" arising from a grating with period= ");
printf("%5.3f",el); printf(" mm \n");

grat=2;                             /* fix the grating type used in these experiments*/    
printf("Enter first blaze angle of grating in degrees \n");
scanf("%lf",&alpha1);
alpha1=alpha1*pi/180;
frac=pow(cos(alpha1),2);
printf("Fraction of period taken by first blaze is= "); printf("%-4.3f", frac, "\n");
el1=el*frac;
el2=el-el1;
hi=fabs(el1*tan(alpha1));                  /*height of grating indentation*/    
alpha2= -(0.5*pi- alpha1);
printf("\n");
printf("For this grating the second blaze angle is "); printf("%-4.3f", alpha2*180.0/pi);
printf(" degrees\n");
printf("and the indentation height is "); printf("%-4.3f", hi); printf(" mm\n");
printf("\n");
f2=100/pow(el,2);

printf(" start recovery of rho^2 from the data points...\n");	 
                    /*estimate of grating factor R^2  and of the coherent & incoherent integrals*/

/*flag=0;
if (!flag) printf("Do you want a narrow or wide PHI scan? Enter narrow(n) or wide(w)\n");
line[0]= 'x';
do { 
    if (line[0] != 'x') printf(" ");
    if (fgets(line, 200, stdin) == NULL) { printf("\nErr: fgets.\n"); exit(1); }
   }
while (line[0] != 'n' && line[0] != 'w'); 
ans = line[0];
if (ans=='n')
{printf("Will scan up to phi=7, in steps of 1 \n");
 phistep=1;}
else
if (ans=='w')
{printf("Will scan up to phi=70, in steps of 10 \n");
phistep=10;}*/
    
/* set the y-limits for the y-z integrations*/
ll[0]= 0.0; ul[0]= wid/2;                  /*y-integral; wid is the grating width */
maxpts= 5000;
eps=1e-4;                                /* acceptable error*/
  
i=(int)(alpha1*180/pi);                       /* no point in angles shallower than the blaze angle*/
for (i=(int)(alpha1*180/pi); i<171; i++)
{ thet[i]=i;                                 /*scan angles from alpha1-170 deg.  */
  theta=thet[i]*pi/180;
  lam=el*(1/beta-cos(theta))/m;      /*lam is the wavelength of the emitted radiation*/
  k= 2*pi/lam;
  if (i==10||i==20||i==30|| i==40||i==50||i==60 || i==70 || i==80||i==90 || i==100 || i==110 || i==120
    ||i==130 || i==140 || i==150 || i==160 || i==170)    
  {printf("%-.2e  ", (theta*180/pi)); printf("\n");}
  ii=0;
  for (ii=0; ii<8; ii++)
  {phi0=phistep*ii*pi/180;         
   kx=k*sin(theta)*cos(phi0);
   ky=k*sin(theta)*sin(phi0);
   lam_e=lam*beta*gam/(2*pi*sqrt(1+pow((beta*gam*sin(theta)*sin(phi0)),2)));  /*evanescent w/l */
   ff= 1/(pi*el);
/*  N.B. all distances from the base of the grating teeth.   */

                       /* calculate for a range of x0 values and store for integration */ 
   lol= x0-5*y0;
   if (lol<=0) lol=1.001*hi;
   upl= x0+5*y0;
   indend=20;                     /* number of steps in x, i.e. in 0.5sigma steps */
   ind=0;
   for (ind=0; ind<indend+1; ind++)
   {xv= lol+ ind*0.5*sigma_x;      /* proceed in steps of 0.5sigma  */   
/*                         first facet                           */
    res1=res2=res3=res4=0.0;
    ll[1]=0.0; ul[1]=el1;                   /* z limits for 1st facet */
    alpha=alpha1;
    psi=0;
    dum=0.0;                          /* dum accounts for diff. expressions for impact param. for the two facets */
    D= k*(1/beta-cos(theta))-kx*tan(alpha);
    temp1=temp2=temp3=temp4=0.0;
    minpts=1;
    d01fcc(ndim, QU1, ll, ul, &minpts, maxpts, eps, &res1, &acc, &fail);  /* real part of the int. for the x&z components */
    minpts=1;
    d01fcc(ndim, QU2, ll, ul, &minpts, maxpts, eps, &res2, &acc, &fail);   /* imag. part */
    G1x=Ccreate((ff*res1*tan(alpha1)), (ff*res2*tan(alpha1)));           /*changed 17/9/10 to comply with gfw25t.c*/
    G1z=Ccreate((ff*res1), (ff*res2));                                      /*changed 17/9/10*/
    
    temp3=temp4=0.0;
    minpts=1;
    d01fcc(ndim, QU3, ll, ul, &minpts, maxpts, eps, &res3, &acc, &fail);  /*real part for the integr. of y component */
    minpts=1;
    d01fcc(ndim, QU4, ll, ul, &minpts, maxpts, eps, &res4, &acc, &fail);  /*imag. part for the y-integral*/
    G1y=Ccreate((ff*res3*tan(alpha1)), (-ff*res4*tan(alpha1)));            /*changed 17/9/10*/

/*                    second facet,including phase correction psi             */

    res1=res2=res3=res4=0.0;
    ll[1]=el1; ul[1]=el;                   /* z limits for 2nd facet */
    alpha=alpha2;
    psi=2*pi*el1/el;
    dum= el*tan(alpha2);          /* dum accounts for diff. expressions for impact param. for the two facets */
    D= k*(1/beta-cos(theta))-kx*tan(alpha);
    temp1=temp2=temp3=temp4=0.0;
    minpts=1;
    d01fcc(ndim, QU1, ll, ul, &minpts, maxpts, eps, &res1, &acc, &fail);    
    minpts=1;
    d01fcc(ndim, QU2, ll, ul, &minpts, maxpts, eps, &res2, &acc, &fail);                
    G2x=Ccreate((ff*res1*tan(alpha2)), (ff*res2*tan(alpha2)));               /*changed 17/9/10 to comply with gfw25t.c*/
    G2z=Ccreate((ff*res1), (ff*res2));                                            /*changed 17/9/10*/
    
    temp3=temp4=0.0;
    minpts=1;
    d01fcc(ndim, QU3, ll, ul, &minpts, maxpts, eps, &res3, &acc, &fail);
    minpts=1;
    d01fcc(ndim, QU4, ll, ul, &minpts, maxpts, eps, &res4, &acc, &fail);
    G2y=Ccreate((ff*res3*tan(alpha2)), (-ff*res4*tan(alpha2)));                   /*changed 17/9/10*/         
 /* combine the 2 facets...   */   
    Gx= Cadd(G1x, G2x);
    Gy= Cadd(G1y, G2y);
    Gz= Cadd(G1z, G2z);
/* and create the complex vector G    */
    G= Vcreate( Gx.r, Gx.i, Gy.r, Gy.i, Gz.r, Gz.i);
    nv= Vcreate( (sin(theta)*cos(phi0)), 0, (sin(theta)*sin(phi0)), 0, cos(theta), 0);  /*dir. unit vector*/ 
    nvp= Vcreate( (cos(theta)*cos(phi0)), 0, (cos(theta)*sin(phi0)), 0, -sin(theta), 0); /*1st pol. unit vector*/
    nvv= Vcreate( -sin(phi0), 0, cos(phi0), 0, 0, 0);                                    /*2nd pol. unit vector*/ 
      
/*    first polarization e1, i.e vector nvp, in plane of n,z. Need G.nvp                                   */    
    a1=Vdot(G,nvp);
    a1t= Cmultiply(a1, Cconjugate(a1));        /*square of magn. in first polarisation*/ 
/*    second polarization e2, i.e. vector nvv, vertical to n and z                                         */
    a2=Vdot(G,nvv);
    a2t= Cmultiply(a2, Cconjugate(a2));        /*square of magn. in second polarisation*/ 
    f5c=Cadd(a1t,a2t);                /*total */
    f5= f5c.r;
    x0_bin[ind]= xv;
    inc_bin[ind]= f5*exp(-(xv-x0)*(xv-x0)/(2*sigma_x*sigma_x));
    coh_bin[ind]= sqrt(f5)*exp(-(xv-x0)*(xv-x0)/(2*sigma_x*sigma_x));                            
    }                              /*end of x0 scan  */ 

/* numerical integration over x0 follows, to find the coherent and incoherent integrals*/
/* the two arrays below contain the incoherent and coherent parts of the x-integrals */
/* arranged so that in col 0 data for phi=0, in 1 for phi=1(10), in 7 for phi=7(70)*/
    d01gac(indend, x0_bin, inc_bin, &incans, &err, &fail);
    rbin_inc[i][ii]= incans/(sqrt(2*pi)*sigma_x);    
    d01gac(indend, x0_bin, coh_bin, &cohans, &err, &fail);
    rbin_coh[i][ii]= cohans*cohans/(2*pi*sigma_x*sigma_x);
   }                             /* end of ii (phi) scan */
    
 }                               /* end of i (theta) scan */  
printf(" Finished with the calculation of R^2 \n");
printf("\n");

          /*next, the incoherent and partially coherent components of the radiated energy */
	  /* these will be stored in bin_1 & bin_2, respectively */

i=(int)(alpha1*180/pi);
for (i=(int)(alpha1*180/pi); i<171; i++)
{ ii=0;
  for (ii=0; ii<philmt; ii++)
  { phi0=phistep*ii*pi/180;                             /* phi scanned up to 5deg., i.e. 6 values*/
    thet[i]=i;                                              /*scan theta from 10 to 170 deg.  */
    theta=thet[i]*pi/180;
    lam=el*(1/beta-cos(theta))/m;    
    lam_e=lam*beta*gam/(2*pi*sqrt(1+pow((beta*gam*sin(theta)*sin(phi0)),2)));
    kx=2*pi*sin(theta)*cos(phi0)/lam;
    ky=2*pi*sin(theta)*sin(phi0)/lam;
    f4[i]=pow(m,2)*pow((beta/(1-beta*cos(theta))),3);                     
    f_y_c=exp(-pow((ky*sigma_y),2)/2);
    f_y_s=0;
    f_t[i]=(f_y_c*f_y_c+f_y_s*f_y_s)*rbin_coh[i][ii];             /*transverse coherence factor*/
    bin_1[i][0]=i;
    bin_1[i][ii+1]=f1*f2*f4[i]*n_e*rbin_inc[i][ii];   /*incoherent; in col.1 data for phi=0, in 2 for phi=1, in 8 for phi=7*/
    bin_2[i][0]=i;
    bin_2[i][ii+1]=f1*f2*f4[i]*n_e*n_e*f_t[i];        /*coherent; in col.1 data for phi=0, in 2 for phi=1, etc*/    
  }  
}

/*NB bin_1 has the incoherent component and bin_2 the coherent one*/

i=(int)(alpha1*180/pi);
for ( i=(int)(alpha1*180/pi); i<171; i++)
{ sum=0.0; ii=2;
  for (ii=2; ii<philmt+1; ii++)
  {sum= sum+ 2*bin_1[i][ii];}               /* start from col. index 2(phi=1) and double the sum to account for +-phi */
  bin_1[i][9]= (bin_1[i][1]+sum)/(2*philmt-1);                 /* average over phi=0-5 and put av. value in col. 9*/
}
i=(int)(alpha1*180/pi);
for ( i=(int)(alpha1*180/pi); i<171; i++)
{ sum=0.0; ii=2;
  for (ii=2; ii<philmt+1; ii++)
  {sum= sum+ 2*bin_2[i][ii];}
  bin_2[i][9]= (bin_2[i][1]+sum)/(2*philmt-1);                 /* average over phi=0-5 and put av. value in col. 9*/
}

                /* the following section averages over the accepted theta range, for each port */
i=0;
for (i=0; i<11; i++)
{
    thet[i]=40+i*10;
    theta=thet[i]*pi/180;                                              /* change to radians*/
   /*thet_1 and thet_2 define the accepted theta range for a given observation angle*/
   /* as determined by the Winston cone properties*/
    thet_1= theta+ 6*pi/180;
    thet_2= theta- 6*pi/180;
    if (thet_1<0)   thet_1=pi+thet_1;
    if (thet_2<0)   thet_2=pi+thet_2;
    int_thet_1=(int)180*thet_1/pi;
    int_thet_2=(int)180*thet_2/pi;
    if (180*thet_1/pi-int_thet_1>=0.5) int_thet_1++;    
    if (180*thet_2/pi-int_thet_2>=0.5) int_thet_2++;   
    outbin_1[i][0]=theta*180/pi;
    outbin_1[i][1]=int_thet_2;
    outbin_1[i][2]=int_thet_1;   
    outbin_2[i][0]=theta*180/pi;
    outbin_2[i][1]=int_thet_2;
    outbin_2[i][2]=int_thet_1; 
/*  n0 is total no. of angles accepted */
    n0=int_thet_1-int_thet_2;
    if (n0<=0) n0=-n0;      
    if (int_thet_1<=int_thet_2) jstart= int_thet_1;
    else
    jstart=int_thet_2;    
    sum_th=0;
    j=1;  
    for (j=1; j<n0+2; j++)                       /* modified May 08 to make it equal to 13 values*/
      {
        sum_th= sum_th+ bin_1[jstart+j-1][9];
      };
    aven=sum_th/(n0+1);                                            /*take average over detected angles*/
    outbin_1[i][3]=aven;    
    outbin_1[i][4]= outbin_1[i][3];                      /* redundant, may be useful later*/
    if (int_thet_1<=int_thet_2) jstart= int_thet_1;
    else
    jstart=int_thet_2;    
    sum_th=0;
    j=1;  
    for (j=1; j<n0+2; j++)
      {
        sum_th= sum_th+ bin_2[jstart+j-1][9];
      };
    aven=sum_th/(n0+1);                                            /*take average over detected angles*/
    outbin_2[i][3]=aven;    
    outbin_2[i][4]= outbin_2[i][3];                      /* redundant, may be useful later*/ 
};
printf("\n");
                                    /* finished with averaging. Results are in outbin_1 & outbin_2 */
if (fcount==1) istart=0;
else if (fcount==2) istart=goodpoints[1]; else if (fcount==3) istart=goodpoints[1]+goodpoints[2];
else istart=goodpoints[1]+goodpoints[2]+ goodpoints[3];
printf("good points= "); printf("%2d", goodpoints[fcount]); printf("\n");
printf("Angle     incoh.   part_coh.    rho^2    diff. en\n");
printf("         J/sr/cm    J/sr/cm                         \n");
i=0;
j=0;                              
for (i=0; i<11; i++)
{  thet[i]=40+i*10;              
   theta=thet[i]*pi/180;
   lam=el*(1/beta-cos(theta))/m;
   if (bin_inp[i][1]>=0)
   {
    f_l_re[j]= ((bin_inp[i][1]/(0.1*lgr*domeg_m))-outbin_1[i][4])/outbin_2[i][4];
    bin_11[istart+j][0]=thet[i];
    bin_11[istart+j][1]= lam;
    bin_11[istart+j][2]= 0.3/lam;                    /*frequency, in THz*/
    bin_11[istart+j][3]= f_l_re[j];
    bin_11[istart+j][4]= bin_inp[i][2];
    printf("%5.1f",thet[i]); printf("   "); 
    printf(" "); printf("%-6.3e ",outbin_1[i][4]); printf("%-6.3e  ",outbin_2[i][4]);
    printf("%-6.3e  ",f_l_re[j]); printf("%-6.3e  ",bin_inp[i][1]/(0.1*lgr*domeg_m));
    printf("\n");
    j=j+1;}
   else
   {printf(" point rejected \n");}
   
}
printf("Angle     incoh.   part_coh.    rho^2    diff. en\n");
printf("         J/sr/cm    J/sr/cm                         \n");
printf("\n");

/*check the new array bin_11*/

printf("angle\tlambda\t\t freq.\t\t coh\t\t weight\n");
if (fcount==1) iend=goodpoints[1];
else if (fcount==2) iend=goodpoints[1]+goodpoints[2];
else if (fcount==3) iend= goodpoints[1]+goodpoints[2]+goodpoints[3];
else iend=goodpoints[1]+goodpoints[2]+goodpoints[3]+ goodpoints[4];
i=0;
for ( i=0; i<iend; i++)
{ printf("%5.1f \t",bin_11[i][0]); 
  printf("%5.3f \t\t",bin_11[i][1]); printf("%-6.3e \t",bin_11[i][2]);
  printf("%-6.3e \t",bin_11[i][3]); printf("%-6.3e \t",bin_11[i][4]);
  printf("\n"); 
}
printf("\n");
fcount= fcount+1;
if (fcount<=fnum) goto ent1;
esc30: printf(" Read all the data files! \n");

printf("You have a total of "); printf("%2d", (goodpoints[1]+goodpoints[2]+goodpoints[3]+goodpoints[4]));
printf(" good data points \n"); printf("\n");
printf(" now combine data in array bin_22 and calculate  sqrt(f_lon) \n");
printf(" !!which is now called rho!! \n");	
i=0;
for (i=0; i<iend; i++)
{ 
  bin_22[i][0]= bin_11[i][2];                 /* frequency, in THz. copy from bin_11*/
  bin_22[i][1]= bin_11[i][3];                            /* rho^2, copied from bin_11*/
  bin_22[i][2]= sqrt(bin_22[i][1]);
  bin_22[i][3]= bin_11[i][4];                            /* copy weights from bin_11*/
}     
printf("Freq.(THz)\t  f_lon\t\t rho\t\t weight\t \n");
i=0;
for (i= 0; i<iend; i++)
{ 
  printf("%-6.3e \t",bin_22[i][0]);
  for (ii=1; ii<4; ii++)
  { if (ii<=4) printf("%-6.3e \t",bin_22[i][ii]); else printf("%-6.3f \t", bin_22[i][ii]); }
  printf("\n");
}
printf("\n");

printf(" now re-arrange according to frequency (in THz) \n");
/* re-arrange in ascending frequency values*/
l=iend;                                               /*start of sorting section, n=no. of rows*/
n=3;                                                 /* no. of columns, i.e. 4 here*/
ic=0;                                               /* column index for sorting, i.e. 1st here*/
i=0;
for (i=0; i<l; i++)
  { for (j=i+1; j<l; j++)
     { if (bin_22[i][ic]>bin_22[j][ic])
         { for (kk=0; kk<n+1; kk++)
              { dumm[kk]=bin_22[i][kk];
                bin_22[i][kk]=bin_22[j][kk];
                bin_22[j][kk]=dumm[kk];
              }
         }
     }
  }

numin= bin_22[0][0];           /* minimum frequency in THz in data table*/
rhomax= bin_22[0][2];         /* corresp. values of rho*/
numax= bin_22[iend-1][0];            /* maximum frequency in THz in data table*/
rhomin= bin_22[iend-1][2];    /* corresp. value of rho*/
/* give weight to the points...*/
i=0;
for (i=0; i<iend; i++)
{  
   xval[i]= bin_22[i][0];
   yval[i]= bin_22[i][2];
   wval[i]= bin_22[i][3];
}
/* ...and ensure monotonicity in frequency...*/
printf("\n");
j=0;
for (j=0; j<iend; j++)
{  monocheck = xval[j]- xval[j-1];
   if (monocheck<= 1e-4) xval[j]= xval[j-1]+ 0.0001;   /* to ensure monotonicity */                                  
}
printf("Freq.(THz)\t  rho\t\t weight\t\n");
i=0;
for (i=0; i<iend; i++)
{ 
  printf("%-6.3e \t",xval[i]); printf("%-6.3e \t",yval[i]);
  printf("%-6.3e \t",wval[i]);
  printf("\n");
}
printf(" in the original table of data points, we have: \n "); 
printf(" minimum freq.  = "); printf("%-6.3e ", numin); printf("\n");
printf(" maximum freq.  = "); printf("%-6.3e ", numax); printf("\n");
printf(" maximum rho    = "); printf("%-6.3e ", rhomax); printf("\n");
printf(" minimum rho    = "); printf("%-6.3e ", rhomin); printf("\n");

jj=0;         /* must be changed if data cleaning is required */
flag=0;
if (!flag) printf(" Do you want to clean data points? yes(y) or no(n) \n");
line[0]= 'x';
do { 
    if (line[0] != 'x') printf(" ");
    if (fgets(line, 200, stdin) == NULL) { printf("\nErr: fgets.\n"); exit(1); }
   }
while (line[0] != 'y' && line[0] != 'n'); 
ans = line[0];
if (ans=='n')
{printf("OK, will not remove points \n");
 goto esc_noclean;
}
printf(" \n");  
/* remove bad points, which must be at high freq.end of the table*/
printf("How many points do you want to remove? \n");
scanf("%2d",&jj); 
rhomin= yval[iend-1-jj]; numax= xval[iend-1-jj];

/*...and print cleaned up data...*/
printf("Freq.(THz)\t  rho\t\t \n");
i=0;
for (i=0; i<iend-jj; i++)
{ 
  printf("%-6.3e \t",xval[i]); printf("%-6.3e \t",yval[i]);
  printf("%-6.3e \t",wval[i]);
  printf("\n");
}
printf(" in the cleaned table of data points, we have:\n "); 
printf(" minimum freq.  = "); printf("%-6.3e ", numin); printf("\n");
printf(" maximum freq.  = "); printf("%-6.3e ", numax); printf("\n");
printf(" maximum rho    = "); printf("%-6.3e ", rhomax); printf("\n");
printf(" minimum rho    = "); printf("%-6.3e ", rhomin); printf("\n");

esc_noclean: printf("\n");


                     /* extrapolation section*/
		     
/* first calculate average slope at of last four points at low frequency end */
i=0;
for (i=0; i<3; i++)
{ slp[i]= (yval[i+1]- yval[i])/(xval[i+1]- xval[i]);
  printf("%-6.3e ", slp[i]); printf("\n");
}
slp[3]= (slp[0]+ slp[1] + slp[2])/3;
printf(" average slope, low freq.   = "); printf("%-6.3e ", slp[3]); printf("\n");
flag=0;
if (!flag) printf(" Do you want to change this slope? yes(y) or no(n) \n");
line[0]= 'x';
do { 
    if (line[0] != 'x') printf(" ");
    if (fgets(line, 200, stdin) == NULL) { printf("\nErr: fgets.\n"); exit(1); }
   }
while (line[0] != 'y' && line[0] != 'n'); 
ans = line[0];
if (ans=='y')
{ printf(" enter required slope for low freq. extrapolation ");
  scanf("%lf",&slp[3]); printf("\n");}
else
{printf("OK, will use the calculated slope \n");
}
gg=(log(rhomax)-slp[3]*numin/rhomax)/(numin*numin);    /* see comments below re. extrapol. function */
printf(" low freq. extrapol. coeffs. = "); printf("%-6.3e ", gg); printf(" & "); printf("%-6.3e ", slp[3]/rhomax); printf("\n");

              /* next for the high frequency end*/
ij=4;       /* integer for power extrapolation to high freq; not very sensitive */
ggh=0;
flag=0;
/* matching of slopes option added Dec. 08. The new extrapol.function is a combination of*/
/* 4th,3rd & 2nd power functions, where the coeffs. of the 3rd & 2nd degree terms */
/* are adjusted to match the slope and the other boundary conditions; PROBABLY USELESS */
if (!flag) printf(" Do you also want to match slopes at high freq. end? yes(y) or no(n) \n");
line[0]= 'x';
do { 
    if (line[0] != 'x') printf(" ");
    if (fgets(line, 200, stdin) == NULL) { printf("\nErr: fgets.\n"); exit(1); }
   }
while (line[0] != 'y' && line[0] != 'n'); 
ans = line[0];
if (ans=='y')
{ i=0;
  for (i=0; i<3; i++)
  { slph[i]= (yval[iend-jj-(i+1)]- yval[iend-jj-(i+2)])/(xval[iend-jj-(i+1)]- xval[iend-jj-(i+2)]);
  printf("%-6.3e ", slph[i]); printf("\n");
  }
  slph[3]= (slph[0]+ slph[1] + slph[2])/3;
  printf(" average slope, high freq.  = "); printf("%-6.3e ", slph[3]); printf("\n");
  ggh= -(fabs(slph[3])*numax+ 4*rhomin);
  printf(" high freq. extrapol. coeff.  = "); printf("%-6.3e ", ggh); printf("\n");}
else
{ ggh=0; printf("OK, will not match slope \n");
}
                        /*end of extrapolation section */

printf(" next interpolate inside data set & extrapolate outside.... \n");

/* section modofied July 2010. Freq.range increased to 3 orders */
/* create frequency-rho matrix (bin_f) for frequencies 0.1-50THz  */
/* to be used for subsequent calculation of phase  */
e01bec(iend-jj,xval,yval,derval,NAGERR_DEFAULT);
/* next create bin_f, with col 0=freq., col 1=fitted rho and col 2=phase */
/* see below for other columns of bin_f */
/* starting point must be lower than numin in the table*/
if (numin<=0.1) { nustart= numin-0.1;} else {nustart= 0.1;}
i=0;
for (i=0; i<1001; i++)
{
  bin_f[i][0]= nustart+ i*0.05;             /*scan frequencies, start at low end*/
  nu_bin1[i]= bin_f[i][0];
   /*calculate rho using interpolation & extrapolation */
  if (nu_bin1[i]>numin && nu_bin1[i]<numax)                          
     {  
      e01bfc(iend-jj,xval,yval,derval,1000,nu_bin1,res_bin1,&fail);    /* !!!!NB. number 1000 needs checking out!!!! */
      val0=res_bin1[i];	 
     }
  else                                                  /* extrapolation to lower frequencies*/ 
     if (nu_bin1[i]<=numin)                        /* modified 3/1/09 to include second exponential & match slope*/
     {
      val0=rhomax*exp(-gg*(nu_bin1[i]*nu_bin1[i]-numin*numin))*exp(slp[3]*(nu_bin1[i]-numin)/rhomax);         
     }
  else     /*extrap. to higher freq., assuming a power ij  decrease with freq.*/ 
     {
      val0=rhomin*pow((numax/nu_bin1[i]),ij)+ggh*pow((numax/nu_bin1[i]),(ij-1))-ggh*pow((numax/nu_bin1[i]),(ij-2));
     }
  bin_f[i][1]= val0;
}
printf("\n");

esc_timestep: printf(" Enter start time, in ps. Default is 0.01ps \n");
scanf("%lf", &tstart); printf("\n");
if (tstart<0.0) tstart=0.01;
printf("Attention!! The time span can be selected! Total number of steps is 1000.\n");
printf("enter 0.001 for 0.001ps step, 0.01 for 0.01ps etc etc\n");
scanf("%lf", &percent);
i=0;
for (i=0; i<1001; i++)                    
{ j=1;
  for (j=1; j<1000; j++)               
  {
    x_cor[j-1]= bin_f[j][0];    
    if (j==i)                     /* approximate with Taylor series*/
    y_cor[j-1]= (bin_f[i][1]-bin_f[i+1][1])/(2*bin_f[i][0]*(bin_f[i][0]-bin_f[i+1][0])*bin_f[i][1]);
    else
    y_cor[j-1]= log(bin_f[j][1]/bin_f[i][1])/(bin_f[i][0]*bin_f[i][0]-bin_f[j][0]*bin_f[j][0]);
  }
  d01gac(999,x_cor,y_cor,&res1, &error, &fail);        /* this is integral (12) for calculation of phase */
  bin_f[i][2]= 2*bin_f[i][0]*res1/pi;                     /* calculated phase in this column */
  j=3;
  for (j=3; j<1004; j++)
  { bin_f[i][j]= bin_f[i][1]*cos(2*pi*bin_f[i][0]*(tstart-j*percent)+ bin_f[i][2]);}
  /* place the integrand of eq.14 in the next 1000 columns of bin_f,for variable times */  
}
/* tidy-up phase angles */
i=0;

/*for (i==0; i<1000; i++)
{ kk=1;
  for (kk==1; kk<51; kk++)
  { if ( bin_f[i][2]>=2*pi) bin_f[i][2]= bin_f[i][2]- 2*pi ;}
}*/

for (i==0; i<1001; i++)
{ 
   if ( bin_f[i][2]>=2*pi) bin_f[i][2]= bin_f[i][2]- 2*pi ;
}
printf(" Printing SOME of the values from the frequency- phase table bin_f \n");
printf("Freq.(THz)\t rho_fit\t   phase\t  error\n");
ii=0;
for (ii=0; ii<100; ii++)                    
{ 
  printf("%8.3e \t", bin_f[ii*10][0]);
  printf("%8.3e \t", bin_f[ii*10][1]);
  printf("%8.3f \t", 180*bin_f[ii*10][2]/pi); printf("%6.3f \t", 180*error/pi);
  printf("\n");
 }

   /* ...and now the time profile...*/

j=0;
for (j=0; j<1001; j++)
{ /*time[j]= (j-500)* percent;*/                     /* time span can now be selected*/
  time[j]= tstart-j* percent;
  i=6;
  for (i=6; i<1000; i++)
  { x_cor[i-6]= bin_f[i][0];
    y_cor[i-6]= bin_f[i][j+3];
  }
  d01gac(994,x_cor,y_cor,&res1, &error, &fail);      /*eq. 14; was 993 points */ 
  timeprof[j]= 2*res1;
  timeerr[j]= error;
}    

i=0;
for (i=0; i<1001; i++)
  {
   dum70[i][0]=time[i];
   dum70[i][1]=timeprof[i];
  }

l=1000;                                                  /*start of sorting section, n=no. of rows*/
n=1;                                                    /* no. of columns, i.e. 2 here*/
ic=1;                                                   /* column index for sorting, i.e. 2nd here*/
i=0;
for (i=0; i<l; i++)
  { j=i+1;
    for (j=i+1; j<l+1; j++)
     { if (dum70[i][ic]<dum70[j][ic])
         { kk=0;
	   for (kk=0; kk<n+1; kk++)
              { dumm[kk]=dum70[i][kk];
                dum70[i][kk]=dum70[j][kk];
                dum70[j][kk]=dumm[kk];
              }
         }
     }
  }
printf(" Maximun for this case =%-4.3e",dum70[0][1]);
printf(" at t =%6.2f ",dum70[0][0]); printf(" ps");
printf("\n");
printf(" Minimum for this case =%-4.3e",dum70[1000][1]);
printf(" at t =%6.2f ",dum70[1000][0]); printf(" ps");
printf("\n");
normfactor= dum70[0][1]- dum70[1000][1];
shiftfactor= dum70[0][0];
printf(" Norm factor =%-4.3e",normfactor); printf("\n");
printf(" shift factor =%-4.3e",shiftfactor); printf("\n");

i=0;
for (i=0; i<1001; i++)
{ if (shiftfactor<=0) plot_bin[i][0]=time[i]+ fabs(shiftfactor);
  else plot_bin[i][0]=time[i]- shiftfactor;
  plot_bin[i][0]=time[i];
  plot_bin[i][1]=(timeprof[i]-dum70[1000][1])/normfactor;
}

printf("  The vertical axis has been shifted, to eliminate negative values ");
printf("\n");
printf(" The time axis has been shifted, so that maximum is at t=0 ");
printf("\n");
printf(" Printing SOME of the values from the final time- amplitude data \n");
printf("Time(ps)\tamplitude\t \n");
ii=0;
for (ii=0; ii<101; ii++)                    
{ 
  printf("%8.4f \t", plot_bin[10*ii][0]); printf("%8.4e \t", plot_bin[10*ii][1]);
  printf("\n"); 
}
flag=0;
if (!flag) printf("Do you want to create an output .txt file? yes(y) or no(n) ");
line[0] = 'x';
	do { 
	if (line[0] != 'x') printf(" ");
	if (fgets(line, 200, stdin) == NULL) { printf("\nErr: fgets.\n"); exit(1); }
	}
	while (line[0] != 'y' && line[0] != 'n'); 
ans2 = line[0];
if (ans2=='y')
{   
    printf("Name of output file?? ");
    scanf("%s",&outfile_name[0]);
    out_file=fopen(outfile_name,"w");
    for (i=0; i<1001; i++)
    { fprintf(out_file,"\n");
      for (ii=0; ii<2; ii++)          
      	  {if (ii<1) fprintf(out_file, " %-8.4f \t", plot_bin[i][ii]);
	  else  fprintf(out_file, " %-8.4e", plot_bin[i][ii]);
          }             
    }
    fprintf(out_file,"\n");
    printf(" This case had the following parameters: \n");
    printf("gamma= "); printf("%6.1f \n",gam);
    printf("beam height= "); printf("%6.3f \n",x0);
    printf("no. of electrons= "); printf("%-4.3e \n",n_e_t);
    printf("time step used= "); printf("%-5.3f \n",percent);
    /*printf("grating period= "); printf("%-5.3f \n",el);*/
    printf("order= "); printf("%1d \n",m);
    printf("phi step= "); printf("%1d \n",phistep);
    printf("limiting phi= "); printf("%1d ",((philmt-1)*phistep)); printf(" deg.\n");
    printf(" \n ");
    fclose(out_file);
    printf(" Done!\n");
}
flag=0;
if (!flag) printf("Do you want to try another time step? yes(y) or no(n) ");
line[0] = 'x';
	do { 
	if (line[0] != 'x') printf(" ");
	if (fgets(line, 200, stdin) == NULL) { printf("\nErr: fgets.\n"); exit(1); }
	}
	while (line[0] != 'y' && line[0] != 'n'); 
ans2 = line[0];
if (ans2=='y') goto esc_timestep;
else
{ printf(" OK, finished ");
  printf("\n");}

return(0); 
}

complex Ccreate(double r, double i)
{
	complex t;
	t.r = r;
	t.i = i;
	return t;
}

complex Cadd(complex a, complex b)
{
	complex t;
	t.r = a.r + b.r;
	t.i = a.i + b.i;
	return t;
}

complex Cmultiply(complex a, complex b)
{
	complex t;
	t.r = a.r * b.r - a.i * b.i;
	t.i = a.i * b.r + a.r * b.i;
	return t;
}

complex Cdivide(complex a, complex b)
{
	complex t;
	double n;
	n = b.r * b.r + b.i * b.i;
	t.r = (a.r * b.r + a.i * b.i) / n;
	t.i = (a.i * b.r - a.r * b.i) / n;
	return t;
}
	
complex Cconjugate(complex a)
{
	complex t;
	t.r = a.r;
	t.i = - a.i;
	return t;
}

vector Vcreate(double xr, double xi, double yr, double yi, double zr, double zi)
{
	vector temp;

	temp.x = Ccreate(xr, xi);
	temp.y = Ccreate(yr, yi);
	temp.z = Ccreate(zr, zi);

	return temp;
}

vector Vadd(vector v1, vector v2)
{
	vector temp;

	temp.x = Cadd(v1.x, v2.x);
	temp.y = Cadd(v1.y, v2.y);
	temp.z = Cadd(v1.z, v2.z);

	return temp;
}

vector Vmultiply(vector v, complex c)
{
	vector temp;

	temp.x = Cmultiply(v.x, c);
	temp.y = Cmultiply(v.y, c);
	temp.z = Cmultiply(v.z, c);

	return temp;
}

vector Vconjugate(vector v)
{
	vector temp;

	temp.x = Cconjugate(v.x);
	temp.y = Cconjugate(v.y);
	temp.z = Cconjugate(v.z);

	return temp;
}

complex Vdot(vector v1, vector v2)
{
	complex temp;

	temp = Cadd(Cmultiply(v1.x, v2.x), Cmultiply(v1.y, v2.y));
	temp = Cadd(temp, Cmultiply(v1.z, v2.z));

	return temp;
}

static double QU1(Integer ndim, double var[])                     /*integrand of real part of Gx, Gz*/
{  
   extern double theta,  xv, k, kx, alpha, beta, gam, D, dum, psi;
   double u, tem1, arg, y, z;
   static NagError fail;
   
   y=var[0]; z=var[1];   
   u= xv -z*tan(alpha)+ dum;
   arg= k*sqrt(u*u+y*y)/(beta*gam);
   tem1= s18adc(arg,&fail);
   return (2*k*u*cos(D*z-kx*dum+psi)*tem1*cos(ky*y)/(sqrt(u*u+y*y)*beta*gam));
}

static double QU2(Integer ndim, double var[])                     
{  
   extern double theta, xv, k, kx, alpha, beta, gam, D, dum, psi;
   double u, tem1, arg, y, z;
   static NagError fail;
      
   y=var[0]; z=var[1];   
   u= xv -z*tan(alpha)+ dum;
   arg= k*sqrt(u*u+y*y)/(beta*gam);
   tem1= s18adc(arg,&fail);                      
   return (2*k*u*sin(D*z-kx*dum+psi)*tem1*cos(ky*y)/(sqrt(u*u+y*y)*beta*gam));
}

static double QU3(Integer ndim, double var[])                    
{  
   extern double theta, xv, k, kx, alpha, beta, gam, D, dum, psi;
   double u, tem1, arg, y, z;
   static NagError fail;
   
   y=var[0]; z=var[1];   
   u= xv -z*tan(alpha)+ dum;
   arg= k*sqrt(u*u+y*y)/(beta*gam);
   tem1= s18adc(arg,&fail);
   return (2*k*y*sin(D*z-kx*dum+psi)*tem1*sin(ky*y)/(sqrt(u*u+y*y)*beta*gam));
}

static double QU4(Integer ndim, double var[])                    
{  
   extern double theta, xv, k, kx, alpha, beta, gam, D, dum, psi;
   double u, tem1, arg, y, z;
   static NagError fail;
   
   y=var[0]; z=var[1];   
   u= xv -z*tan(alpha)+ dum;
   arg= k*sqrt(u*u+y*y)/(beta*gam);
   tem1= s18adc(arg,&fail);
   return (2*k*y*cos(D*z-kx*dum+psi)*tem1*sin(ky*y)/(sqrt(u*u+y*y)*beta*gam));                               
}

static double GAU(double x)
{
   extern double x0,sigma_x;
   return (exp(-(x-x0)*(x-x0)/(2*sigma_x*sigma_x)));
}




