#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <dpmi.h>
#include <llp.h>

extern short _pspseg;
int _argc;
char **_argv_arr;

#pragma startup argset 15

static void get_progname(char *buf)
{
	char * pos;
	SELECTOR sel;
	DPMI_REGS regs;
	int len;

	__doscall(0x19,&regs);
	buf[0] = regs.b.al + 'A';
	buf[1] = ':';
	/* get path */

	/* find file name, assumes DOS 3... */
	asm push edi
	asm push es
	asm mov ecx,-1
	asm sub edi,edi
	asm mov es,[_pspseg]
	asm mov es,es:[0x2c]
	asm sub al,al
lp:
	asm repnz scasb
	asm cmp es:[edi],al
	asm jnz lp
	asm add edi,3
	asm movzx edx,byte ptr es:[edi+1]
  asm mov [pos],edi
  asm mov [sel],es
	asm mov ecx,-1
	asm repnz scasb
	asm not ecx
	asm mov [len],ecx
	asm pop es
	asm pop edi
	if (_EDX == ':')
		dpmi_copy_to_ds(buf,sel,(ULONG) pos,len);
	else
		dpmi_copy_to_ds(buf+2,sel,(ULONG) pos,len);
	

}
static void argset(void)
{
	char buf[200];
	char *bufp[100], *ocl, *_cmdline;
	int inquote = 0;
	ocl = _cmdline = malloc(128);
	dpmi_copy_to_ds(_cmdline,_pspseg,0x80,128);
  _cmdline[_cmdline[0]+1] = 0;
	_cmdline++;
	_argc = 1;
	while (*_cmdline) {
		while (isspace(*_cmdline)) _cmdline++;
		if (*_cmdline) {
			int i = 0;
			while ((inquote || !isspace(*_cmdline)) && *_cmdline)  {
				if (*_cmdline == '"') {
					inquote = !inquote ;
					_cmdline++ ;
					continue ;
				}
				buf[i++] = *_cmdline++;
			}
			buf[i++] = 0;
			bufp[_argc++] = strdup(buf) ;
		}
	}
	_argv_arr = calloc((_argc+1),sizeof(char *));
	memcpy(_argv_arr,bufp,_argc*sizeof(char *));
	_cmdline = ocl;
	get_progname(_cmdline);
	_argv_arr[0] = _cmdline;
}