#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>

/*This code is similar to BUNCH, but with no plotting options. It evaluates the energy per bunch, */
/*taking into account coherence effects. This version is for fixed beam energy but it allows */
/* variation of pulse width and of sigma_x and sigma_y. It creates . */
/*          written July 2003                                        */
/* phase correction for 2nd facet included in Jan. 2005              */
/* new code architecture to allow for fast change of longit. profile, Oct. 2005  */
/*  May 2006, treatment of asymmetric triangular shape changed*/
/* November 2006, 'double-Gaussian' shape added; modified Feb. 2008                */
/* May08: max-min accepted angles theta_1 & theta_2 changed */
/* June 08: changed definition of what is 'bunch length'  */
/* June 09: bunch length changed again. Now it is the FWHM */
/* July 09: fine scan in phi, up to 1.4deg.    */
/* Feb. 10: number of electrons Ne now explicitly included in S_inc & S_coh; hence, f1 is now redefined */
static double GAU(double x);
static double FUN(double x);
static double FUN_X(double x);
static double LOR1(double t);
static double LOR2(double t);

double a, b, epsl, x0, sigma_x, sigma_y, sigma_t, beta, gam, lam_e, om;
double ky, g1, g2;

main()
{
const double pi=3.1415926;
const double qe=1.602177e-19*3e9;
char line[200], ans,ans1, ans2;
char outfile_name[64];
FILE *out_file;
int i, ii, j, k, l, m, n, liw, ic, pulse_shp, grat, flag, philmt;
int n0, int_thet_1, int_thet_2, jstart, ngauss;
extern double a, b, x0,sigma_x, sigma_y, beta, gam, lam_e;
double sigma_t1, sigma_t2, sigma_t3, sigma_t4, sigma_t5;
double mu1, mu2, mu3, mu4, mu5, g1, g2, g3, g4, g5;
double lgr, el, frac, el1, el2, alpha1, alpha2, hi, x, percent;
double phi0, phistep, emit, nemit, y0, y0_av, charlen;
double ll, ul, abserr, epsabs, epsrel, res1, res2, n_e, n_e_t;
double pulse_len, len50, i_av_p, om, u, u1, u2, u3, u4, u5, ratio;
double a1, b1, a2, b2, a2_t, b2_t, a111, a112, a113, a114, a115;
double a211, a212, a_sin, a_cos, b_sin, b_cos, a1t, a2t;
double eta1, eta2, tau1, tau2, rho, xi, kx, ky, theta, lam;
double f1, f2, f3, f5, sf3, f33, f_y_c, f_y_s, f_z_c, f_z_s, z, x_rad;
double sigma_t, sigma_teff, apb, ssigma_x, theta_u, theta_d, sum, sum1;
double d_theta, d_phi;                             /* used only in the estimate of total radiated energy */
double t, tmax, f, fmax, temp1, temp2, temp3;
double aven, r, r2, domeg_m;
double thet_1, thet_2, sum_th, sum_tr;
double dumsum, tot_int;
double s_coh_long, s_coh_xy;
double dum[3], hyperg[500];
double scalefactor[179];
double f4[179], thet[179], en_inc[179], en_coh[179];
double bin_1[179][2], dum70[179][2];
double r_bin[179][10], s_inc_x[179][10], s_coh_x[179][10], s_coh_tr[179][10], s_coh_z[179][10], f_b[179][10], bin[179][15];
float outbin[171][6];
Nag_QuadProgress QP;
Nag_QuadSubProgress QPSUB1,QPSUB2;
Nag_TrigTransform WT_FUNC;
static NagError FAIL;

printf("\n"); printf("\n"); printf("\n");
printf("                   LATEST VERSION- FINE SCAN IN PHI              \n");
printf("\n");
printf("       !!! Note new definition of bunch length !!!           \n");
printf("\n");
printf("    now defined as the FWHM of the distribution    \n");
printf("\n");
printf(" this is to account for shapes that do not have a simple analytical form \n");
printf("\n"); printf("\n");
printf("            NEW bunch shape, with up to 5 Gaussians \n");
printf(" NB. scale factor f1 DOES NOT include n_e, which has been moved to S_inc & S_coh \n");
printf(" Have re-written some expressions to bring them closer to those used in publications \n");
printf("\n"); printf("\n");

printf(" Enter grating period in mm\n");
scanf("%lf",&el);
/*printf(" Now select type of grating \n");
printf(" Type:\n");
printf("      -3 for strip grating\n");
printf("      -1 for reverse blaze echelle grating \n");
printf("       0 for idealized strip grating       \n");
printf("       1 for normal blaze echelle grating  \n");
printf("       2 for sawtooth grating              \n");
printf(" Default is the sawtooth grating           \n");
scanf("%d",&grat);*/
printf("\n");
grat=2;
if (grat==-3) 
    {printf(" This is a strip grating \n");
    alpha1=0;
    printf(" Enter height of vertical facet, in mm  \n");
    scanf("%lf",&hi);
    alpha2=0;
    printf(" Enter the fraction of the period taken by the strip \n");
    scanf("%lf",&frac);
    if (frac<0.0 || frac>1.0) frac=0.5; 
    el1=el*frac;
    el2=el-el1;}
else if (grat==-1)   
    {printf("This is a reverse blaze echelle grating \n");
    frac=0;
    el1=0;
    alpha1=pi/2;
    el2=el;
    printf(" Enter second blaze angle of grating in degrees; MUST BE greater than 90 \n");
    scanf("%lf",&alpha2);
    alpha2= alpha2*pi/180;
    hi=fabs(el2*tan(alpha2));} 
else if (grat==0)
    {printf(" This is an idealized  strip grating \n");
    alpha1=0;
    printf(" Enter the fraction of the period taken by the strip \n");
    scanf("%lf",&frac);
    if (frac<0.0 || frac>1.0) frac=0.5; 
    el1=el*frac;
    alpha2=0;} 
else if (grat==1)
    {printf("This is an echelle-type grating \n");
    frac=1.0;
    el1=el;
    el2=0;
    alpha2= pi/2;
    printf("Enter first blaze angle of grating, in degrees \n");
    scanf("%lf",&alpha1);
    alpha1=alpha1*pi/180;
    hi=fabs(el*tan(alpha1));}
else
    {
    if (el==1.5) alpha1=30;
    else if (el==1.0) alpha1=35;
    else if(el==0.5) alpha1=40;
    else {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);     /* alpha2 redefined, 10/1/10 */
    }
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");
lgr=40;            /* grating length, in mm*/
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.3deg. */
domeg_m=pi*(r2/2)*(r2/2)/pow(r,2);                                      /*max. solid angle */
printf("\n");
printf(" With these dimensions ,we have: \n");
printf("Max. solid angle at 90 is= "); printf("%-7.4f",domeg_m); printf(" sr \n");
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("%le",&nemit);
emit=1e-3*nemit/(beta*gam);                                  /*converted to mm.rad*/

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;  } */                                             /*default order 1 */
printf(" \n");

printf("This code can take up to 7 steps in the azimuthal direction phi \n");
printf(" Define step size: min.=0.1deg, max.=10deg, default=1.0deg. \n");
scanf("%lf", &phistep);
if (phistep<0.1 || phistep>10) phistep=1.0;
printf("OK, phi step is equal to= "); printf("%-3.1f", phistep); printf(" deg.\n");


/*estimate of grating factor R^2*/
i=1;
for (ii=0; ii<8; ii++)
{ phi0= ii*phistep*pi/180;                                  /* phi scanned up to 7xphistep deg.*/  
  for (i=1; i<180; i++)
  {
    thet[i]=i;                                 /*scan angles up to 180 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;
    om=2*pi*0.3/lam;                          /*0.3 is vel. of light in mm/ps*/
/*lam is the wavelength of the emitted radiation; lam_e the effective w/l     */
/*            find the grating shape factor f5                                */
/* Here we assume a sawtooth grating x0+(l-z)tan(alpha), where alpha is       */
/* blaze angle. This case can be treated analytically and the square of the   */
/* modulus of the integral is given by f5. N.B. distances now from the base of*/
/* the grating teeth.                                                         */
    xi=hi/lam_e;
    rho=el/lam_e;
/* consider first facet                                                       */
    tau1=2*pi*m*cos(alpha1)-kx*el*sin(alpha1);
    eta1=2*pi*m*el1/el-kx*hi;
    if (grat==-3)
    a1=sin(pi*m*el1/el)*cos(pi*m*el1/el-kx*hi)/(pi*m);
    else
    a1=(rho*sin(alpha1)*(cos(eta1)-exp(-xi))+tau1*sin(eta1))
         /(rho*rho*sin(alpha1)*sin(alpha1)+tau1*tau1);
    if (grat==-3)
    b1=sin(pi*m*el1/el)*sin(pi*m*el1/el-kx*hi)/(pi*m);
    else
    b1=(rho*sin(alpha1)*sin(eta1)-tau1*(cos(eta1)-exp(-xi)))
         /(rho*rho*sin(alpha1)*sin(alpha1)+tau1*tau1);
/*second facet                                                                */
    tau2=2*pi*m*cos(alpha2)-kx*el*sin(alpha2);
    eta2=2*pi*m*el2/el;
    if (grat==0 || grat==-2)
    {
        a2_t=0;
        b2_t=0;}
    else if (grat==-3)
    {
        a2_t=exp(-xi)*sin(pi*m*el2/el)*cos(pi*m*el2/el)/(pi*m);
        b2_t=exp(-xi)*sin(pi*m*el2/el)*sin(pi*m*el2/el)/(pi*m);}
    else
    {
        a2_t=(rho*sin(alpha2)*(cos(eta2)*exp(-xi)-cos(kx*hi))
           +tau2*(sin(eta2)*exp(-xi)+sin(kx*hi)))/(rho*rho*sin(alpha2)*sin(alpha2)+tau2*tau2);
        b2_t=(rho*sin(alpha2)*(sin(eta2)*exp(-xi)+sin(kx*hi))
           -tau2*(cos(eta2)*exp(-xi)-cos(kx*hi)))/(rho*rho*sin(alpha2)*sin(alpha2)+tau2*tau2);}
/* phase correction for 2nd facet */
    a2= a2_t*cos(2*pi*el1/el)-b2_t*sin(2*pi*el1/el);
    b2= b2_t*cos(2*pi*el1/el)+a2_t*sin(2*pi*el1/el);
/* end of correction */
/* combination of the two facets                                              */
    a_sin=a1*sin(alpha1)+a2*sin(alpha2);
    b_sin=b1*sin(alpha1)+b2*sin(alpha2);
    a_cos=a1*cos(alpha1)+a2*cos(alpha2);
    b_cos=b1*cos(alpha1)+b2*cos(alpha2);
/* first polarization e1 in plane of n,z                                      */
    a111=(a_sin*a_sin+b_sin*b_sin)*pow(cos(theta),2)*pow(cos(phi0),2);
    a112=(a_sin*a_sin+b_sin*b_sin)*pow((ky*lam_e),2)*pow(cos(theta),2)*pow(sin(phi0),2);
    a113=(a_cos*a_cos+b_cos*b_cos)*pow(sin(theta),2);
    a114=-2*(a_sin*a_cos+b_sin*b_cos)*sin(theta)*cos(theta)*cos(phi0);
    a115=2*(a_sin*b_cos-b_sin*a_cos)*ky*lam_e*sin(theta)*cos(theta)*sin(phi0);
/* total for e1, squared                                                      */
    a1t=a111+a112+a113+a114+a115;
/* second polarization e2                                                     */
    a211=(a_sin*a_sin+b_sin*b_sin);
    a212=sin(phi0)*sin(phi0)*(1+pow((kx*lam_e),2));
/* total for e2, squared                                                      */
    a2t=a211*a212;
    f5=a1t+a2t;
    r_bin[i][ii]=f5;         /*so, in col.label 0 data for phi=0, in 1 for phi=1xphistep, in 7 for phi=7xphistep*/
  }                              
}

i=1;
for (i=1; i<180; i++)
{   printf("\n");
    printf("%-3d  ", i);
    ii=0;
    for (ii=0; ii<8; ii++)
    { printf( "%.3e\t", r_bin[i][ii]); }        
}        
printf("\n");
printf(" Each column above is for a phi step of "); printf("%-3.1f",phistep); printf(" deg. \n");
printf(" Finished with the calculation of R^2 \n");
printf("\n"); 

                              /*beam parameters  */
esc20: printf("\n");
printf("Enter position (in mm) of beam centroid above grating\n");
scanf("%lf",&x0);
esc24:printf("\n");
printf("Enter sigma_x(in mm) of Gaussian beam at waist, at the centre of grating \n");
scanf("%le",&sigma_x);
printf(" For this sigma_x: \n");
printf(" 0.50 of the beam is within a radius of "); printf("%-4.2e",0.6749*sigma_x); printf(" mm \n");
printf(" 0.90 of the beam is within a radius of "); printf("%-4.2e",1.6450*sigma_x); printf(" mm \n");
printf(" 0.99 of the beam is within a radius of "); printf("%-4.2e",2.5733*sigma_x); printf(" mm \n");

y0=1.6450*sigma_x;                        /* y0 is an assumed beam x-radius */
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.2e",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("%le",&sigma_y);
printf(" For this sigma_y: \n");
printf(" 0.50 of the beam is within a radius of "); printf("%-4.2e",0.6749*sigma_y); printf(" mm \n");
printf(" 0.90 of the beam is within a radius of "); printf("%-4.2e",1.6450*sigma_y); printf(" mm \n");
printf(" 0.99 of the beam is within a radius of "); printf("%-4.2e",2.5733*sigma_y); printf(" mm \n");

ll=x0-5*sigma_x;                                       /* GD modified 5/6/06*/
if (ll<0) ll=0;
ul=x0+5*sigma_x;
epsabs=1.0e-12;
epsrel=1.0e-4;
liw=500;
d01ajc(GAU,ll,ul,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);
flag=0;

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;
esc25: printf("Enter nominal bunch duration (FWHM), in ps \n");
scanf("%lf",&pulse_len);
i_av_p=n_e_t*1.602177*1e-7/pulse_len;
printf("The average current in the pulse is= "); printf("%-4.3f",i_av_p); printf(" A \n");
f1=2*pi*qe*qe*1e-7;
printf(" The  scale factor f1="); printf("%le",f1); printf(" J.cm \n");

f2=100/pow(el,2);                 /* geometry factor f2 in cm-2; grating period in mm */

esc1: printf( "\n");
printf("You now have the following  choice for profiles in z-direction \n");
printf("Type one of the following: \n");
printf(" 0 for a DC beam \n");
printf(" 1 for a single Gaussian \n"); printf(" 2 for triangular \n"); printf(" 3 for double-exp. \n");
printf(" 4 for parabolic \n"); printf(" 5 for cosine \n"); printf(" 6 NOT IN USE \n");
printf(" 7 for Lorentz shape \n"); printf(" 8 for a multi-Gauss shape \n");
printf(" which one do you want?? \n");
scanf("%d",&pulse_shp);
if (pulse_shp<0 || pulse_shp==6 ||pulse_shp>8)
  { printf(" I do not recognize this \n");
   goto esc1;}
  
if (pulse_shp==1)                     /*Gaussian*/
{  
   printf("Type asymmetry factor epsl \n");
   scanf("%lf",&epsl);
   sigma_t= pulse_len/(sqrt(2*log(2))*(1+epsl));              /*length defined by FWHM 11/5/09*/
   printf(" the sigma of the leading edge is "); printf("%-4.3f",sigma_t); printf(" ps \n");
   printf(" and sigma of the trailing edge is "); 
   printf("%-4.3f",epsl*sigma_t); printf(" ps \n"); 
}
else if (pulse_shp==2)                      /*triangular, modified 11/05/09*/
{
   printf("Type asymmetry factor epsl \n");
   scanf("%lf",&epsl);
   sigma_t= pulse_len/((1+epsl)*(1-0.5));                          /* now in terms of FWHM, 11/05/09 */
   printf(" For this bunch shape, the sigma_t is "); printf("%-4.3f",sigma_t); printf(" ps \n");
}
else if (pulse_shp==3)                     /*double exponential*/
{  
   printf("Type asymmetry factor epsl \n");
   scanf("%lf",&epsl);
   sigma_t=pulse_len/((1+epsl)*log(1/0.5));             /*changed 11/05/09, now using FWHM */
   printf(" the sigma_t is "); printf("%-4.3f",sigma_t); printf(" ps \n");    
}
else if (pulse_shp==4)                        /*parabolic*/
{
   printf("Type asymmetry factor epsl \n");
   scanf("%lf",&epsl);
   sigma_t=pulse_len/((1+epsl)*sqrt(1-0.5));       /*changed 11/05/09, using FWHM*/   
   printf(" For this bunch shape, sigma_t is "); printf("%-4.3f",sigma_t); printf(" ps \n");    
}
else if (pulse_shp==5)                     /*cosine*/
{
   epsl=1;
   sigma_t=pulse_len*pi/(4*acos(0.5));                   /* changed 11/05/09, using FWHM*/   
   printf(" For this bunch shape, sigma_t is "); printf("%-4.3f",sigma_t); printf(" ps \n");
}
else if (pulse_shp==6)
{
   goto esc1;
}
else if (pulse_shp==7)                    /*Lorentz*/
{
   printf("Enter the asymmetry factor epsl; symmetric shape means eps=1 \n");
   scanf("%lf",&epsl);
   apb=pulse_len;                                 /* changed 15/5/09*/
   printf("a+b is = "); printf("%-4.3f",apb); printf(" ps \n");  
   a=apb/(1+epsl);       /* no need for sigma_t; shape is defined by a & b */
   b=a*epsl;
   printf(" a(leading edge)= "); printf("%-4.3f",a); printf("ps \n"); 
   printf(" b(trailing edge)= "); printf("%-4.3f",b); printf("ps \n");
}
else if (pulse_shp==8)        /*multiple Gaussian,  June 08, modified for FWHM 11/05/09*/
{  
  esc81: printf(" how many gaussians are you fitting? Min. is 2 and max. is 5 \n");
  scanf("%1d", &ngauss);
  res1=0; 
  printf(" for the 1st peak, enter sigma, amplitude & position \n");
  scanf("%lf %lf %lf", &sigma_t1, &g1, &mu1);
  if (ngauss==2)
  {printf(" for the 2nd peak, enter sigma, amplitude & position \n");
   scanf("%lf %lf %lf", &sigma_t2, &g2, &mu2);
   sigma_t3=sigma_t4=sigma_t5=0;
   g3=g4=g5=0;
   mu3=mu4=mu5=0;}
  else if (ngauss==3)
  {printf(" for the 2nd peak, enter sigma, amplitude & position \n");
   scanf("%lf %lf %lf", &sigma_t2, &g2, &mu2);
   printf(" for the 3rd peak, enter sigma, amplitude & position \n");
   scanf("%lf %lf %lf", &sigma_t3, &g3, &mu3);
   sigma_t4=sigma_t5=0;
   g4=g5=0;
   mu4=mu5=0;}
  else if (ngauss==4)
  {printf(" for the 2nd peak, enter sigma, amplitude & position \n");
   scanf("%lf %lf %lf", &sigma_t2, &g2, &mu2);
   printf(" for the 3rd peak, enter sigma, amplitude & position \n");
   scanf("%lf %lf %lf", &sigma_t3, &g3, &mu3);
   printf(" for the 4th peak, enter sigma, amplitude & position \n");
   scanf("%lf %lf %lf", &sigma_t4, &g4, &mu4);
   sigma_t5=0;
   g5=0;
   mu5=0;}
  else
  {printf(" for the 2nd peak, enter sigma, amplitude & position \n");
   scanf("%lf %lf %lf", &sigma_t2, &g2, &mu2);
   printf(" for the 3rd peak, enter sigma, amplitude & position \n");
   scanf("%lf %lf %lf", &sigma_t3, &g3, &mu3);
   printf(" for the 4th peak, enter sigma, amplitude & position \n");
   scanf("%lf %lf %lf", &sigma_t4, &g4, &mu4);
   printf(" for the 5th peak, enter sigma, amplitude & position \n");
   scanf("%lf %lf %lf", &sigma_t5, &g5, &mu5);}

  /* check total value of this integral, i.e. normalisation factor */
  tot_int= sqrt(2*pi)*(g1*sigma_t1+g2*sigma_t2+g3*sigma_t3+g4*sigma_t4+g5*sigma_t5);
  printf(" the normalisation factor is  "); 
  printf("%-4.3e",tot_int); printf(" units \n");  
  sigma_teff= g1*sigma_t1+ g2*sigma_t2+g3*sigma_t3+ g4*sigma_t4+g5*sigma_t5; 
     /* find position & value of maximum of normalised distribution; total scan width=15ps */
  fmax=0;
  tmax=0;
  i=0;
  for (i==0; i<1500; i++)
  { 
  t= 1*sigma_teff- i*0.01;              /* start well into the positive region*/  
  f=(g1*exp(-(t-mu1)*(t-mu1)/(2*sigma_t1*sigma_t1))+g2*exp(-(t-mu2)*(t-mu2)/(2*sigma_t2*sigma_t2))+
     g3*exp(-(t-mu3)*(t-mu3)/(2*sigma_t3*sigma_t3))+
     g4*exp(-(t-mu4)*(t-mu4)/(2*sigma_t4*sigma_t4))+
     g5*exp(-(t-mu5)*(t-mu5)/(2*sigma_t5*sigma_t5)))/tot_int;
  if (f>= fmax) {fmax=f; tmax=t;}
  }
  printf(" maximum for the (normalised) shape is at t="); 
  printf("%-4.3f", tmax); printf(" \n");
  printf(" and is equal to "); 
  printf("%-4.3f", fmax); printf(" \n");
   /* finished with this; now find points where value of function is about 0.5 */
   /* and use these as the limits for the evaluation of the normalised integral */
   /* start on positive side...*/
  i=0;
  for (i==0; i<1500; i++)
  { 
  t= tmax + i*0.01;   
  f=(g1*exp(-(t-mu1)*(t-mu1)/(2*sigma_t1*sigma_t1))+g2*exp(-(t-mu2)*(t-mu2)/(2*sigma_t2*sigma_t2))+
     g3*exp(-(t-mu3)*(t-mu3)/(2*sigma_t3*sigma_t3))+
     g4*exp(-(t-mu4)*(t-mu4)/(2*sigma_t4*sigma_t4))+
     g5*exp(-(t-mu5)*(t-mu5)/(2*sigma_t5*sigma_t5)))/tot_int;
  if (f<= 0.5*fmax) {ul=t; goto esc82;}
  }
  esc82: printf("the upper 50 percent point of the distribution is "); printf("%-4.2f",ul);
/* continue on negative...*/
  i=0;
  for (i==0; i<1500; i++)
  { 
  t= tmax - i*0.01;   
  f=(g1*exp(-(t-mu1)*(t-mu1)/(2*sigma_t1*sigma_t1))+g2*exp(-(t-mu2)*(t-mu2)/(2*sigma_t2*sigma_t2))+
     g3*exp(-(t-mu3)*(t-mu3)/(2*sigma_t3*sigma_t3))+
     g4*exp(-(t-mu4)*(t-mu4)/(2*sigma_t4*sigma_t4))+
     g5*exp(-(t-mu5)*(t-mu5)/(2*sigma_t5*sigma_t5)))/tot_int;
  if (f<= 0.5*fmax) {ll=t; goto esc83;}
  }
  esc83: printf(" and the lower one "); printf("%-4.2f",ll); printf("\n");
/* done*/        
  esc80: len50= ul- ll;    /* this is the assumed bunch length */
  printf(" Hence, the assumed bunch length (FWHM) is "); printf("%-4.2f",len50); printf(" ps \n");
  flag=0;
  if (!flag) printf(" Do you want to change anything? 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("go back to input parameters \n");
   goto esc81;
  }
  printf(" \n");  
}
printf("\n");

printf("Calculating energy per micropulse, PER CM length of grating  \n");
ii=0;
for (ii=0; ii<8; ii++)
{ phi0= ii*phistep*pi/180;                                     /* phi scanned in 7 steps, each of size=phistep*/
  i=1;
  for (i=1; i<180; i++)
  {
    thet[i]=i;                                 /*scan angles up to 180 deg.  */
    theta=thet[i]*pi/180;
    lam=el*(1/beta-cos(theta))/m;
/*     find the angular distribution factor f4; see comment in POLAR          */
    f4[i]=pow(m,2)*pow((beta/(1-beta*cos(theta))),3);
    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;
/*    scalefactor[i]= f1*f2*f4[i];*/
    om=2*pi*0.3/lam;                          /*c=0.3 mm/ps, hence om in ps^-1*/

                      /*calculate longitudinal coherence effects*/
    if (pulse_shp==0)
    {
        u=0;                         /*not necessary, but no coh. for DC beam*/
        f_z_c=0;
        f_z_s=0;
    }
    else if (pulse_shp==1)
    { u1= om*sigma_t;
      u2= om*sigma_t*epsl;
      temp1=0; temp2=0;
      f_z_c=(exp(-(u1*u1)/2)+ epsl*exp(-(u2*u2)/2))/(1+epsl);    /* yes, it is correct!*/
/* degenerate hypergeometric function below is taken from G&R page 480  */ 
      k=1;
      hyperg[0]=1;
      for (k==1; k<201; k++)
      { ratio= (u1*u1/2)*(2*k-1)/(k*(2*k+1));
	hyperg[k]= hyperg[k-1]*ratio;
      }
      k=1;
      sum=1;
      for (k==1; k<201; k++)
      { dumsum= sum+ hyperg[k];
      	sum=dumsum;
      }
      temp1= fabs(sum*u1*sigma_t*exp(-u1*u1/2));      
/*      now for the trailing part of the bunch */ 
      k=1;
      hyperg[0]=1;
      for (k==1; k<201; k++)
      { ratio= (u2*u2/2)*(2*k-1)/(k*(2*k+1));
	hyperg[k]= hyperg[k-1]*ratio;
      }
      k=1;
      sum=1;
      for (k==1; k<201; k++)
      { dumsum= sum+ hyperg[k];
      	sum=dumsum;
      }
      temp2= fabs(sum*u2*sigma_t*epsl*exp(-u2*u2/2));
      f_z_s=2*(temp1-temp2)/(sqrt(2*pi)*sigma_t*(1+epsl));    /* including nor. factor of 2/sqrt(2pi)..  */	
    }        
    else if (pulse_shp==2)
    {
        u=om*sigma_t;
        f_z_c=2*(1-(epsl*cos(u)+cos(epsl*u))/(1+epsl))/(epsl*u*u);
        f_z_s=2*((sin(epsl*u)-epsl*sin(u))/(1+epsl))/(epsl*u*u);
    }
/* integrate to edge of pulse*/
    else if (pulse_shp==3)
    {
       u=om*sigma_t;
       f_z_c=(1+epsl*u*u)/(1+u*u)/(1+pow((epsl*u),2));
       f_z_s=(epsl*u-u)/(1+u*u)/(1+pow((epsl*u),2));
    }
/*integr. to infinity, so only sigma_t appears in result*/
    else if (pulse_shp==4)
    {
        u=om*sigma_t;
        f_z_c=3*(sin(u)+sin(epsl*u)/(epsl)-u*cos(u)-u*cos(epsl*u)/(epsl))/((1+epsl)*pow(u,3));
        f_z_s=3*(1/(epsl*epsl)-1+cos(u)-cos(epsl*u)/(epsl*epsl)+u*sin(u)-u*sin(epsl*u)/(epsl))/((1+epsl)*pow(u,3));
/* integrate to edge of pulse i.e. sigma_t*/
    }
    else if (pulse_shp==5)
    {
        u=om*sigma_t;
        f_z_c=pi*pi*cos(u)/(pi*pi-4*u*u);
        f_z_s=0;
/*must integrate to edge of pulse, i.e. sigma_t*/
    }
    else if (pulse_shp==6)
    {
        u=om*sigma_t;
        f_z_c=((1-u*u)*cos(u)+2*u*sin(u))/(pow((1+u*u),2));
        f_z_s=0;
/*must integrate from -inf. to edge of pulse, i.e. sigma_t*/
    }
    else if (pulse_shp==7)                      /*numerical integr. for Lorentz shape*/
    {
        /* a and b deal with asymmetric Lorentz shape. a is for leading edge*/
                            /* norm. factor is 2/pi/(a+b)  */
	f_z_c=(b*exp(-om*b)+a*exp(-om*a))/(apb);
        WT_FUNC=Nag_Sine;
        d01asc(LOR1,0.0,om,WT_FUNC,50,500,1E-3,&res1,&abserr,&QPSUB1,&FAIL);
	d01asc(LOR2,0.0,om,WT_FUNC,50,500,1E-3,&res2,&abserr,&QPSUB2,&FAIL);
        f_z_s=2*(b*b*res2-a*a*res1)/(pi*(apb));
	NAG_FREE(QPSUB1.interval_error);
        NAG_FREE(QPSUB1.interval_result);
        NAG_FREE(QPSUB1.interval_flag);
	NAG_FREE(QPSUB2.interval_error);
        NAG_FREE(QPSUB2.interval_result);
        NAG_FREE(QPSUB2.interval_flag);
    }
    else if (pulse_shp==8)                        /* double Gaussian, normalised, modified 15/3/08*/
    { sigma_teff= g1*sigma_t1+ g2*sigma_t2+g3*sigma_t3+ g4*sigma_t4+g5*sigma_t5;
      u1=om*sigma_t1; u2=om*sigma_t2;
      u3=om*sigma_t3; u4=om*sigma_t4; u5=om*sigma_t5;
      f_z_c=sqrt(2*pi)*(g1*sigma_t1*exp(-u1*u1/2)*cos(mu1*om)+
                        g2*sigma_t2*exp(-u2*u2/2)*cos(mu2*om)+
                        g3*sigma_t3*exp(-u3*u3/2)*cos(mu3*om)+
			g4*sigma_t4*exp(-u4*u4/2)*cos(mu4*om)+
			g5*sigma_t5*exp(-u5*u5/2)*cos(mu5*om))/tot_int;
      f_z_s=sqrt(2*pi)*(g1*sigma_t1*exp(-u1*u1/2)*sin(mu1*om)+
                        g2*sigma_t2*exp(-u2*u2/2)*sin(mu2*om)+
                        g3*sigma_t3*exp(-u3*u3/2)*sin(mu3*om)+
			g4*sigma_t4*exp(-u4*u4/2)*sin(mu4*om)+
			g5*sigma_t5*exp(-u5*u5/2)*sin(mu5*om))/tot_int;
    }		

    s_coh_long= pow(f_z_c,2)+pow(f_z_s,2);        /*finished with z-part of Scoh*/
    s_coh_z[i][ii]= s_coh_long;                  /*store in separate array for future use*/
/*  find the coupling factor f3 between beam and grating by assuming a        */
/*  Gaussian profile for the e-beam, and integrating across the e-beam;       */
/*  use emittance to calculate varying profile over the grating length        */
    ssigma_x=0;
    for (j=1; j<7; j++)                   /*first calculate beam profile over grating*/
    {
       z=(j-1)*lgr/10;
       sigma_x=y0*sqrt(1+pow((z/charlen),2))/1.645;           /*varying beam half-width*/
       ssigma_x=ssigma_x+sigma_x;}
    sigma_x=ssigma_x/6;    
    ll=x0-5*sigma_x;                                       /* GD modified 5/6/06*/
    if (ll<0) ll=0;
    ul=x0+5*sigma_x;        
    epsabs=1.0e-12;
    epsrel=1.0e-4;
    liw=500;
    d01ajc(FUN,ll,ul,epsabs,epsrel,liw,&res2,&abserr,&QP,&FAIL);            
    f3=res2/(sigma_x*sqrt(2*pi));      /*f3 is the incoherent integral, averaged over 1/2 grating*/
    s_inc_x[i][ii]=f3;
    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);  
    d01ajc(FUN_X,ll,ul,epsabs,epsrel,liw,&res2,&abserr,&QP,&FAIL);
    f33=res2/(sigma_x*sqrt(2*pi));     /*x-part of coherent integral, averaged over 1/2 grating*/
    s_coh_x[i][ii]= f33*f33;            /*.... and squared...*/
    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);                                                  
    f_y_c=exp(-pow((ky*sigma_y),2)/2);
    f_y_s=0;
    s_coh_xy= (f_y_c*f_y_c+f_y_s*f_y_s)*f33*f33;
    s_coh_tr[i][ii]=s_coh_xy;                    /*transverse coherence factor, in new array*/
    f_b[i][ii]= n_e*f3+ n_e*n_e*s_coh_xy*s_coh_long;  /*overall effect of Ne electrons in a bunch*/ 
    /*en_coh[i]= f1*f2*f4[i]*r_bin[i][ii]*f_b[i]; */                            /*radiated energy*/        
    bin[i][0]=i;
    bin[i][ii+1]= f1*f2*f4[i]*r_bin[i][ii]*(n_e*f3+ n_e*n_e*s_coh_xy*s_coh_long); 
    /*NB!! in col.1 data for phi=0, in 2 for phi=1, in 8 for phi=7*/    
  }                            
  
}
printf("\n"); printf("\n");

printf("For Phi0=0 ONLY \n");
printf(" Angle   Lambda   S_inc       S_coh_z     S_coh_tr   Bunch_factor   Energy \n");
for (i=1; i<180; i++)
{ ii=0;
    thet[i]=i;                                 /*scan angles up to 180 deg.  */
    theta=thet[i]*pi/180;
    lam=el*(1/beta-cos(theta))/m;
    printf("%-5.1f",thet[i]); printf("    ");
    printf("%-4.3f",lam);
    printf("    "); printf("%-4.3e",s_inc_x[i][ii]); printf("   ");
    printf("%-4.3e",s_coh_z[i][ii]); printf("   ");   printf("%-4.3e",s_coh_tr[i][ii]); printf("   ");
    printf("%-4.3e",f_b[i][ii]); printf("   "); printf("%-4.3e",bin[i][ii+1]);
    printf("\n");}  
printf(" Angle   Lambda   S_inc       S_coh_z     S_coh_tr   Bunch_factor   Energy \n");
printf("The above apply for Phi0=0 ONLY \n");
printf("\n");
printf("the following is a list of the INCOHERENT & COHERENT parts of the x-integral; INCOHERENT is first \n");
printf(" Each term has also been multiplied by R^2. ");
printf("\n");
i=10;
for (i=10; i<171; i++)
  {   printf("\n");
      printf("%-3d  ", i);
      ii=0;
      for (ii=0; ii<8; ii++)
      { printf( "%.3e  ", (s_inc_x[i][ii]*r_bin[i][ii])); }
      printf("\n"); printf("     ");
      ii=0;
      for (ii=0; ii<8; ii++)
      { printf( "%.3e  ", (sqrt(s_coh_x[i][ii])*r_bin[i][ii])); }         
  } 
printf("\n");
i=0;
for (i=0; i<159; i++)
  {dum70[i][0]=i+20;
   dum70[i][1]=bin[i+20][1];               /*copy to dum70 only the phi=0 values, above theta=20*/
  }
l=158;                                                  /*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])
         { k=0;
	   for (k=0; k<n+1; k++)
              { dum[k]=dum70[i][k];
                dum70[i][k]=dum70[j][k];
                dum70[j][k]=dum[k];
              }
         }
     }
  }
printf("\n");
printf(" Maximun for this case(phi=0) =%-4.3e",dum70[0][1]);
printf(" J/sr/cm at theta =%6.2f\n",dum70[0][0]);
printf("\n");

/*rough estimate of full width at half max. for the power distribution*/
i=0;
for (i=0; i<179; i++)
{
    if (dum70[i][1]>=0.5*dum70[1][1]) 
    {
        bin_1[i][0]=dum70[i][0];
        bin_1[i][1]=dum70[i][1];
    }
    else
    {
        bin_1[i][0]=0;
        bin_1[i][1]=0;
    }
}
l=178;                                                  /*start of sorting section, n=no. of rows*/
n=1;                                                    /* no. of columns, i.e. 2 here*/
ic=0;                                                   /* column index for sorting, i.e. 1st here*/
i=0;
for (i=0; i<l; i++)
  { j=i+1;
    for (j=i+1; j<l+1; j++)
     { if (bin_1[i][ic]<bin_1[j][ic])
         { k=0;
	   for (k=0; k<n+1; k++)
              { dum[k]=bin_1[i][k];
                bin_1[i][k]=bin_1[j][k];
                bin_1[j][k]=dum[k];
              }
         }
     }
  }
theta_u=bin_1[0][0];
i=0;
for (i=0; i<179; i++)
{
    if (bin_1[i][1]<=0) goto esc2;
    theta_d=bin_1[i][0];
}
esc2:printf("\n");
printf("Rough estimate of full-width, half maximum \n");
printf(" Lower limit at= %6.2f\n",theta_d);
printf(" Upper limit at= %6.2f\n",theta_u);
printf(" \n");

 /* rough estimate of total radiated energy, per single bunch */
printf("I will now average over the accepted azimuthal angles \n");
printf("The min. number of steps in phi, INCLUDING phi=0, is 1; max is 8,\n");
printf(" which would take you up to phi= %4.1f \n", (7*phistep));
printf(" Enter number of steps \n");
scanf("%1i",&philmt);
if (philmt<1 || philmt>8) philmt=8;
printf(" I will average up to phi= %-3.1f ",((philmt-1)*phistep)); printf(" \n");

i=1;
for ( i=1; i<180; i++)
{     
   sum=0.0; ii=1;
   if (philmt==0) sum= bin[i][1];
   else
   for (ii=1; ii<philmt+1; ii++)
   {sum=sum+ 2*bin[i][ii+1];}             /* start from col. index 2(phi=1xphistep) and double the sum to account for +-phi */
   if (philmt==0) bin[i][9]= bin[i][1];
   else 
   bin[i][9]=(bin[i][1]+ sum)/(2*philmt+1);       /* col. 9 is the store for av. diff. energy over all ACCEPTED phi's */	 
}
printf("\n");

d_theta=1.745e-2;                                      /* d_theta step is always 1 degree */
d_phi= phistep*1.745e-2;                                 /* d_phi expressed in rad */
i=1;
for (i=1; i<180; i++)
{  sum=0.0; ii=1;
   for (ii=1; ii<8; ii++)
   {sum=sum+sin(i*pi/180)*d_theta*d_phi*bin[i][ii+1];  /*Domega=sin_theta*d_theta*d_phi*/
   }        
   bin[i][10]= sin(i*pi/180)*d_theta*d_phi*bin[i][1]+ 2*sum;  /* col. 10 is a temp. store for J.cm-1 over ALL phi's */   
}
i=20;
sum1=0.0;
for (i=20; i<180; i++)           /* start from 20 to avoid all the 'nan' at the lower end */
{ sum1= sum1+bin[i][10];
  }
printf("\n");                   
printf("                             For this grating                \n");
printf("             Rough estimate of total radiated energy (per bunch) over hemisphere = ");
printf("%.3e", sum1*0.1*lgr);              /* no need for x2, since +-phi has been taken into account*/
printf(" J"); printf("\n");
percent=sum1*0.1*lgr/(n_e_t*1.602177e-19*(gam-1)*0.511*1e6);
printf(" This is equal to "); printf("%.3e",percent); printf(" of the energy in a single bunch \n"); 
printf("\n"); printf("\n");

printf("This case had the following parameters:\n");
printf("gamma= %-5.1f \n",gam);
printf("beam height(mm)= %-6.3f \n",x0);
printf("pulse length (FWHM,ps)= %-6.3f \n",pulse_len);
printf("total number of electrons in the bunch= %-6.3e \n",n_e_t);
printf("pulse shape code is= %1i \n",pulse_shp);
printf("asymmetry factor= %-3.1f \n",epsl);
if (pulse_shp==7)
{apb=pulse_len; a=apb/(1+epsl);
 printf("for Lorentz shape a+b= %-5.3f ",apb);
 printf(" ps and leading edge fraction = %-5.3f \n",a);}
printf("grating period(mm)= %-5.3f \n",el);
printf("emission order= %1i \n",m);
printf("PHI step= %-4.2f \n",phistep);
printf("limiting value of phi= %-3.1f ",(phistep*(philmt-1))); printf(" deg. \n");
printf("\n");

flag=0;
if (!flag) printf("Do you want to create a .txt file for the diff. energy values? 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=='n') goto esc3;
printf("Name of output file?? ");
scanf("%s",&outfile_name[0]);
out_file=fopen(outfile_name,"w");
i=1;
for (i=1; i<180; i++)
{     fprintf(out_file,"\n");
      ii=0;
      for (ii=0; ii<11; ii++)
      {if (ii==0) fprintf(out_file, "%-5.1f  ", bin[i][ii]);
      else fprintf(out_file, " %.3e ", bin[i][ii]);
      }        
}
fprintf(out_file,"\n");
fprintf(out_file,"gamma= %6.1f \n",gam);
fprintf(out_file,"x0= %6.3f \n",x0);
fprintf(out_file,"pulse length= %6.3f \n",pulse_len);
fprintf(out_file,"no. of electrons= %-4.3e \n",n_e_t);
fprintf(out_file,"pulse shape= %1d \n",pulse_shp);
fprintf(out_file,"grating period= %-5.3f \n",el);
fprintf(out_file,"order= %1d \n",m);
fprintf(out_file,"phi step= %3.1f \n",phistep);
fprintf(out_file,"no. of steps in phi= %2d \n",philmt);
fclose(out_file);
esc3: printf("\n");
     
printf(" Angle   Theta2    Theta1    diff_energy/bunch   energy/bunch \n");
printf("                                J/sr/cm              J \n");
i=10;
for (i=10; i<171; i++)
{
    thet[i]=i;
    theta=thet[i]*pi/180;                                              /* change to radians*/
   /*thet_1 and thet_2 below are the max. possible angles for a given observation angle*/
  /* NB. !!!!definition changed from previous versions of the code!!!*/
  /* now determined by the Winston cone acceptance angle */

    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[i][0]=theta*180/pi;
    outbin[i][1]=int_thet_2;
    outbin[i][2]=int_thet_1;   
/*  n0 is total no. of angles accepted, modified May 08; must be 13 values */
    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;
/* somehow the following seems to work...........*/    
    sum_th=0;
    j=1;  
    for (j=1; j<n0+2; j++)
      {
        sum_th=sum_th+bin[jstart+j-1][9];
      };
    aven=sum_th/(n0+1);                                            /*take average over detected theta angles*/
    sum_tr=aven*0.1*lgr*domeg_m;                                    /*changed 28/3/07 to energy*/
    outbin[i][3]=aven;
    outbin[i][4]=sum_tr;
    printf("%-5.1f",theta*180/pi); printf("   "); printf("%5d",int_thet_2); printf("      ");
    printf("%5d",int_thet_1); printf("       ");
    printf("%-6.3e",aven); printf("         "); printf("%-6.3e \n",sum_tr);
    
};
printf(" Angle   Theta2    Theta1    diff_energy/bunch   energy/bunch \n");
printf("                                J/sr/cm              J \n");
printf("\n");
flag=0;
if (!flag) printf("Do you want to create an output .txt file for the collected energy values? 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");    
    i=10;
    for (i=10; i<171; i++)
    { fprintf(out_file,"\n"); ii=0;
      for (ii=0; ii<5; ii++)          
      	  {if (ii<3) fprintf(out_file, " %-5.1f \t", outbin[i][ii]);
	  else if (ii==3) fprintf(out_file, " %-6.3e \t", outbin[i][ii]);
          else  fprintf(out_file, " %-6.3e ", outbin[i][ii]); }             
    }
    fprintf(out_file,"\n");
    fprintf(out_file," This case had the following parameters: \n");
    fprintf(out_file,"gamma= %6.1f \n",gam);
    fprintf(out_file,"beam height(mm)= %6.3f \n",x0);
    fprintf(out_file,"pulse length (FWHM, ps)= %6.3f \n",pulse_len);
    fprintf(out_file,"no. of electrons= %-4.3e \n",n_e_t);
    fprintf(out_file,"pulse shape code= %1d \n",pulse_shp);
    if (pulse_shp!=7)
    {fprintf(out_file,"asymmetry factor= %-3.1f \n",epsl);}
    else
    {fprintf(out_file,"Lorentz shape with a+b= %-5.3f ",apb);
     fprintf(out_file, "and leading fraction of bunch= %-4.2f \n",a);}
    fprintf(out_file,"grating period(mm)= %-5.3f \n",el);
    fprintf(out_file,"order= %1d \n",m);
    fprintf(out_file,"phi step= %3.1f \n",phistep);
    fprintf(out_file,"limiting phi= %3.1f ",((philmt-1)*phistep)); fprintf(out_file," deg.\n");
    fprintf(out_file,"first column= emission angle theta \n");
    fprintf(out_file,"second column= theta2 \n");
    fprintf(out_file,"third column= theta1 \n");
    fprintf(out_file,"fourth column= diff. energy per bunch(J/sr/cm) \n");
    fprintf(out_file,"fifth column= energy per bunch (J) \n");
    fprintf(out_file, " \n ");
    fclose(out_file);
    printf(" Done it, goodbye \n");
}
else
{ printf(" OK, re-entry options? ");
  printf("\n");}
                                    /*re-entry options*/
printf("Type:\n");
printf("1 for new beam position \n");
printf("2 for new sigma_x \n");
printf("3 for new bunch shape\n");
printf("anything else to exit this programme\n");
scanf("%d",&ans1);
if (ans1==1) goto esc20;
else if (ans1==2) goto esc24;
else if (ans1==3) goto esc1;
printf(" End of programme\n");

return(0); 
}

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

static double FUN(double x)
{
   double k;
   extern double x0,sigma_x,lam_e;
      k=2/lam_e;
   return (exp(-(x-x0)*(x-x0)/(2*sigma_x*sigma_x))*exp(-k*x));
}

static double FUN_X(double x)
{
   double k;
   extern double x0,sigma_x,lam_e;
      k=1/lam_e;
   return (exp(-(x-x0)*(x-x0)/(2*sigma_x*sigma_x))*exp(-k*x));
}

static double LOR1(double t)                  /*time integral for leading edge of Lorentz shape*/
{ 
    extern double a;
    return (1/(a*a+t*t));
}

static double LOR2(double t)                  /*time integral for trailing edge of Lorentz shape*/
{
    extern double b;
    return (1/(b*b+t*t));
}

