#include "../../model/geometry/datarose_geometry.h"
#include "../../model/geometry/density_legend_geometry.h"
#include "../../view/state0.h"
#include "../actions/set_ortho.h"
#include "reshape.h"
#include <GL/glut.h>
#include <math.h>
#include <stdio.h>

#define S state0

void
reshape (int w, int h)
{
  glMatrixMode (GL_PROJECTION);
  glLoadIdentity ();

  /*
   * Scale the zoom region to the aspect ratio of the window.
   */
  if (S.zoom.active)
    {
      if (w >= h)
	{
	  double scale
	    =
	    (((S.zoom.coords[1] -
	       S.zoom.coords[0]) * ((double) w / (double) h)) -
	     (S.zoom.coords[1] - S.zoom.coords[0])) * 0.5;

	  S.ortho.min_x = S.zoom.coords[0] - scale;
	  S.ortho.max_x = S.zoom.coords[1] + scale;
	  S.ortho.min_y = S.zoom.coords[2];
	  S.ortho.max_y = S.zoom.coords[3];
	}
      else
	{
	  double scale
	    =
	    (((S.zoom.coords[3] -
	       S.zoom.coords[2]) * ((double) h / (double) w)) -
	     (S.zoom.coords[3] - S.zoom.coords[2])) * 0.5;

	  S.ortho.min_x = S.zoom.coords[0];
	  S.ortho.max_x = S.zoom.coords[1];
	  S.ortho.min_y = S.zoom.coords[2] - scale;
	  S.ortho.max_y = S.zoom.coords[3] + scale;
	}
    }

  else
    {
      /*
       * This scaling produces an odd effect when the coordinates are
       * not centered at 0,0.  When 0,0 is the lower left rather than
       * the center this reshape is a bit unnatural since the image is
       * not centered in the middle of the window.  Try chaning this
       * to use the method used above for the zoom region scaling.
       */
      if (w <= h)
	{
	  S.ortho.min_x = S.ortho_min;
	  S.ortho.max_x = S.ortho_max;
	  S.ortho.min_y = S.ortho_min * (double) h / (double) w;
	  S.ortho.max_y = S.ortho_max * (double) h / (double) w;
	}
      else
	{
	  S.ortho.min_x = S.ortho_min * (double) w / (double) h;
	  S.ortho.max_x = S.ortho_max * (double) w / (double) h;
	  S.ortho.min_y = S.ortho_min;
	  S.ortho.max_y = S.ortho_max;
	}
    }

  set_ortho ();

  glMatrixMode (GL_MODELVIEW);

  // Set the viewport equal to the size of the window.
  glViewport (0, 0, (GLsizei) w, (GLsizei) h);

  density_legend_geometry ();
  //  datarose_geometry ();

  return;
}