/*
 * File: simple.c
 * Author: Andrew Salo
 * Date: 20.11.02
 *
 */

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

#define FI -M_PI_4


FILE *fin, *fout;

/* Point structure */
struct POINT {
  float x;  // coordinates
  float y;
  int i_x;  // indicators
  int i_y;
  float c_x;  // counters
  float c_y;
};


/* Functions */
int get (float *, float *);
void rotate (float *, float *, float *, float *);
int is_way_point (struct POINT *, float, float);


/* Main procedure */
int main (int argc, char **argv)
{
  struct POINT p1, p2;
  float eps = 1, x1, y1, x2, y2;

  /* Open files */
  if (argc != 3)
    {
      printf ("Usage: %s file_in file_out\n", argv[0]);
      exit (1);
    }
    
  if ((fin = fopen (argv[1], "r")) == NULL)
    {
      perror (argv[1]);
      exit (1);
    }

  if ((fout = fopen (argv[2], "w")) == NULL)
    {
      perror (argv[2]);
      fclose (fin);
      exit (1);
    }

  /* Try to get first point */
  if (get (&x1, &y1) == -1)
    return -1;

  p1.x = x1;
  p1.y = y1;
  p1.i_x = 0;
  p1.i_y = 0;
  p1.c_x = 0;
  p1.c_y = 0;

  /* Rotate point */
  rotate (&p1.x, &p1.y, &p2.x, &p2.y);

  p2.i_x = 0;
  p2.i_y = 0;
  p2.c_x = 0;
  p2.c_y = 0;

  /* Get next point */
  while (get (&x1, &y1) != -1)
    {
      /* Is angle greater than PI/4 ? */
      if (sqrt ((x1 - p1.x) * (x1 - p1.x) +
		(y1 - p1.y) * (y1 - p1.y)) < eps * sqrt (2))
	continue;

      /* Rotate coordinates */
      rotate (&x1, &y1, &x2, &y2);

      if (is_way_point (&p1, x1, y1) | is_way_point (&p2, x2, y2))
	fprintf (fout, "%.4f %.4f\n", p1.x, p1.y);

      p1.x = x1;
      p1.y = y1;
      p2.x = x2;
      p2.y = y2;
    }

  /* Last point */
  fprintf (fout, "%.4f %.4f\n", p1.x, p1.y);

  /* Close files*/
  fclose (fin);
  fclose (fout);
  
  return 0;
}



/* Get next point */
int get (float *x, float *y)
{
  fscanf (fin, "%f %f", x, y);

  if (feof (fin))
    return -1;

  return 0;
}



/* Rotate coordinates */
void rotate (float *x1, float *y1, float *x2, float *y2)
{
  *x2 = *x1 * (float)cos (FI) + *y1 * (float)sin (FI);
  *y2 = *y1 * (float)cos (FI) - *x1 * (float)sin (FI);
}



/* Check if pt1 is a way-point */
int is_way_point (struct POINT *pt, float x, float y)
{
  int delta_x, delta_y, wp = 0;

  /* Set delta_x */
  if ((x - pt->x) >= 0)
    delta_x = 1;
  else
    delta_x = -1;

  /* Set delta_y */
  if ((y - pt->y) >= 0)
    delta_y = 1;
  else
    delta_y = -1;

  /* Direction changed */
  if (delta_x != pt->i_x)
    {
      if (fabsf (pt->c_x) >= fabsf (pt->c_y))
	wp = 1;

      pt->c_x = 0;
      pt->i_x = delta_x;
    }

  /* Direction changed */
  if (delta_y != pt->i_y)
    {
      if (fabsf (pt->c_y) >= fabsf (pt->c_x))
	wp = 1;

      pt->c_y = 0;
      pt->i_y = delta_y;
    }

  /* Change counters */
  pt->c_x += x - pt->x;
  pt->c_y += y - pt->y;

  return wp;
}



