#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include "rx.h"
#include "rxparse.h"
#include "rxrun.h"
#include "ctype.h"

static void
pretty_fputc (c, fp)
     int c;
     FILE * fp;
{
  if (isprint (c))
    fputc (c, fp);
  else
    fprintf (fp, "{%o}", c);
}

extern char * rx_compile_pattern ();

int
main (argc, argv)
     int argc;
     char ** argv;
{
  char fastmap[256];
  unsigned char * file;
  off_t file_size;
  char * error;
  struct rx_buf rx;
  {
    struct stat stat;
    int fd;
    
    fd = open (argv[2], O_RDONLY, 0);
    if (fd < 0)
      exit(1);
    fstat (fd, &stat);
    file_size = stat.st_size;
    file = (unsigned char *)malloc (file_size + 10);
    file[0] = '\n';
    file[file_size + 1] = '\n';
    if (read (fd, file + 1, file_size) != file_size)
      exit (2);
  }
  rx.no_sub = 0;
  rx.fastmap = fastmap;
  error = rx_compile_pattern (argv[1], strlen(argv[1]), &rx);
  if (error)
    {
      fprintf (stderr, "Failed to compile regex: %s\n", error);
      exit (1);
    }
  {
    int pos = 0;
    struct re_registers regs;
    int x;
    regs.num_regs = 10;
    regs.start = (regoff_t *) malloc (10 * sizeof(regoff_t));
    regs.end = (regoff_t *) malloc (10 * sizeof(regoff_t));
    while (pos < file_size)
      {
	int eol;
	int match;
	match = rx_search (&rx, file, file_size, pos, file_size - pos,
			       &regs);
	if (match < 0)
	  exit (0);
	else
	  {
	    int x;
	    for (pos = regs.start[0]; file[pos] != '\n'; --pos) ;
	    ++pos;
	    for (x = 0; x < regs.num_regs; ++x)
	      if (regs.start[x] >= 0)
		{
		  printf ("%d: ", x);
		  fwrite (file + regs.start[x],
			  sizeof (unsigned char),
			  regs.end[x] - regs.start[x],
			  stdout);
		  putchar ('\n');
		}
	    for (eol = pos; file[eol] != '\n'; ++eol) ;
	    file[eol] = '\0';
	    fprintf (stdout, "%s\n", file + pos);
	    file[eol] = '\n';
	    ++eol;
	    pos = eol;
	  }
      }
  }
}
