#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <thread.h>

#include "dt_smiles.h"
#include "dt_smarts.h"
#include "mp_utils.c"

#define MAXSMI 5000
#define MAX_THREADS 40

/*============================================
 * do_smarts() - Test a single SMILES against
 * a pattern and quit.
 ============================================= */

void *do_smarts(void *arg)
{
  char      line[MAXSMI];
  dt_Handle mol, mypat;
  dt_String cansmi;
  int       lencan, i;

  mypat = (dt_Handle)arg;

  fprintf(stderr, ".");
  while (1)
    {
      if (feof(stdin))
        pthread_exit(NULL);

      if (!gets(line))
        pthread_exit((void *)1);

      /*** smartsfilter_lock actually has the dt_mp_lock(mypat) here,
        before dt_smilin() ***/
      mol = dt_smilin(strlen(line), line);
      if (mol == NULL_OB)
        fprintf(stderr, "smilin failed.\n");

      dt_mp_lock(mypat);
      if (dt_match(mypat, mol, TRUE))
        printf("%s\n", line);
      dt_mp_unlock(mypat);
      dt_dealloc(mol);
    }
  return (NULL);
}

main(int argc, char *argv[])
{
  dt_Handle pattern;
  void *status;
  int i, ok = TRUE;
  int thr_count = 4;
  
  dt_mp_initialize();
  
  /*** Get SMARTS from command line ***/
  
  if ((2 != argc) && (3 != argc))
    ok = FALSE;
  else
    {
      pattern = dt_smartin(strlen(argv[1]), argv[1]);
      if (NULL_OB == pattern)
	{
	  fprintf(stderr, "Can't parse SMARTS: \"%s\"\n", argv[1]);
	  exit(1);
	}
    }
  
  if ((argc == 3) && (1 != sscanf(argv[2], "%d", &thr_count)))
    ok = FALSE;
  
  if (thr_count < 0) thr_count = 1;
  if (thr_count > MAX_THREADS) thr_count = MAX_THREADS;
  
  if (!ok)
    {
      fprintf(stderr, "usage: %s SMARTS [num_threads]\n", argv[0]);
      exit(1);
    }

  fprintf(stderr, "thr_count: %d\n", thr_count);
  for (i = 0; i < thr_count; i++)
    pthread_create(&thr, NULL, do_smarts, (void *)pattern);
  
  thr_exit(NULL);
}