/* cblaunch.c
 * Command line launcher for TOS < 2.0X
 * Based on various bits of code lifted from books/magazines etc
 * Roland Givan. Autumn 1994
 *
 */

#include <osbind.h>
#include <string.h>

#include "cblaunch.h"

#define TRUE -1
#define FALSE 0

typedef struct cmd_line_tag{
	char length;
	char data[125];
} CMD_LINE;

CMD_LINE cl;

GEM_SIZE    contrl[12],
	intin[128],
	ptsin[128],
	intout[128],
	ptsout[128];

GEM_SIZE    work_out[57],
	work_in[12];


GEM_SIZE handle;	/* handle of VDI workstation */
GEM_SIZE gl_hhbox,gl_hwbox,gl_hhchar,gl_hwchar;

int ap_id;	/* Application ID of this process */
int width,height;
OBJECT *dlog;

/* Function prototypes for this file */

void gem_setup(void);
void gem_close_down(void);
void bale_out(void);
void open_work(void);
int handle_dialog(OBJECT *dlog,int editnum);
void get_tedinfo(OBJECT *tree, int obj, char *dest);

void main()
{
	int len;

	gem_setup();
	cl.length=70;
	if (!cmdline_dialog(&(cl.data))){
		gem_close_down();
	}
	len = strlen(cl.data);
	if (len < 126){
		cl.length = len;
		if (Pexec(0,"CBZPLAY.PRG",(char *)(&cl),NULL) < 0){
			failed_dialog();
		}
		gem_close_down();
	}	
}

void gem_setup(void)
{
	ap_id = appl_init();
	handle = graf_handle(&gl_hwchar,&gl_hhchar,&gl_hwbox,&gl_hhbox);
	open_work();

	if(!rsrc_load("CBLAUNCH.RSC")){
		form_alert(1,"[3][Can't load resource file | CBLAUNCH.RSC ][ OK ]");
		bale_out();
	}
	rsrc_gaddr(R_TREE,FORM1,&dlog);
}


void gem_close_down(void)
{
	rsrc_free();
	bale_out();
}

void bale_out(void)
{
	v_clsvwk(handle);
	form_dial(FMD_START,0,0,0,0,0,0,width,height);
	form_dial(FMD_FINISH,0,0,0,0,0,0,width,height);
	appl_exit();
	exit(0);
}

void open_work(void)
{
	int i;

	for (i=0; i<10; work_in[i++]=1);
	work_in[10] = 2;
	v_opnvwk(work_in, &handle, work_out);
	width=work_out[0];
	height=work_out[1];
}


int handle_dialog(OBJECT *dlog,int editnum)
{
	GEM_SIZE x,y,w,h;
	int but;

	form_center(dlog,&x,&y,&w,&h);
	form_dial(FMD_START,0,0,0,0,x,y,w,h);
	objc_draw(dlog,0,10,x,y,w,h);
	but=form_do(dlog,editnum);
	form_dial(FMD_FINISH,0,0,0,0,x,y,w,h);
	dlog[but].ob_state&=~SELECTED;	/* de-select exit button */
	return(but);
}


/*
 * copy the string from a TEDINFO into another string
 */
void get_tedinfo(OBJECT *tree, int obj, char *dest)
{
	char *source;

	source=((TEDINFO *)tree[obj].ob_spec)->te_ptext;	/* extract address */
	strcpy(dest,source);
}

int cmdline_dialog(char *cmdline)
{
	char input[70];
	int but;
	but=handle_dialog(dlog,cmd_line);
	if (but==ok_field){
		get_tedinfo(dlog,cmd_line,input);
		strcpy(cmdline,&input[0]);
		return(TRUE);
	}else{
		return(FALSE);;
	}
}


void failed_dialog(void)
{
	form_alert(1,"[3][ Error on trying | to run CBZPLAY.PRG][ Quit ]");
}
