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

#define NCAM 10          /* numero de caminhadas */
#define NPAS 1000        /* numero de passos em cada */

#define frand() (double)rand()/(RAND_MAX+1.)  /* excluindo valor 1 */ 
                                      
int main(){
   
  FILE *camin;            /* arquivos de saida, dados */ 
  FILE *fpout = NULL;     /* arquivos de saida, gnuplot */
  int semente = 300;       /* semente para o frand */
  int i,j;
  int pos[NCAM];
 /* abre os arquivos de saida */
  camin = fopen("caminhada.dat","w");  
  srand(semente);
   
  for (i=0; i<NCAM; i++) pos[i]=0.0;      /* todos comecam da origem */  
  for (j=0; j<NPAS; j++){                /* loop nos passos */
    fprintf(camin,"%d",j); 
    for (i=0;i<NCAM; i++) fprintf(camin,"\t%d",pos[i]);   /* imprime posicao */
    fprintf(camin,"\n");
    for (i=0;i<NCAM; i++){                /* passo */
       if(frand()<0.5){
         pos[i]=pos[i]+1;
       }else{
         pos[i]=pos[i]-1;
       }
    }
  }

  /* fecha os arquivos de saidas */
  fclose(camin);

  /* gnuplot */

  fpout=fopen("mplot.plt", "w+");   
  fprintf(fpout, "set term post eps enhanced color\n");
  fprintf(fpout, "set out 'Grafico.eps'\n");
  fprintf(fpout, "set title ' Caminhada aleatoria '\n");
  fprintf(fpout, "set xlabel 'Tempo'\n");
  fprintf(fpout, "set ylabel 'X(t) '\n");
  fprintf(fpout, "set key left top\n");
  fprintf(fpout, "set xrange[0:1010]\n");
  fprintf(fpout, "set yrange[-70:70]\n");     
  fprintf(fpout, "plot 'caminhada.dat'    using 1:2 notit \n"); 
  fprintf(fpout, "replot 'caminhada.dat'  using 1:3 notit \n");
  fprintf(fpout, "replot 'caminhada.dat'  using 1:4 notit\n");
  fprintf(fpout, "replot 'caminhada.dat'  using 1:5 notit\n");
  fprintf(fpout, "replot 'caminhada.dat'  using 1:6 notit\n");
  fprintf(fpout, "replot 'caminhada.dat'  using 1:7 notit\n"); 
  fprintf(fpout, "replot 'caminhada.dat'  using 1:8 notit\n");
  fprintf(fpout, "replot 'caminhada.dat'  using 1:9 notit\n");
  fprintf(fpout, "replot 'caminhada.dat'  using 1:10 notit\n");
  fprintf(fpout, "replot 'caminhada.dat'  using 1:11 notit\n");   
  fclose(fpout);  
  system("gnuplot  'mplot.plt'");
  system("evince Grafico.eps");
  system("rm mplot.plt");

  return 0;
}
