/* Copyright (C) 1999 E. H. Haley
   
   was going to graphically show area averages for things run through
   targa, but really it seems to be working, just fom the #s.
   
   now use it to reconstruct something out of the sector top40s.
   
 */

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

int w,h;
res *tree;
tfile tarf;

void init(int aardc, char **aardv)
{
  int check;
  FILE *targafile;
  
  glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

  if ((targafile=fopen(*++aardv,"r"))==NULL)
    { fprintf(stderr, "1. can't open %s\n",*aardv); exit(1); }

  check=fread(&tarf, sizeof(tfile),1,targafile);
  tree=(res *)malloc(tarf.nnodes*sizeof(res));
  check=fread(tree, tarf.nnodes*sizeof(res),1,targafile);
  fclose(targafile);
  w=h=tarf.side; 
}

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

  /* display should take each top40, plop it in an array the right
    size that's otherwise a bunch of zeroes, and inverse WT that.
    Draw it in the right place, treeage-style.
    
   */

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

	  scr=(float *)calloc(w*h*3/(l*l),sizeof(float));
	  arr=(JSAMPLE *)malloc(w*h*3/(l*l)*sizeof(JSAMPLE));

	  for(k=0; k<40; k++)
	    scr[3*(tree[p].entry[k].index[0]
		   + (w/l)*(tree[p].entry[k].index[1]))
		   + tree[p].entry[k].index[2]]
	      //e.g. [3*(i+w*j)+k]
	      = tree[p].entry[k].val;
	    
	  //	  wtd(scr,w/l,h/l,3,-1,daub4);
	  wtd(scr,w/l,h/l,3,-1,dobb4);
	  for(k=0; k<w*h/(l*l); k++)
	    yiq256rgb(scr+3*k,arr+3*k);

	  glRasterPos2i(i*w/l, j*h/l);
	  glDrawPixels(w/l, h/l, GL_RGB, GL_UNSIGNED_BYTE, arr);

	  free(arr);
	  free(scr);
	}
}

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

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

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

  glViewport(0,0, (GLfloat)w,(GLfloat)h);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluOrtho2D(0.0, (GLfloat)w, 0.0, (GLfloat)h);
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

  glutMainLoop();
  exit(0);
}


