/*  menucmdg.c   */
/*  Copyright 1989 Mountain Math Software  */
/*  All Rights Reserved                    */
#include <string.h>
#include "pack.h"
#include "gui.h"
#include "newaloc.h"
#include "cgidbg.h"
#include "menucmdg.h"
#include "tremfnc.h"
#include "remparm.h"
#include "shared.h"
#include "xdrv.h"
#include "dsp_app.h"
#include "remcom.h"

ExecuteCmdGui Master;

void CommandParameters::Execute()
{
	Master.Init(this);
	Master.Execute();
	if (wait) {
		DspApplication::set_waiting_on_dsp();
		Master.set_wait_remote_execute();
		while (DspApplication::is_busy()) {
			ReadSeg->ReadPacket();
			while (DspApplication::event_check()) ;
		}
/*
 *			while  (DspApplication::check_processing());
 *			for (int i = 0; i < 100;i++) while (ReadSeg->CheckPacketRead());
 *		}
 */
		DspApplication::clear_waiting_on_dsp();
		Master.clear_wait_remote_execute();
	}
}


void ExecuteCmdGui::ExecuteRemote()
{
	if (DspApplication::state()->IsBusy()) {
		// LogOut << "The DSP process is busy.\n" ;
		*Output + OutputHelp << "The DSP process is busy.\n" ;
		*Output << "You cannot execute a remote command until it completes.\n";
		return ;
	}
	// LogOut << "In Execute Remote\n" ;
	ParameterLimits& l = RemoteParamLimits[Params->ParameterType];
	PacketHeader Head(PacketRemoteCommand,-Params->RoutineIndex);
	PackAndSend Send(Head);

	PackDesc Desc(sizeof(Params->ParameterType),1);
	Send.AddItem(Desc,&(Params->ParameterType));

	Desc.NumBytes = sizeof(*(Params->IntParameters));
	Desc.NumItems = l.IntLimits ;
	Send.AddItem(Desc,Params->IntParameters);

	Desc.NumBytes = sizeof(*(Params->FloatParameters));
	Desc.NumItems = l.FloatLimits ;
	Send.AddItem(Desc,Params->FloatParameters);

	Desc.NumBytes = 0;
	Desc.NumItems = l.StringLimits ;
	Send.AddItem(Desc,Params->StringParameters);
 
	Desc.NumBytes = 0;
	Desc.NumItems = 1;
	for (int i = 0 ; i < l.StackLimits;i++) {
		int Index ;
/*
 *		LogOut << "Getting Stack entry " <<
 *			(Index = Params->StackParameters[i]) << "\n" ;
 *		LogOut << "This is `" << DspApplication::root_window()
			->menu_stack_name(Index) << "'\n" ;
 */
		const char * MenuName =
			DspApplication::root_window()->
			menu_stack_name(Params->StackParameters[i]);
		Send.AddItem(Desc,&MenuName);
	}
	DspState->MenuCommandSend();
	Send.PackageComplete();
}


void ExecuteCmdGui::Init(CommandParameters * params)
{
	Params = params ;
	TheCall = 0;
	if (!Params) return ;
	TheCall = AllActions[Params->RoutineIndex-1];
}


void ExecuteCmdGui::Execute()
{
	if (Params->RoutineIndex < 0) {
		ExecuteRemote();
		return ;
	}
	DoCall();
}

