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

#include "descartes.h"

#define MAXPOINTS 50

/* Array of points read from the user */
point_t points[MAXPOINTS];

/* Number of points in the points array */
int num_points = 0;

/* size of square drawn round points */
const int OFFSET = 4;

/* routine to mark a point as selected or unselected.
   Second argument is 1 for selected, 0 for unselected. */
void MarkSelected(point_t p, int selected) {
  int x = XCoord(p), y = YCoord(p);
  rectangle_t r = Rectangle(Point(x-(OFFSET-1),y-(OFFSET-1)),
    Point(x+(OFFSET-1),y+(OFFSET-1)));
  if ( selected ) FillRectangle(r); else ClearRectangle(r);
}

/* routine to draw a square round a point */
void MarkPoint(point_t p) {
  int x = XCoord(p), y = YCoord(p);
  /* BEGIN ANSWER (a) -- do not delete this line */

  // ADD YOUR CODE HERE

  /* END ANSWER (a) -- do not delete this line */
}

/* Given a point p, find the first point in points which is within
   OFFSET of it (in each coordinate), and return the index.
   Return -1 if no point found. */
int FindPoint(point_t p) {
  int x = XCoord(p), y = YCoord(p);
  /* BEGIN ANSWER (b) -- do not delete this line */

  // ADD YOUR CODE HERE

  /* END ANSWER (b) -- do not delete this line */
  return -1;
}

/* This routine takes a point from the user, looks it up using FindPoint,
   and then asks the user to try again if they weren't in one of the 
   selected points. It returns the successful result from FindPoint,
   or -1 if the user clicks the middle button.
*/
int AskPoint() {
  int i;
  while ( 1 ) {
    point_t p = GetPoint();
    if ( XCoord(p) == -1 ) { return -1; }
    i = FindPoint(p);
    if ( i >= 0 ) { return i; }
    printf("That wasn't in one of your points. Try again.\n");
  }
  return -1;
}

int main(void) {
  OpenGraphics();

  printf("Enter your points (click middle button to finish).\n");
  while ( num_points < MAXPOINTS ) {
    point_t p = GetPoint();
    if ( XCoord(p) == -1 ) break;
    points[num_points++] = p;
    MarkPoint(p);
  }
  if ( num_points == MAXPOINTS ) { 
    printf("That's enough points!\n");
  }
  printf("Now you can draw lines between points.\n\n");

  int finished = 0;
  while ( ! finished ) {
    /* indexes in the array of the start and end points for the line */
    int start, end;
    printf("Select a start point (or middle click to finish)\n");
    start = AskPoint();
    if ( start == -1 ) {
      finished = 1;
    } else {
      MarkSelected(points[start],1);
      printf("Now select an end point.\n");
      /* BEGIN ANSWER (c) -- do not delete this line */

      // ADD YOUR CODE HERE

      /* END ANSWER (c) -- do not delete this line */
    }
  }
  
  CloseGraphics();
  return 0;
}
