# include <stdio.h>
# include <unistd.h>
# include <fcntl.h>
# include <sys/ioctl.h>
# include <linux/videodev.h>

# define MAX_BYTES (640*480*3)

unsigned char image[MAX_BYTES];

int main()
 {
  int fd;
  long length;
  struct video_window video_win;


  if ((fd = open("/dev/video", O_RDONLY)) == -1)
   {
    perror("read_image: Can't open device");
    return(1);
   }

  if (ioctl(fd, VIDIOCGWIN, &video_win) == -1)
   {
    perror("read_image: Can't get video window");
    return(1);
   }
  length = video_win.width * video_win.height * 3;
  if (length > MAX_BYTES)
   {
    fprintf(stderr, "read_image: Image too large.\n");
    return(1);
   }

  if (read(fd, image, length) == -1)
   {
    perror("read_image: Error while reading");
    return(1);
   }

  printf("P6\n%d %d\n255\n", video_win.width,
         video_win.height);
  fwrite(image, 3, video_win.width*video_win.height,
         stdout);

  close(fd);

  return(0);
 }
