/* cansmi.c */

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

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

#define MAXSMI 5000
#define THR_COUNT 4

/*==========================================================
 * Each thread reads until EOF.  When a thread gets a
 * SMILES, it'll canonicalize it.  Note that all the
 * I/O stream locking is handled invisibly by the stdio
 * library.
 ========================================================= */

void *do_cansmi_forever(void *arg)
{
  char      line[MAXSMI];
  dt_Handle mol;
  dt_String cansmi;
  int       lencan;

  fprintf(stderr, ".");
  while (1)
    {
      if (feof(stdin))
	pthread_exit((void *)1);
  
      /*** This handles concurrancy in the input stream
	automatically as part of the stdio library ***/

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

      mol = dt_smilin(strlen(line), line);
      if (mol == NULL_OB)
	fprintf(stderr, "smilin failed.\n");
      cansmi = dt_cansmiles(&lencan, mol, 1);

      /*** printf handles output concurrancy ***/

      if (0 < lencan)
	printf("%.*s\n", lencan, cansmi);
      dt_dealloc(mol);
    }
  return (NULL);
}

main(int argc, char *argv[])
{
  pthread_t thr;
  int i, thr_count;
  
  dt_mp_initialize();

  /*** Read in the count of threads to use from the 
    user, if available ***/

  if ((argc != 2) ||
      (1 != sscanf(argv[1], "%d", &thr_count)))
    thr_count = THR_COUNT;

  /*** Start up the required threads ***/

  fprintf(stderr, "thr_count: %d\n", thr_count);
  for (i = 0; i < thr_count; i++)
    pthread_create(&thr, NULL, do_cansmi_forever, NULL);

  return(NULL);
}