/*                                                 -*-mode:C;tab-width:8-*-
 * 
 * cxg_show.c -- print on a terminal in "ascii scale"
 *
 * Copyright (C) 1995 Alessandro Rubini  -- rubini@ipvvis.unipv.it
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <termios.h> /* winsize */

#include "cxdrv.h"

#define B (512*512)
unsigned char buf[B];
unsigned char *optr;
int hires=0;
int howmany=256*256;
int side=256;


char alpha[]=" .,:|IO#";

int main(int argc, char **argv)
{
  FILE *f=stdin;
  int fd;
  int i,x,y,X,Y;
  int show=1; int grab=1;
  double xstep;
  double ystep;
  struct winsize win;
  unsigned char *obuf;

  
  /*
   * First, try to adapt your size.
   */
  if (ioctl(2 /* stderr */, TIOCGWINSZ, &win)<0)
    { win.ws_col=80; win.ws_row=50; }
  obuf=malloc(win.ws_col*win.ws_row);
  if (!obuf) { perror("malloc()"); exit(1); }
  xstep=256.0/win.ws_col;
  ystep=256.0/(win.ws_row-1);
  

  while (argc>1 && argv[1][0]=='-')
	{
	switch(argv[1][1])
	  {
	  case 'h': hires=1; howmany=B; xstep*=2; ystep*=2; side=512; break;
	  case 'r': hires=-1; howmany/=4; xstep/=2; ystep/=2; side=128; break;
	  case 'R': hires=-2; howmany/=16; xstep/=4; ystep/=4; side=64;break;
	  case 'g': show=0; break;
	  case 's': grab=0; break;
	  default: fprintf(stderr,"Unsupported option\n");
	  }
	argv++; argc--;
	}

  if (argc>1)
	f=fopen(argv[1],"r");
  if (!f)
	{perror(argv[1]);exit(1);}

  fd=fileno(f);
  if (grab)
	{
	Cxg_GrabLive(fd);
	Cxg_SetBit(fd,CXG_BIT_DISP_RAM);
	Cxg_LowRes(fd,hires<1);
	Cxg_RamPage(fd,CXG_AUTODETECT);
	Cxg_SetPage(fd,0); /* page 0 */

	if (hires<0)
	  {
	  Cxg_Roi roi;
	  
	  roi.x=roi.y=64;
	  roi.wid=roi.hei=128;
	  roi.count=1;
	  if (hires<-1)
		roi.wid=roi.hei=64;
	  Cxg_SetRoi(fd,&roi);
	  }
	}

  for (i=0;; i++)
	{
	int tot;
	
	for (tot=0; tot<howmany; tot+=read(fd,buf+tot,howmany-tot))
	  ;
	
	optr=obuf;
	if (show)
	  {
	  for (y=0; y < win.ws_row-1; y++)
		{
		Y=y*ystep;
		for (x=0; x < win.ws_col; x++)
		  {
		  X=x*xstep;
		  *(optr++)=alpha[buf[X+Y*side]>>5];
		  }
		*(optr++)='\n';
		}
	  write(fileno(stdout),"\x1b[000;000H",10);
	  write(fileno(stdout),obuf,win.ws_col*(win.ws_row-1));
	  }
	else
	  write(fileno(stdout),buf,howmany);
	}

  return 0;
}



