#include <dos.h>
#include <dpmi.h>
#include <string.h>

static unsigned getdta(void)
{
	DPMI_REGS regs;
	regs.h.ax = 0x2f;
	regs.h.flags =0x72;
	regs.h.ss = 0;
	regs.h.sp = 0;
	dpmi_simulate_real_interrupt(0x21,&regs);
	return (regs.h.es << 16) + regs.h.bx;

}
static void setdta(unsigned dta)
{
	DPMI_REGS regs;
	regs.h.ax = 0x1a;
	regs.h.flags =0x72;
	regs.h.ss = 0;
	regs.h.sp = 0;
	regs.h.ds = dta >> 16;
	regs.h.dx = dta & 0xffff;
	dpmi_simulate_real_interrupt(0x21,&regs);
}
int _dos_getdrive(void)
{
	DPMI_REGS regs;
	regs.h.ax = 0x19;
	regs.h.flags =0x72;
	regs.h.ss = 0;
	regs.h.sp = 0;
	dpmi_simulate_real_interrupt(0x21,&regs);

	return regs.h.ax & 0xff;
}
int _dos_getpwd(char *buf, int drive)
{
	DPMI_REGS regs;
	SELECTOR sel,para;
	if (!dpmi_alloc_real_memory(&sel,&para,0x3))
		return 8;
	regs.h.ax = 0x47;
	regs.h.flags =0x72;
	regs.h.ss = 0;
	regs.h.sp = 0;
	regs.h.ds = para;
	regs.h.dx = drive;
	regs.h.si = 0;
	dpmi_simulate_real_interrupt(0x21,&regs);
	dpmi_copy_to_ds(buf,sel,0,65);
	dpmi_dealloc_real_memory(sel);
	return strlen(buf);
}
int _dos_findfirst(char *string, int attr, struct find_t *buf)
{
	DPMI_REGS regs;
	SELECTOR sel,para;
	SELECTOR nsel,npara;
	long dta = getdta();
	if (!dpmi_alloc_real_memory(&sel,&para,0x3))
		return 8;
	if (!dpmi_alloc_real_memory(&nsel,&npara,0x8)) {
		dpmi_dealloc_real_memory(sel);
		return 8;
	}
	setdta((long)para << 16);
	dpmi_copy_from_ds(nsel,0,string,strlen(string));
	regs.h.ax = 0x4f;
	regs.h.flags =0x72;
	regs.h.ss = 0;
	regs.h.sp = 0;
	regs.h.ds = npara;
	regs.h.dx = 0;
	regs.h.cx = attr;
	dpmi_simulate_real_interrupt(0x21,&regs);
	dpmi_copy_to_ds(buf,sel,0,48);
	dpmi_dealloc_real_memory(sel);
	dpmi_dealloc_real_memory(nsel);
	setdta(dta);
	if (regs.h.flags & 1)
		return regs.b.al;
	else
		return 0;
}
int _dos_findnext(struct find_t *buf)
{
	DPMI_REGS regs;
	SELECTOR sel,para;
	long dta = getdta();
	if (!dpmi_alloc_real_memory(&sel,&para,0x3))
		return 8;
	setdta((long)para << 16);
	dpmi_copy_from_ds(sel,0,buf,48);
	regs.h.ax = 0x4f;
	regs.h.flags =0x72;
	regs.h.ss = 0;
	regs.h.sp = 0;
	dpmi_simulate_real_interrupt(0x21,&regs);
	dpmi_copy_to_ds(buf,sel,0,48);
	dpmi_dealloc_real_memory(sel);
	setdta(dta);
	if (regs.h.flags & 1)
		return regs.b.al;
	else
		return 0;
}
main()
{
	char buf[80];
	struct find_t r;
	printf("%d\n",_dos_getdrive());
	dos_getpwd(buf,0);
	printf("%s\n",buf);
	if (!_dos_findfirst("*.obj",0,&r) {
		do 
			printf("%s\n",r->name);
		while (!dos_findnext(&r));
	}
	
}	