#include "drawfigs.h"
#include <ioprotos.h>
#include <js.h>
#include <ps.h>

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

#define NORMTERMS 9

float nrandom(void)
  {
    float s = 0.0;
    int j;
    for (j=0; j < NORMTERMS; j++) { s += 2.0*frandom() - 1.0; }
    return (s * ((float) sqrt (1.5 / (double) NORMTERMS)));
  }

void gen_figure (
    char *name,
    float xmin, float xmax, 
    float ymin, float ymax,
    void draw_proc(FILE *f),
    int eps_format
  )
  {
    float wx = xmax - xmin;
    float wy = ymax - ymin;
    float wm = (wx > wy ? wx : wy);
    double scale = 6.0 * 72.0 / wm;
    double hc = 4.25 * 72.0;
    double hmin = hc - scale * wx / 2.0;
    double hmax = hc + scale * wx / 2.0;
    double vc = 6.50 *72.0;
    double vmin = vc - scale * wy / 2.0;
    double vmax = vc + scale * wy / 2.0;

    char* file_name = txtcat(name, ( eps_format ? ".eps" : ".ps"));
    
    FILE *f = fopen(file_name, "w");

    if (f == NULL)
      { error (txtcat("gen_figure: can't open output file ", file_name)); }

    if (eps_format) 
      { ps_begin_figure(f, 
          xmin, xmax, ymin, ymax,
          hmin, hmax, vmin, vmax,
          1, 1
        );
      }
    else
      { ps_begin_document(f);
        ps_begin_page(f, 1, xmin, xmax, ymin, ymax, hmin, hmax, vmin, vmax, 1, 1);
        ps_add_caption(f, name);
      }
      
    draw_proc(f);
    
    if (eps_format)
      { ps_end_figure(f);
      }
    else
      { ps_draw_frame(f);
        ps_end_page(f);
        ps_end_document(f, 1);
      }
      
    fclose(f);
  }