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

#define FILE_DOTS "./punti.txt"
#define FILE_SEGS "./segmenti.txt"
#define STRLEN    256
#define DT        0.01
#define TA        0
#define TB        1

typedef struct _dot {float x,y;} dot;
typedef dot*   pdot;
typedef struct _seg {dot  d1,d2;} seg;
typedef seg*   pseg;
typedef FILE*  pfile;
typedef float* pfloat;
typedef int*   pint;

int leggi_val_float(pfile pf,pfloat pv)
 {char s[STRLEN];
  if (!fscanf(pf,"%s",s)) return 0;
  *pv=atof(s);
  return 1;
 }

int leggi_val_int(pfile pf,pint pv)
 {char s[STRLEN];
  if (!fscanf(pf,"%s",s)) return 0;
  *pv=atoi(s);
  return 1;
 }

int leggi_dot(pfile pf,pdot pd)
 {if (!leggi_val_float(pf,&(pd->x))) return 0;
  if (!leggi_val_float(pf,&(pd->y))) return 0;
  return 1;
 }

int leggi_seg(pfile pf,pseg ps)
 {if (!leggi_dot(pf,&(ps->d1))) return 0;
  if (!leggi_dot(pf,&(ps->d2))) return 0;
  return 1;
 }

int main(void)
 {pfile    pf;
  int      id,is,nd,ns,best_id;
  pdot     pd,pd2;
  pseg     ps,ps2;
  float    t,x,y,dx,dy,x1,y1,dist_ps,best_dot_x,best_dot_y,xx,yy,d;
 
  if ((pf=fopen(FILE_DOTS,"r"))==NULL)         goto file_err;
  if (!leggi_val_int(pf,&nd))                  goto file_err;
  if ((pd=(pdot)malloc(sizeof(dot)*nd))==NULL) goto mem_err;
  for (id=0,pd2=pd;id<nd;id++,pd2++) if(!leggi_dot(pf,pd2)) {free(pd); goto file_err;}
  fclose(pf);

  if ((pf=fopen(FILE_SEGS,"r"))==NULL)         goto file_err;
  if (!leggi_val_int(pf,&ns))                  goto file_err;
  if ((ps=(pseg)malloc(sizeof(seg)*ns))==NULL) goto mem_err;
  for (is=0,ps2=ps;is<ns;is++,ps2++) if(!leggi_seg(pf,ps2)) {free(pd); free(ps); goto file_err;}
  fclose(pf);

  for(is=0,ps2=ps;is<ns;is++,ps2++)
   {dist_ps=FLT_MAX;
    x1=ps2->d1.x; dx=ps2->d2.x-x1;
    y1=ps2->d1.y; dy=ps2->d2.y-y1;
    for(t=TA;t<=TB;t+=DT)
     {x=x1+t*dx; y=y1+t*dy;
      for(id=0,pd2=pd;id<nd;id++,pd2++)
       {xx=x-pd2->x;yy=y-pd2->y;
        d=xx*xx+yy*yy;
        if (d<dist_ps) {dist_ps=d; best_id=id; best_dot_x=x; best_dot_y=y;}
       }
     }
    printf("Il punto (%.2f,%.2f) del segmento (%.2f,%.2f,%.2f,%.2f) dista dal punto (%.2f,%.2f) %.2f\n",
           best_dot_x,best_dot_y,x1,y1,dx+x1,dy+y1,pd[best_id].x,pd[best_id].y,sqrt(dist_ps));

   }

  return EXIT_SUCCESS;

  file_err: printf("File   Error!\n");  return EXIT_FAILURE;
  mem_err:  printf("Memory Error!\n");  return EXIT_FAILURE;
 }
