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

#define NFD "dati.txt"
#define NFF "filtra.txt"
#define NFI "in.txt"
#define NFO "out.txt"
 
#define STRLEN   256

typedef float* pfloat;
typedef FILE*  pfile;
typedef struct _dot
 {float x,y;
 } dot;
typedef dot*  pdot;

float get_float_from_file(pfile f)
 {char s[STRLEN]; 
  fscanf(f,"%s",s);
  return atof(s);
 }

int get_int_from_file(pfile f)
 {char s[STRLEN]; 
  fscanf(f,"%s",s);
  return atoi(s);
 }
int main(void)
 {pfile    f1,f2;
  unsigned i,ndt,nd;
  float    vx,vy,vv,bx,by,m,s;
  pdot     pd;
  pfloat   pdist;
  
  if ((f1=fopen(NFD,"r"))==NULL) goto file_err;
  if ((f2=fopen(NFF,"r"))==NULL) goto file_err;
  ndt=get_int_from_file(f2);
  if ((pd=(pdot)malloc(sizeof(dot)*ndt))==NULL) goto mem_err;
  for(i=nd=0,bx=by=0.0;i<ndt;i++)
   {vx=get_float_from_file(f1);
    vy=get_float_from_file(f1);
    if (get_float_from_file(f2)!=0.0) 
     {bx+=pd[nd].x=vx;  
      by+=pd[nd].y=vy;
      nd++; 
     }
    }
  fclose(f1); fclose(f2);
  if ((f1=fopen(NFI,"w"))==NULL) goto file_err;
  if ((f2=fopen(NFO,"w"))==NULL) goto file_err;
  printf("Baricentro (x,y)=(%.2f,%.2f)\n",bx/=nd,by/=nd); 
  if ((pdist=(pfloat)malloc(sizeof(float)*nd))==NULL) goto mem_err;
  for(i=0,m=s=0.0;i<nd;i++)
   {vx=pd[i].x-bx; vy=pd[i].y-by;
    m+=vv=pdist[i]=pow(vx*vx+vy*vy,0.5);
    s+=vv*vv;
    printf("Distanza di (%.2f,%.2f) dal baricentro=%.2f\n",pd[i].x,pd[i].y,vv);
   }
  printf("Soglia di scarto=%.2f\n",s=2.0*pow(nd*s-m*m,0.5)/nd);
  for(i=0;i<nd;i++) fprintf((pdist[i]<s)?f1:f2,"(%.2f,%.2f)\n",pd[i].x,pd[i].y); 
  fclose(f1); fclose(f2); free(pd); free(pdist);
  return EXIT_SUCCESS;

  file_err: printf("Problema coi files!\n");     return EXIT_FAILURE;
  mem_err:  printf("Problema colla memoria!\n"); return EXIT_FAILURE;
 }
