/* 
   Copyright 1994-2003 Free Software Foundation, Inc.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 
   USA

   You may contact the author at:

   mailto::camille@bluegrass.net

   or by snail mail at:

   David Lindauer
   850 Washburn Ave Apt 99
   Louisville, KY 40222
*/
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <dpmi.h>
#include "llp.h"

extern short _pspseg, _envseg;
int _RTL_DATA _argc, _RTL_DATA __argc;
char _RTL_DATA **_argv, _RTL_DATA **__argv;

#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,[_envseg]
	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 == '"' && (_cmdline == ocl+1 || *(_cmdline-1) != '\\')) {
					inquote = !inquote ;
					_cmdline++ ;
					continue ;
				}
				buf[i++] = *_cmdline++;
			}
			buf[i++] = 0;
			bufp[_argc++] = strdup(buf) ;
		}
	}
   _argv = calloc((_argc+1),sizeof(char *));
   memcpy(_argv,bufp,_argc*sizeof(char *));
	_cmdline = ocl;
	get_progname(_cmdline);
   _argv[0] = _cmdline;
   __argv = _argv ;
   __argc = _argc ;
}