#include <stdio.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/types.h>

static char query_in_fname[64] ;
static file_count = 0 ;

int mg_db_available(char *colldir, char *collname)
{
  char fname[FILENAME_MAX] ;
  struct stat statbuf ;

  sprintf(fname, "%s/%s.rebuilding", colldir, collname) ;
  if (stat(fname, &statbuf))
    return 1 ;
  else return 0 ;
}

void do_mg_query(char *qstring, char *colldir, char *collname, 
		 char **p_out_fname)
{
  sprintf(query_in_fname, "/tmp/mgqueryin%d", getpid()) ;

  *p_out_fname = (char *)malloc(sizeof(char) * 32) ;

  sprintf(*p_out_fname, "/tmp/mgqueryout%d@%d", getpid(),
	  file_count++) ;
  {
    FILE *in_fp ;
    in_fp = fopen(query_in_fname, "w") ;
    fprintf(in_fp, ".output > %s\n", *p_out_fname) ;
    fprintf(in_fp, ".set doc_sepstr \"entrnum %%n\\n\"\n") ;
    fprintf(in_fp, "%s\n", qstring) ;
    fprintf(in_fp, ".quit\n") ;
    fclose(in_fp) ;
  }

  {
    char command[128] ;
    sprintf(command, "echo '.input < %s'|/usr/local/mg-1.2/bin/mgquery -d %s -f %s",
	    query_in_fname, colldir, collname) ;
    system(command) ;
  }
  unlink(query_in_fname) ;
}

void do_mg_query_from_file(char *qname, char *colldir, char *collname,
			   char **p_out_fname)
{
  FILE *qfile ;
  
  qfile = fopen(qname, "r") ;
  if (qfile != NULL) {

    sprintf(query_in_fname, "/tmp/mgqueryin%d", getpid()) ;

    *p_out_fname = (char *)malloc(sizeof(char) * 32) ;

    sprintf(*p_out_fname, "/tmp/mgqueryout%d@%d", getpid(),
	    file_count++) ;
    {
      FILE *in_fp ;
      in_fp = fopen(query_in_fname, "w") ;
      fprintf(in_fp, ".output > %s\n", *p_out_fname) ;
      fprintf(in_fp, ".set doc_sepstr \"entrnum %%n\\n\"\n") ;
      while (!feof(qfile)) {
	char c ;
	c = fgetc(qfile) ;
	if (!feof(qfile)) fputc(c, in_fp) ;
      }
      fprintf(in_fp, "\n.quit\n") ;
      fclose(in_fp) ;
    }

    {
      char command[128] ;
      sprintf(command, "echo '.input < %s'|/usr/local/mg-1.2/bin/mgquery -d %s -f %s",
	      query_in_fname, colldir, collname) ;
      system(command) ;
    }
    unlink(query_in_fname) ;
  }
}
