#include <stdio.h>
#include <math.h>

#define N 1000
#define r 1.0

double norm_cube(double theta, double x, double y, double z) {

  double Lx,Ly,Lz,L;

  Lx=x-r*cos(theta);    
  Ly=y-r*sin(theta);    
  Lz=z;                
  L=sqrt(Lx*Lx+Ly*Ly+Lz*Lz);
  return L*L*L;
}

/* Evaluate the trapezoid rule approximation to a given function */
/* Assumes that the data is evenly spaced*/ 

double trapezoid(double x[],double f[]) {

  int i;
  double sum=0.5*(f[0]+f[N]);
  double h=fabs(x[1]-x[0]);
  /* Add on to sum the remaining elements */
  for (i=1;i<=(N-1);i++)
    sum+=f[i];
  
  return h*sum;
}

main() {

  int i;
  double x=0.0,y,z;
  double L3,Bx,By,Bz;
  double theta[N],fx[N],fy[N],fz[N];
  FILE *fid;

  fid=fopen("mag-field","w");

  for (y=-2.05;y<=1.95;y=y+0.1)
    for (z=-1.55;z<=1.45;z=z+0.1) {
      
      /* Form the function and the theta array */
      for (i=0;i<N;i++) {
        theta[i]=i*2*M_PI/N;
        L3=norm_cube(theta[i],x,y,z);
        fx[i]=z*r*cos(theta[i])/L3;
        fy[i]=z*r*sin(theta[i])/L3;
        fz[i]=(cos(theta[i])*(r*cos(theta[i])-x)+sin(theta[i])*(r*sin(theta[i])-y))/L3;
      }
      
      fprintf(fid,"%10.6lf %10.6lf %10.6lf %10.6lf %10.6lf %10.6lf\n",x,y,z,\
              trapezoid(theta,fx),trapezoid(theta,fy),trapezoid(theta,fz));
      
    }
  fclose(fid);
}

/* plot 'mag-field' using 2:3:($5/70):($6/70) with vectors head filled lt 2 */

