/*
    ####             #    #     # #
    #   #            #    #       #          The FreeWare C library for 
    #   #  ##   ###  #  # #     # ###             RISC OS machines
    #   # #  # #     # #  #     # #  #   ___________________________________
    #   # ####  ###  ##   #     # #  #                                      
    #   # #        # # #  #     # #  #    Please refer to the accompanying
    ####   ### ####  #  # ##### # ###    documentation for conditions of use
    ________________________________________________________________________

    File:    Menu.Extend.c
    Author:  Copyright  1993 Shaun Blackmore and Jason Williams
    Version: 1.00 (30 Apr 1993)
    Purpose: Extends a menu by adding entries to the bottom of it
*/

#include <stdlib.h>

#include "Desk.Error.h"
#include "Desk.Screen.h"
#include "Desk.Wimp.h"
#include "Desk.Menu.h"
#include "Desk.DeskMem.h"

#include "MenuDefs.h"




extern Desk_menu_ptr Desk_Menu_Extend(Desk_menu_ptr menu, const char *description)
{
  Desk_menu_ptr  newmenu;
  int       maxwidth = 0, newitems = 0, lastitem = 0;
  Desk_menu_item *item = (Desk_menu_item *) ((int) menu + sizeof(Desk_menu_block));

  Desk_Menu__CountItems(description, &newitems, &maxwidth);

  maxwidth *= 8 * Desk_screen_delta.x;
  if (menu->width < maxwidth)
    menu->width = maxwidth;

  while (!item[lastitem].menuflags.data.last)         /* Find the last item */
    lastitem++;

  newmenu = Desk_DeskMem_XRealloc((void *) menu, sizeof(Desk_menu_block) +
                             (sizeof(Desk_menu_item) * (lastitem + 1 + newitems)));
  if (newmenu == NULL)
    return((Desk_menu_ptr) Desk_Error_OutOfMemory(Desk_bool_FALSE, "menus"));

  item = (Desk_menu_item *) ((int) newmenu + sizeof(Desk_menu_block));
  item[lastitem].menuflags.data.last = Desk_bool_FALSE;

  if (!Desk_Menu__Create(&item[lastitem + 1], description, newitems))
    return(menu);

  item[lastitem + newitems].menuflags.data.last = Desk_bool_TRUE;

  return(newmenu);
}
