# include "data.h"

int tv (int argc, char **argv) {
  
  int N, j, status, Npix, Ncolors, size, ISLOG, NNcol;
  char buffer[1024], buffer2[100];
  double a1, a2, max, min, zero, range;
  float *in;
  char *out, *outbuffer, *p, *tmpstring;
  int Ximage, Nimage;
  Coords coords;
  Buffer *buf;

  Nimage = -1;
  if (N = get_argument (argc, argv, "-n")) {
    remove_argument (N, &argc, argv);
    Nimage = atof (argv[N]);
    remove_argument (N, &argc, argv);
  }
  if (!GetImage (&Ximage, &Nimage)) return (FALSE);

  /* shell exits on pipe close, FIX */
  if (N = get_argument (argc, argv, "-kill")) {
    close (Ximage);
    Ximage = 0;
    return (TRUE);
  }

  min = max = 0.0;
  ISLOG = FALSE;
  if (N = get_argument (argc, argv, "-log")) {
    remove_argument (N, &argc, argv);
    ISLOG = TRUE;
  }

  if ((argc != 2) && (argc != 4)) {
    fprintf (stderr, "USAGE: tv <buffer> [zero range] [-n Nimage] [-log] [-kill]\n");
    return (FALSE);
  }

  GetImageScale (&zero, &range);
  if (argc == 4) {
    zero = atof (argv[2]);
    range = atof (argv[3]);
    if (range == 0.0) range = 0.001;
    SetImageScale (zero, range);
  }

  if ((buf = SelectBuffer (argv[1], OLDBUFFER, TRUE)) == NULL) return (FALSE);
  GetCoords (&coords, &buf[0].header);

  Npix = buf[0].matrix.Naxis[0]*buf[0].matrix.Naxis[1];
  size = Npix * sizeof (char);
  in = (float *) (buf[0].matrix.buffer);
  ALLOCATE (outbuffer, char, Npix);
  out = outbuffer;

  status = write (Ximage, "READ", 4); /* tell Ximage to look for the incoming image */

  /* convert from (float) internal rep to 1 byte chars -- depends on how many colors Kii owns*/
  read (Ximage, buffer, 16); 
  sscanf (buffer, "%*s %d", &Ncolors); 

  /* need to invert the logic if range < 0 */
  /* define color table, */
  NNcol = Ncolors - 1;
  if (ISLOG) {
    range = MAX (2, range);
    a1 = Ncolors / log10 (range);
    for (j = 0; j < Npix; j++, in++, out++) {
      *out = (char) MIN (a1 * log10 (MAX (*in - zero, 1.0)), NNcol);
    }
  }
  if (!ISLOG) {
    a1 = Ncolors / range;
    a2 = Ncolors * zero / range;
    for (j = 0; j < Npix; j++, in++, out++) {
      *out = (char) MIN (MAX (a1 * *in - a2, 0), NNcol);
    }
  }
  
  /* done with the conversion, now send Ximage the converted picture */
  sprintf (buffer, "%8d %8d 8 1 %f %f ", buf[0].matrix.Naxis[0], buf[0].matrix.Naxis[1], 0.0, 1.0);
  sprintf (buffer2, "NBYTES: %6d ", strlen (buffer));
  write (Ximage, buffer2, 16);
  write (Ximage, buffer, strlen (buffer));
  
  sprintf (buffer, "%f %f %f %f %d ", zero, range, min, max, size);
  sprintf (buffer2, "NBYTES: %6d ", strlen (buffer));
  write (Ximage, buffer2, 16);
  write (Ximage, buffer, strlen (buffer));

  sprintf (buffer, "%f %f %g %g %g ", coords.crval1, coords.crpix1, coords.cdelt1, coords.pc1_1, coords.pc1_2);
  sprintf (buffer2, "NBYTES: %6d ", strlen (buffer));
  write (Ximage, buffer2, 16);
  write (Ximage, buffer, strlen (buffer));

  sprintf (buffer, "%f %f %g %g %g ", coords.crval2, coords.crpix2, coords.cdelt2, coords.pc2_1, coords.pc2_2);
  sprintf (buffer2, "NBYTES: %6d ", strlen (buffer));
  write (Ximage, buffer2, 16);
  write (Ximage, buffer, strlen (buffer));

  p = strrchr (buf[0].file, '/');
  if (p == (char *) NULL) p = buf[0].file;
  else p++;
  tmpstring = strcreate (p);
  sprintf (buffer, "%s %s %s ", coords.ctype, tmpstring, buf[0].name);
  free (tmpstring);
  sprintf (buffer2, "NBYTES: %6d ", strlen (buffer));
  write (Ximage, buffer2, 16);
  write (Ximage, buffer, strlen (buffer));

  write (Ximage, outbuffer, size);

  free (outbuffer);

  SetImageName (argv[1]);
  set_str_variable ("TV", argv[1]);
  return (TRUE);

}


/* 
projections and coordinates:

IRAS:
CTYPE1  = 'LL      '                    /TANGENT PLANE (L)                     
CRVAL1  =         0.100000D+02          /R.A. OF MAP CENTER  *** SEE COMMENT   
CDELT1  =        -0.133333D-01          /SEPARATION IN L (DEG)                 
CRPIX1  =                  128          /MAPCENTER IN L                        
CROTA1  =         0.000000E+00          /NO ROTATION            
                                                                               
CTYPE2  = 'MM      '                    /TANGENT PLANE (M)                     
CRVAL2  =         0.410000D+02          /DEC. OF MAP CENTER  *** SEE COMMENT   
CDELT2  =         0.133333D-01          /SEPARATION IN M (DEG)                 
CRPIX2  =                  128          /MAP CENTER IN M                       
CROTA2  =         0.000000E+00          /NO ROTATION                           

HIRAS:
CTYPE1  = 'RA---TAN          ' / PRIMARY AXIS NAME                             
CRVAL1  =   1.000000000000E+01 / PRIMARY REFERENCE VALUE                       
CDELT1  =  -5.555555555556E-03 / PRIMARY PIXEL SEPARATION                      
CRPIX1  =   2.560000000000E+02 / PRIMARY REFERENCE PIXEL                       
CUNIT1  = 'DEGREE            ' / PRIMARY AXIS UNITS                            

CDELT2  =   5.555555555556E-03 / PRIMARY PIXEL SEPARATION                      
CRPIX2  =   2.560000000000E+02 / PRIMARY REFERENCE PIXEL                       
CRVAL2  =   4.100000000000E+01 / PRIMARY REFERENCE VALUE                       
CTYPE2  = 'DEC--TAN          ' / PRIMARY AXIS NAME                             
CUNIT2  = 'DEGREE            ' / PRIMARY AXIS UNITS                            

PROJTYPE= 'GNOMON    '                                                         
COORDSYS= 'EQUATORIAL     '                                                    

gene (small FOV linear):
RA_O
RA_X 
RA_Y 
DEC_O
DEC_X
DEC_Y


*/

# ifdef NEWTVMODE  
  {
    double *pixvalues, slope;

    ALLOCATE (pixvalues, double, Ncolors + 1);
    range = fabs (range);
    for (i = 0; i < Ncolors + 1; i++) {
      if (ISLOG) {
	pixvalues[i] = i*range / NNcol + zero;
      }
      if (!ISLOG) {
	pixvalues[i] = pow (10.0, i*log10(range - 1.0) / NNcol) + zero - 1.0;
      }      
    } 
    for (j = 0; j < Npix; j++, in++, out++) {
      if (*in < pixvalues[0]) {
	i = 0;
      } else {
	if (*in > pixvalues[NNcol]) {
	  i = NNcol;
	} else {
	  for (i = 0; (*in < pixvalues[i]) || (*in > pixvalues[i+1]); ) {
	    slope = 1.0 / (pixvalues[i+1] - pixvalues[i]);
	    i = MIN (MAX (0, i + (*in - pixvalues[i]) * slope), NNcol);
	  }
	}	
      }
      /* for (i = 0; (i < Ncolors - 1) && (pixvalues[i] < *in); i++); */
      *out = i;
    }
    free (pixvalues);
  }
# endif
