/* 
   Copyright (C) 1999 E. H. Haley
   
   treeage() goes with snatches() in that sn writes a data file of
   tiles (fname, score, exp) and that's what treeage reads.  (Used to
   be matches wrote whole nodes and triage read those.)
   
   
 */

#include <stdio.h>
#include <stdlib.h>
#include <jpeglib.h>
#include "lib/loadj.h"
#include <GL/glut.h>
#include <X11/Xlib.h>
#include "lib/tile.h"

int displayw,displayh;
tile *dcont; //display_contender
//"display" meaning accessible from functions such as display(void)
tfile tatch;

void init(int aardc, char **aardv)
{
  int check;
  FILE *matchfile;

  glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

  if (aardc<2) exit(0);
  if ((matchfile=fopen(*++aardv,"r"))==NULL)
    { fprintf(stderr, "can't open %s\n",*aardv); exit(1); }
  
  check=fread(&tatch,sizeof(tfile),1,matchfile);
  printf("%d\n",tatch.nnodes);
  displayw=displayh=tatch.side;

  dcont=(tile *)malloc(tatch.nnodes*sizeof(tile));
  check=fread(dcont,tatch.nnodes*sizeof(tile),1,matchfile);
  fclose(matchfile);
}



void display(void)
{
  int p,w,h,c, l,i,j,k, check, zint,exp;
  float zoom;
  JSAMPLE *arr;

  p=-1;
  for(l=1; l>0; l<<=1) //forever
    for(i=0; i<l; i++)
      for(j=0; j<l; j++)
	{
	  if (++p>=tatch.nnodes) return; 

	  exp = dcont[p].exp;
	  zint = 1 << (exp>0 ? exp : -exp);
	  zoom = exp>0 ? (float)zint : 1.0/(float)zint;
	  glPixelZoom(zoom,zoom);
	  
	  glRasterPos2i(i*displayw/l, j*displayh/l);

	  if((arr=rjf(dcont[p].fname,&w,&h,&c))!=NULL)
	    glDrawPixels(w,h, c<2?GL_LUMINANCE:GL_RGB, GL_UNSIGNED_BYTE, arr);
	  
	  printf("p=%d; f=%s; original w=h=%d; wanted=%d; exp=%d; score=%d\n",
		 p,
		 dcont[p].fname, 
		 w,
		 displayw/l,
		 dcont[p].exp,
		 dcont[p].score);
	      
	  fflush(stdout);
	  free(arr);
	}
}

void mouse(int button, int state, int x, int y)
{
  free(dcont);
  exit(0);
}

int main(int aardc, char **aardv)
{
  init(aardc, aardv);
  glutInit(&aardc, aardv);

  glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA);
  glutInitWindowSize(displayw,displayh);
  glutCreateWindow(aardv[0]);
  glutDisplayFunc(display);
  glutMouseFunc(mouse);

  glViewport(0,0, (GLfloat)displayw,(GLfloat)displayh);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluOrtho2D(0.0, (GLfloat)displayw, 0.0, (GLfloat)displayh);
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

  glutMainLoop();
  exit(0);
}

