/*  randsig -- select an random signature
 * 
 *  Copyright (C) 2002-2003 Sascha Wilde
 * 
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 *------------------------------------------------------------------------- 
 * 
 * reads an databasefile (for format see below) on standart-in and
 * writes an random cite/signature to standart-out.
 * 
 * an optional numeric argument can be given to select an specific
 * signature/cite
 * 
 * The db-file is simple, it's an a textfile with a bunch of signatures/
 * cites.  Every signature/cite starts with an line with "-- " on its own,
 * this delemiter-line is _not_ echoed to stdout!
 * 
 *-------------------------------------------------------------------------
 * $Id: randsig.c,v 1.5 2003/01/18 08:48:43 wilde Exp $ */

#ifndef lint
static char vcid[] = "$Id: randsig.c,v 1.5 2003/01/18 08:48:43 wilde Exp $";
#endif /* lint */

#define MAXLINE 500
#define SEP "-- \n"

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

int
main (int argc, char **argv)
{
  char line[MAXLINE];
  int sel, i = 0;


  /* Thirst we count the number of sigs */
  while(fgets(line, MAXLINE -1, stdin))
    {
      (strncmp(SEP, line, strlen(line)) == 0) && i++;
    }

  /* look if a selection is given as an argument */
  if ( !((argc == 2) && (sel = atoi(argv[1]))) )
    {
      /* Calc a random selection if not */
      srand ((unsigned int) time ((time_t *) NULL));
      sel = (int) ((double) i * rand () / (RAND_MAX) + 1);
    }
  else
    {
      sel = (sel % i);
    }

  /* now write the Selection to std-out */
  rewind (stdin);
  i=0;

  while(fgets(line, MAXLINE -1, stdin) && (i <= sel))
    {
      if (strncmp(SEP, line, strlen(line)) == 0)
	i++;
      else if (i == sel)
	fputs(line, stdout);
    }

  return(0);
}
