/* calculate_f - calculate the load-handling capacity for a hydraulic cyl */

/* This is a demonstration of how an analysis tool would be incorporated into
   a set of n-dim modeling languages for doing design.  In this case, we
   picked the simple example of a piston.  The design data for a single piston
   is stored in two postgres classes; this tool calculates the equation

               p * PI * di ^ 2
          F = -----------------------
                       4.0

   p and di live in the hydraulicCyl and cylinder classes, respectively.
   The output f is stored into hydraulicCyl. */

#include <stdio.h>
#include <math.h>
#include <libpq-fe.h>
#include "analysis-tools.h"

char *prog_name = "<>";
main(argc, argv)
     int argc;
     char **argv;
{
  int n_groups, n_tuples, n_fields;
  double p, di, f;
  PortalBuffer *pbuf;
  char write_back_query[512], *dbName, *getenv();
  extern char *PQhost, *PQport;

#ifdef PTHREADS
  pthread_init();
#endif

  PQhost = getenv("DATABASE_HOST");
  PQport = getenv("DATABASE_PORT");

  prog_name = argv[0];

  dbName = getenv("DATABASE_NAME");
  if (!dbName)
    dbName = "abbndim";
  PQsetdb(dbName);
  PQexec("begin");
  PQexec("retrieve portal dportal (hydraulicCyl.p,cylinder.d_inside)");
  PQexec("fetch all in dportal");
  pbuf = PQparray("dportal");
  n_groups = PQngroups(pbuf);

  if (n_groups != 1) {
    DIE_1("got back %d groups, was expecting 1", n_groups);
  }
  n_tuples = PQntuplesGroup(pbuf, 0);
  if (n_tuples != 1) {
    DIE_1("got back %d tuples, was expecting 1", n_tuples);
  }
  n_fields = PQnfieldsGroup(pbuf, 0);
  if (n_fields != 2) {
    DIE_1("got back %d fields, was expecting 2", n_fields);
  }

  p = get_floating_point_attribute_val(pbuf, 0, 0);
  di = get_floating_point_attribute_val(pbuf, 0, 1);
  f = (p * M_PI * (di * di)) / 4.0;

  printf("p\t= %lf\ndi\t= %lf\nf\t= %lf\n", p, di, f);

  sprintf(write_back_query, "replace hydraulicCyl (f = %lf)", f);
  PQexec(write_back_query);

  PQexec("close dportal");
  PQexec("end");
  PQfinish();

  exit(0);
}
