/* Copyright 2004 Dan Risacher (not that I'm proud of it, mind you) */
/* May be used for any purpose so long as copyright remains in the source code */

#include <stdio.h>
#include <fcntl.h>
#include <linux/cdrom.h>

int
main(int argc, char **argv)
{
  int fd, arg=0;
  int res1, res2;

  if(argc<2){
    fprintf(stderr,"Usage:\n\t%s <device>\n",argv[0]);
    return 1;
  }

  fd = open(argv[1], O_RDONLY|O_NONBLOCK);

  if (fd < 0) {
    fprintf(stderr,"%s cannot be opened.  exiting.\n",argv[1]);
    return 0;
  }

  while (1) {
    res1 = ioctl(fd, CDROM_MEDIA_CHANGED, &arg);
    res2 = ioctl(fd, CDROM_DRIVE_STATUS, &arg);

    if (res1 == 0 && res2 == CDS_DISC_OK ) { 
      printf ("valid media\n");
      close(fd);
      exit(0);
    }
    sleep(1);
  }
  close(fd);
  return 0;
}
