/*
 * point.h
 * Header file for defining the Point object and
 * functions that operate on it
 */

// Point type definition
struct Point{
  char *label;
  int x, y;
};

// Function prototypes (declarations)
struct Point *initPoint(char *, int, int);
void readPoint(struct Point *);
double distance(struct Point, struct Point);
void printPoint(struct Point);


/*
 * point.c
 * Implementation file for operations defined on the Point object
 */

/* Again, compiler directives go first */
/* Like import, #include brings in definitions needed to use these libraries */

#include <stdio.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "point.h"  // reads the Point type def file from current directory

/* Function definitions */

// initPoint acts as a Point constructor (note the use of malloc)
struct Point *initPoint(char *label, int x, int y) {
   struct Point *p;

   p = (struct Point *) malloc(sizeof(struct Point));
   p->x = x;
   p->y = y;
   p->label = label;  // likely to fail, beware subtle error here!
   return p;
}

// initializes the Point p with information input by the user
void readPoint(struct Point *p) {
  char label[11];       // limit label to 10 chars

  printf("%s", "\nEnter x- and y-coordinates: ");
  scanf("%d %d", &(p->x), &(p->y));
  printf("%s", "\nEnter the label: ");
  getchar();  //eat newline
  scanf("%10s", label); // safety first!
  // NB: could try this instead
  // fgets(label, 10, stdin);

  p->label = malloc(11);
  strcpy(p->label, label);
}

// returns the Euclidean distance between two Points
double distance(struct Point a, struct Point b) {
   double result;
   double xpart, ypart;
   xpart = (a.x - b.x) * (a.x - b.x);
   ypart = (a.y - b.y) * (a.y - b.y);
   result = sqrt(xpart + ypart);
   return result;
}

// output a Point
void printPoint(struct Point p){
  printf("Point %s: [%d, %d]\n", p.label, p.x, p.y);  
}