/*

 * shapes.c

 * This program reads an input file called shapes.txt, analyzes it and

 * computes the area of each shape it specifies.

 */

 

#include <stdio.h>

 

#define MAX_LINE 80

#define PI       3.14159265

 

/* Definition of a point: */

struct _Point

{

  float x;

  float y;

};

 

typedef struct _Point Point;

 

int main ()

{

  Point  p, q, r;

  float  radius;

  char   line[MAX_LINE];

  FILE   *p_file;

  float  area;

 

  /* Open the input file. */

  p_file = fopen ("shapes.txt", "r");

 

  /* Check that the file has been successfully opened. */

  if (p_file == NULL)

  {

    printf ("The input file shapes.txt was not found.\n");

    return (1);

  }

 

  /* Read the file. */

  while (! feof (p_file))

  {

    /* Get the next line. */

    if (fgets (line, MAX_LINE, p_file) == NULL)

      break;

 

    /* The last character in the line is EOL - get rid of it. */

    line[strlen(line) - 1] = '\0';

 

    /* Ignore empty lines. */

    if (strlen(line) == 0)

      continue;

 

    /* The input file should contain descriptions of shapes, using the

       following format:

       | RECTANGLE

       | x1 y1  x2 y2

       or:

       | CIRCLE

       | x y  r

       or:

       | TRIANGLE

       | x1 y1  x2 y2  x3 y3

     */

    if (strncmp (line, "TRI", 3) == 0)

    {

      /* Read the three vertices of the triangle. */

      fscanf (p_file, "%f %f %f %f %f %f",

              &(p.x), &(p.y), &(q.x), &(q.y), &(r.x), &(r.y));

 

      printf ("Read a triangle, ");

      area = (p.x*(q.y - r.y) - p.y*(q.x - r.x) + (q.x*r.y - q.y*r.x)) / 2;

 

    }

    else if (strncmp (line, "RECT", 4) == 0)

    {

      /* Read the to corners of the rectangle. */

      fscanf (p_file, "%f %f %f %f",

              &(p.x), &(p.y), &(q.x), &(q.y));

 

      printf ("Read a rectangle, ");

      area = (p.x - q.x) * (p.y - q.y);

    }

    else if (strncmp (line, "CIRC", 4) == 0)

    {

      /* Read the center and radius of the circle. */

      fscanf (p_file, "%f %f %f",

              &(p.x), &(p.y), &radius);

 

      printf ("Read a circle, ");

      area = PI * radius * radius;

    }

    else

    {

      printf ("Unknown shape (%s) - skipping.\n", line);

      continue;

    }

 

    /* Read until the end of the current line. */

    fgets (line, MAX_LINE, p_file);

   

    /* Print the area. */

    area = (area < 0) ? -area : area;

    printf ("its area is %g\n", area);

  }

 

  /* Close the file. */

  fclose (p_file);

 

  return (0);

}