/* 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 from 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 tilf;

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

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

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

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

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

  for(i=0; i<tilf.nnodes; i++)
    {
      scr=(float *)malloc(w*h*3*sizeof(float));
      arr=(JSAMPLE *)malloc(w*h*3*sizeof(JSAMPLE));
      
      for(k=0; k<40; k++)
	scr[3*(tree[i].entry[k].index[0]
	       + w*(tree[i].entry[k].index[1]))
	   + tree[i].entry[k].index[2]]
	  //e.g. [3*(i+w*j)+k]
	  = tree[i].entry[k].val;
      
      //      wtd(scr,w,h,3,-1,daub4);
      wtd(scr,w,h,3,-1,dobb4);
      for(k=0; k<w*h; k++)
	yiq256rgb(scr+3*k,arr+3*k);
      
      glRasterPos2i(0,0);
      glDrawPixels(w, h, 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);
}

