/* Author: Ram Samudrala (me@ram.org)
 * Version: O1.0
 * Detail: <http://www.ram.org/computing/sc/sc.html>
 * November 22, 1995; Copyright (c) 1995 by Ram Samudrala.
 *
 * See the URL above for terms of use and general help.
 */

#include "cgi_common.h"
#include "cgi_error_handlers.h"
#include "cgi_defines.h"
#include "sc_defines.h"
#include "items.h"

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

void read_items(char filename[], item items[])
{
  FILE *prices_fp;
  char line[(ITEM_DESCRIPTION_STRING_LENGTH*2)+40], *cp;
  int i = 0;

  open_file(&prices_fp, filename, "r", "read_items");
  
  while (fgets(line, 200, prices_fp))
    if ((line[0] != '#') && (line[0] != '\0') && (line[0] != '\n'))
      {
	i++;
	check_max_count(i, MAX_ITEMS, "read_items");
	check_eof(sscanf(line, "%s %d %d %lf %lf", item_name(&items[i]), &item_ql(&items[i]), 
			 &item_qh(&items[i]), &item_price(&items[i]), 
			 &item_shipping_price(&items[i])), "read_items");
	if ((cp = strchr(line, (int) '|')) != NULL)
	  {
	    cp++;
	    cp[strlen(cp)-1] = '\0';
	    strcpy(item_description(&items[i]), cp);
	  }
	else
	  strcpy(item_description(&items[i]), item_name(&items[i]));
      }
  total_items(&items) = i;
  close_file(&prices_fp, filename, "read_items");

  
/* #ifdef DEBUG
  {
    FILE *debug_fp;
    
    debug_fp = fopen("/usr/people/ram/debug.log", "a");
    for(i = 1; i <= total_items(&items); i++)
      fprintf(debug_fp, "%s %6d %6d %7.3f %7.3f\n", item_name(&items[i]), item_ql(&items[i]),
	     item_qh(&items[i]), item_price(&items[i]), item_shipping_price(&items[i]));
    close_file(&debug_fp, "/usr/people/ram/debug_log, "read_items");
  }
#endif */

  return;
}

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

int get_item_desc_price(char name[], int quantity, double *price, double *shipping_price,
			char description[], item items[])
{
  int i;
  
  for(i = 1; i <= total_items(&items); i++)
    if (strcmp(item_name(&items[i]), name) == 0)
      if ((quantity >= item_ql(&items[i])) && (quantity <= item_qh(&items[i])))
	{
	  *price = ((double) quantity) * item_price(&items[i]);
	  *shipping_price = ((double) quantity) * item_shipping_price(&items[i]);
	  strcpy(description, item_description(&items[i]));
	  return TRUE;
	}
  
  return FALSE;
}

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