

#include <linux/videodev.h>
#include <stdlib.h>
#include <vga.h>
#include <vgagl.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/mman.h>

#include <unistd.h>

const int 	x_size = 320;//352;
const int 	y_size = 240;//288;

video_capability  capability;
video_mbuf gb_buffers = { 2*0x151000, 0, {0,0x151000 }};
video_mmap vid_buffer;

char *vid_map = NULL;
int vid_fd = -1;


int main(void)
{

   if ((vid_fd = open("/dev/video", O_RDWR)) == -1) 
   {
	printf("Error opening video0\n");
	return(1);
   }

   if (ioctl(vid_fd, VIDIOCGCAP,&capability) == -1)
   {
	printf("Error: ioctl(fd,VIDIOCGCAP,&capability)\n");
	return(1);
   }

   fcntl(vid_fd, F_SETFD, FD_CLOEXEC);

    if (ioctl(vid_fd, VIDIOCGMBUF,&gb_buffers) == -1) 
    {
        printf("Error: Error getting buffers, I think\n");
    	return(1);
    }

    vid_map = (char *)mmap(0,gb_buffers.size,PROT_READ|PROT_WRITE,MAP_SHARED,vid_fd,0); 

    if (vid_map == NULL) 
    {
        printf("Error: Mmap returned NULL\n");
    	return(1);
    }


//   vga_init();
//   vga_setmode(G320x240x256);

    // Set up out capture to use the correct resolution
    vid_buffer.width =  x_size;
    vid_buffer.height = y_size;
    vid_buffer.format = VIDEO_PALETTE_RGB24;
    vid_buffer.frame = 0;


    int count = 500;
 
    while (count--)
    {

 
    	if (ioctl(vid_fd, VIDIOCSYNC, 0) == -1) 
        {
            printf("Error on sync!\n"); 
            return(1);
        }

    	if (ioctl(vid_fd, VIDIOCMCAPTURE, &vid_buffer) == -1) 
        {
	   	   printf("Error: Grabber chip can't sync (no station tuned in?)\n"); 
    		return(1);
    	}

	
        /*char *base = vid_map;

        for ( int y = 0; y < y_size ; y++)
            for ( int x = 0; x < x_size ; x++)
             {
                 unsigned char c = (*(base) + *(base+1)+ *(base+2) ) / 48 + 17;
       
                 if (c < 16) c = 16;
                 if (c > 31) c = 31;
 
                 vga_setcolor(c);
                 vga_drawpixel(x, y);
                 base+=3;
//base+=3;
             }*/

    }

//    // Return screen to text mode.
  //  vga_setmode(TEXT);
//
   return(0);
}


