# MENU library

integer MENU_RESPONSE
integer MENU_IN_LOOP

integer	     MENU_COUNT			0
string_array MENU_OPTIONS		10


integer MENU_MODAL				
# CAN BE SET TO TRUE OR FALSE

integer  MENU_MODE 				MENU_PROXY
# CAN BE SET TO ONE OF:
constant MENU_PROXY				0
constant MENU_EXECUTE			1

# SET TO TRUE TO DISPLAY THE COMMAND WHILE IN PROXY MODE
integer MENU_DISPLAY_COMMAND	true
	
grammar $integer >menu_number

{+menu_number
# THIS FUNCTION IS CALLED WHEN THE PLAYER TYPES AN IN-GAME COMMAND THAT 
# CONTAINS ONLY AN INTEGER
if MENU_COUNT = 0
   write "There is no menu currently active.^"
   set time = false
   return
endif
if $integer < 1 : $integer > MENU_COUNT
   if MENU_COUNT = 1
      write "The only available choice is 1.^"
      return
   else
      write "Please choose a number between 1 and " MENU_COUNT .^
      return
   endif
endif
if MENU_MODE = MENU_EXECUTE
   execute MENU_OPTIONS[$integer]
else
   if MENU_DISPLAY_COMMAND = true
      write "] "
      style input
      write MENU_OPTIONS[$integer] ^
      style normal
   endif
   proxy MENU_OPTIONS[$integer]
endif
execute +menu_clear_options
}

{+menu_clear_options
# THE FUNCTION CLEARS ALL THE CURRENT OPTIONS FROM THE MENU
set MENU_COUNT = 0
}

{+menu_add_option
# THIS FUNCTION ADDS A NEW OPTION TO THE MENU
# IT ACCEPTS: <Text to print<Response to selection
if MENU_COUNT = 10
   # NO MORE ROOM
   return false
endif
set MENU_COUNT + 1
write MENU_COUNT ". " string_arg[0] ^
setstring MENU_OPTIONS[MENU_COUNT] string_arg[1]
}

{+menu_prompt
# THIS FUNCTION CALLS THE PASSED FUNCTION TO POPULATE THE MENU
# THEN PROMPTS FOR A CHOICE
# IF MENU_MODAL IS SET TO TRUE, THE MENU WILL CONTINUOUSLY LOOP
# ASKING THE PLAYER FOR THEIR NEXT SELECTION UNTIL THE LOOP
# IS TERMINATED BY SETTING MENU_IN_LOOP TO FALSE
if @arg = 0
   write "You must supply a call-back function to +menu_prompt.^"
   return
endif
if @arg = 1
   set MENU_IN_LOOP = true
else
   set MENU_IN_LOOP = arg[1]
endif

repeat
   execute "+menu_clear_options"
   write ^
   execute string_arg[0]
   asknumber MENU_RESPONSE 1 MENU_COUNT
   if MENU_MODAL = false
      if MENU_RESPONSE = -1 : MENU_RESPONSE = 0
         execute +menu_clear_options
         return
      endif
   endif
   if MENU_RESPONSE < 1 : MENU_RESPONSE > MENU_COUNT
      write "Please choose a number between 1 and " MENU_COUNT .^
   else
      if MENU_MODE = MENU_EXECUTE
         execute MENU_OPTIONS[MENU_RESPONSE]
      else
         if MENU_DISPLAY_COMMAND = true
            write "] "
            style input
            write MENU_OPTIONS[MENU_RESPONSE] ^
            style normal
         endif
         proxy MENU_OPTIONS[MENU_RESPONSE]
      endif
   endif
until MENU_IN_LOOP = false
}