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

#define MaxN 100000
#define true 1
#define false 0

typedef struct PointType {
  long x, y;
} PointType;

static int Init = true;
static long N;
static PointType P[MaxN + 3];
static PointType A, B;

static void ReadIn(void)
{
  FILE *inFile = NULL;
  long x, y, i;

  inFile = fopen("fence.in","r");
  if (inFile == NULL){
    printf("ERROR: input file fence.in not found\n");
    exit(1);
  }
  fscanf(inFile, "%ld%ld%ld%ld%*[^\n]", &A.x, &A.y, &B.x, &B.y);
  getc(inFile);
  fscanf(inFile, "%ld%*[^\n]", &N);
  getc(inFile);
    if (N > 100000){
       printf("ERROR: parameter N too large\n");     
      exit(1); 
    }
  for (i = 1; i <= N; i++) {
    fscanf(inFile, "%ld%ld%*[^\n]", &x, &y);
    if (abs(x)>20000 || abs(y)>20000){
       printf("ERROR: coordinate value too large\n");     
      exit(1); 
    }
    
    getc(inFile);
    P[i].x = x;
    P[i].y = y;
  }  /*for i*/
  P[N+1] = A;
  P[N+2] = B;
  if (inFile != NULL)
    fclose(inFile);
  inFile = NULL;
  Init = false;
}  /*Readin*/

int Drift(long x, long y, long z)
{
  /*Returns: +1 if x->y->z turns left,
             0 if x,y and z are collinear,
            -1 if x->y->z turns right*/
  long crosspr;

  if (Init)
    ReadIn();
  if (x < 1 || y < 1 || z < 1 || x > N + 2 || y > N + 2 || z > N + 2) {
    printf("ERROR: Illegal argument of Drift\n");
    exit(1);
  }
  crosspr = (P[y].x - P[x].x) * (P[z].y - P[x].y) -
	    (P[z].x - P[x].x) * (P[y].y - P[x].y);
  if (crosspr < 0)
    return -1;
  else if (crosspr > 0)
    return 1;
  else
    return 0;
}  /*Drift*/

long GetN(void)
{
  if (Init) {
    ReadIn();
    Init = false;
  }
  return N;
}

void Answer(long left, long right)
{
  FILE *outFile = NULL;
  if (Init) {
    printf("ERROR: You must call GetN first\n");
    exit(1);
  }
  outFile = fopen("fence.out", "w");
  fprintf(outFile, "%ld %ld\n", left, right);
  fclose(outFile);
  outFile = NULL;
  exit(0);
}
