// This program reads data from any text file containing lines of the
// form x y code (code = 1: pen down; code = 0: pen up), and displays
// lines, all fitting into a given viewport.  The file name is to be
// supplied as a program argument.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <error.h>
#include <errno.h>

#include "grsys.h"

#define float64 double

int main(int argc, char **argv) {
  if (argc != 2 ) {
    fprintf(stderr, "syntax: %s filename\n", argv[0]);
    exit(EXIT_FAILURE);
  }
  FILE *f = fopen(argv[1], "r");
  if (f == NULL) {
    fprintf(stderr, "%s: %s\n", argv[0], strerror(errno));
    exit(EXIT_FAILURE);
  }

  grsys_InitWindow();
  
  float64 x, y ;
  int code ;
  
  for (;;) {
    int rc = fscanf(f, "%lf %lf %d\n", &x, &y, &code);
    if (rc != 3) {
      if (feof(f)) {
        break;
      }
      fprintf(stderr, "%s: %s\n", argv[0], strerror(errno));
      exit(EXIT_FAILURE);
    }
    grsys_UpdateWindowBoundaries(x, y);
  }

  int rc = fseek(f, 0L, SEEK_SET);
  if (rc < 0L) {
    fprintf(stderr, "%s: %s\n", argv[0], strerror(errno));
    exit(EXIT_FAILURE);
  }

  grsys_InitGr("adjust.hpg"); // plot file desired
  grsys_ViewportBoundaries(grsys_XMin, grsys_XMax,
    grsys_YMin, grsys_YMax, 0.9);

  grsys_Move(grsys_XMin, grsys_YMin);
  grsys_Draw(grsys_XMax, grsys_YMin);
  grsys_Draw(grsys_XMax, grsys_YMax);
  grsys_Draw(grsys_XMin, grsys_YMax);
  grsys_Draw(grsys_XMin, grsys_YMin); // show viewport

  for (;;) {
    int rc = fscanf(f, "%lf %lf %d\n", &x, &y, &code);
    if (rc != 3) {
      if (feof(f)) {
        break;
      }
      fprintf(stderr, "%s: %s\n", argv[0], strerror(errno));
      exit(EXIT_FAILURE);
    }
    x = grsys_XViewport(x);
    y = grsys_YViewport(y);
    if (code != 0 ) {
      grsys_Draw(x, y);
    } else {
      grsys_Move(x, y);
    }
  }
  grsys_EndGr();
  exit(EXIT_SUCCESS);
  return EXIT_FAILURE;
}
