/* Draws a histogram of n values of a variable in array data(1..n) */
/* in the range datmin to datmax using nbin bins. If "oldwin" is   */
/* true, the histogram is plotted in the current window. If not,   */
/* the routine calls "plenv" to set up the graphics environment.   */

#include "plplot.h"
#include <math.h>

void plhist(n,data,datmin,datmax,nbin,oldwin)
int n, nbin;
int oldwin;
float data[], datmin, datmax;
{
      int i, bin, level;
      float x[201], y[201], dx, ymax;
      
      glev(&level);
      if (level<1) fatal("Please call PLSTAR before PLHIST.");
      if (level<3 && oldwin)
              fatal("Please set up window before calling PLHIST.");
      
      if (nbin < 1 || nbin > 200)
              fatal("Cannot have <1 or >200 bins in PLHIST.");
      if (datmin >= datmax)
              fatal("Data range invalid in PLHIST.");
      
      dx = (datmax-datmin) / nbin;
      for (i=0; i<=nbin; i++) {
        x[i] = datmin + i*dx;
        y[i] = 0.0;
      }

      for (i=0; i<n; i++)  {
        bin = (data[i] - datmin)/dx;
        if (bin >= 0 && bin < nbin) y[bin]++;
      }

      if (!oldwin) {
        ymax = 0.0;
        for (i=0; i<nbin; i++) ymax = max(ymax,y[i]);
        plenv(datmin,datmax,0.0,1.1*ymax,0,0);
      }
         
      plbin(nbin+1,x,y,0);
}
