/* Author: Ram Samudrala (me@ram.org)
 * Version: O1.0
 * Detail: <http://www.ram.org/computing/plan/plan.html>
 * May 16, 1993.
 *
 * See the URL above for terms of use and general help.
 */

/******************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include "plan.h"

void quote_plan(FILE *plan_fp, int num_quotes);

/******************************************************************/

int main(int argc, char *argv[])
{
  FILE *plan_fp, *original_plan_fp;
  char line[MAX_LINE_LENGTH];

  while (1)
    {
      if ((plan_fp = fopen(PLAN_FILE, "w")) == NULL)
	{
	  fprintf(stderr, "%s: couldn't open %s for writing!\n", argv[0], PLAN_FILE);
	  return 0;
	}

      if ((original_plan_fp = fopen(ORIGINAL_PLAN_FILE, "r")) == NULL)
	{
	  fclose(plan_fp);
	  fprintf(stderr, "%s: couldn't open %s for reading!\n", argv[0], ORIGINAL_PLAN_FILE);
	  return 0;
	}

      system(LOGFINGER_COMMAND);
      
      while(fgets(line, MAX_LINE_LENGTH, original_plan_fp))
	fprintf(plan_fp, "%s", line);
      fclose(original_plan_fp);

      if (argc == 2)
	if (atoi(argv[1]) > 0) 
	  quote_plan(plan_fp, atoi(argv[1]));

      fclose(plan_fp);
      sleep(1);            
    }
  return 1;
}

/******************************************************************/

void quote_plan(FILE *plan_fp, int num_quotes)
{
  char line[MAX_LINE_LENGTH];
  FILE *quotes_fp;
    
  sprintf(line, "%s%ld", QUOTES_FILE_PREFIX, (time(NULL) % num_quotes));  
  if ((quotes_fp = fopen(line, "r")) == NULL)
    return;  
  while (fgets(line, MAX_LINE_LENGTH, quotes_fp))
    fprintf(plan_fp, "%s", line);
  fprintf(plan_fp, "\n");
  fclose(quotes_fp);
  return;
}

/******************************************************************/
