/* prtmenu.c */

/*
    NUT nutrition software 
    Copyright (C) 1996-2008 by Jim Jozwiak.

    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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "prtmenu.h"
#include "food.h"
#include "options.h"
#include "util.h"
#include "db.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void print_menus()
{
FILE *fp;
struct meal *meal_ptr = options.temp_meal_root;
int firstpage = 1, count, mealcount = 0;
char last_meal_date[9], last_meal = '0', newpage = 0x0c;
if (meal_ptr->next == NULL)
 {
 header("NUT:  Print Menus from Meal Database");
 spacer(0);
 printf("\nThere are no meals in database.  Press <enter> to continue..."); 
 firstpage = get_int();
 return;
 }
if ((fp = fopen("menus.txt","w")) == NULL)
 {
 printf("Can't open file \"menus.txt\" to write.\n");
 printf("Press <enter> to continue...");
 firstpage = get_int();
 return;
 }
strcpy(last_meal_date,"");
clear_work();
while (meal_ptr->next != NULL)
 {
 meal_ptr = meal_ptr->next;
 if (strcmp(last_meal_date,meal_ptr->meal_date) != 0 || last_meal != meal_ptr->meal)
  {
  strcpy(last_meal_date,meal_ptr->meal_date);
  last_meal = meal_ptr->meal;
  mealcount++;
  if (mealcount > options.defanal && options.defanal != 0) break;
  if (firstpage == 1)
   {
   firstpage = 0;
   fprintf(fp,"Meal Date:  %s                                           Meal Number:  %d\n\n",last_meal_date,last_meal);
   } 
  else
   {
   fprintf(fp,"\n");
   food_display(fp);
   if (mealcount % 2) fprintf(fp,"%c",newpage);
   else fprintf(fp,"________________________________________________________________________________\n\n");
   fprintf(fp,"Meal Date:  %s                                           Meal Number:  %d\n\n",last_meal_date,last_meal);
   clear_work();
   }
  }
 fprintf(fp,"%4.0f gm or %4.1f oz %-60s\n",meal_ptr->grams,meal_ptr->grams / GRAMS_IN_OUNCE,FoodIndex[meal_ptr->food_no]->name);
 for (count = 0; count < NUTRIENT_COUNT; count++) food_work.nutrient[count] += (FoodIndex[meal_ptr->food_no]->nutrient[count] * meal_ptr->grams / 100);
 }
fprintf(fp,"\n");
food_display(fp);
clear_work();
fclose(fp);
header("NUT:  Print Menus from Meal Database");
spacer(0);
printf("\nMenus printed to \"menus.txt\".  Press <enter> to continue..."); 
firstpage = get_int();
return;
}
