/***********************************************
 * chdir.c
 *  - Changes Unix directory in DOSEMU
 ***********************************************/

#include <dos.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

typedef unsigned char uint8;
typedef unsigned int uint16;

#define DOS_HELPER_INT            0xE6
#define DOS_HELPER_DOSEMU_CHECK   0x00

void (far * dosemu_id_proc)(void) = (void (far *)(void))MK_FP(0xfc00, 0x0000);
int  (far * unix_chdir)(void)     = (int  (far *)(void))MK_FP(0xfc00, 0x0104);

/* returns non-zero major version number if DOSEMU is loaded */
uint16 CheckForDOSEMU(void)
{
    char far * id_string;

    _AH = 0xC0;
    geninterrupt(0x15);
    id_string = (char far *)MK_FP(_ES, _BX+10);
    if (_fstrncmp(id_string, "DOSEMU ", 7) == 0) {
       dosemu_id_proc();
       if (_AX == 0xaa55)
          return _BX;
    }

    _AH = 0x35;
    _AL = DOS_HELPER_INT;
    geninterrupt(0x21);
    if (_ES != 0 || _BX != 0) {
       _AL = DOS_HELPER_DOSEMU_CHECK;
       geninterrupt(DOS_HELPER_INT);
       if (_AX == 0xaa55)
          return _BX;
    }

    return (0);
}


int main(int argc, char **argv)
{
	uint16 version;

	version = CheckForDOSEMU();
	if (version == 0) {
	        printf("%s must be run under DOSEMU!\n");
		exit(2);
	}

	if(argc != 2) {
		printf("%s <newpath>\n", argv[0]);
		exit(1);
	}

	if (version >= 61) {
		_DX = (int)argv[1];
		_AX = _DS;
		_ES = _AX;
		return(unix_chdir());
	}
	else {
                _AX = _DS;
		_ES = _AX;
		_AX = 0x81;
		_DX = (int)argv[1];
		geninterrupt(0xe6);
		return(_AX);
	}
}

