#include <iostream.h>
#include "client.h"
#include "daemon.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

/* CAREFUL!!! must use forward slash '/' for path seperator.
 * ALSO have to check CARRY flag for errors etc
 */
int main(int argc, char **argv) {
  if (server_init() < 0) {
    exit(-1);
  }

  DOS_CMD = DAEMON_GETBUF;
  call_dosemu();
  uint16 dosbuf = DOS_BX;
  int size = 4096; //DOS_CX;
  cerr << "dosbuf = " << (void *)dosbuf << endl;
  cerr << "sizeof dosbuf = " << size << endl;
  char filebuf[65536];
  
  uint16 handle;
  daemon_comms * dcom = &(server->daemon_comm);
  bzero (dcom->buf, sizeof (dcom->buf));
  
  cerr << "DS = " << (void *)DOS_DS << endl;
  cerr << "dcom->seg = " << (void *)dcom->seg << endl;
  cerr << "dcom->off = " << (void *)dcom->off << endl;
  /* open the file */
  HI(ax) = 0x3d;
  LO(ax) = 00;
  DOS_DX = dcom->off + (offsetof (daemon_comms, buf));
  if (argc == 2)
    sprintf (dcom->buf, "%s%c", argv[1], (char)0);
  else
    sprintf (dcom->buf, "c:/autoexec.bat%c", (char)0);
//  LWORD(eflags) &= ~(1 << 0);
  Daemon_int86 (0x21);

#if 1
  if ((LWORD(eflags) & (1 << 0)) == 0x1) {
    cerr << "Carry flag SET!!!" << endl;
    cerr << "open failed: AX = " << DOS_AX << endl;
    server_exit();
    return -1;
  }
#endif
  handle = DOS_AX;
  cerr << "handle = " << handle << endl;
  
  /* now start the read */
  cerr << "reading data from file" << endl;
  int total = 0;
  do {
    
    HI(ax) = 0x3f;
    LO(ax) = 0;
    DOS_BX = handle;
    DOS_CX = size;
//    DOS_DX = dcom->off + (offsetof (daemon_comms, buf));
    DOS_DX = dosbuf; // the buffer allocated above

    Daemon_int86 (0x21);
//    cerr << "AX = " << DOS_AX << endl;
    if (DOS_AX > 0) {
#if 0
      cout.write(dcom->buf, DOS_AX);
#else
      total = DOS_AX;
//      total += DOS_AX;
//      if (total > size) { // only write out every 32k
	Daemon_getmem (filebuf, dcom->seg, dosbuf, total);
	cout.write (filebuf, total);
  //    }
#endif
    }
  } while (DOS_AX == DOS_CX);
  cout << endl;
  /* close the file */
  cerr << "closing file" << endl;
  HI(ax) = 0x3e;
  DOS_BX = handle;
  Daemon_int86 (0x21);
  
  
#if 0  // free up the memory allocated
  DOS_CMD = DAEMON_FREE;
  DOS_ARG = dosbuf;
#endif
  call_dosemu();
  
  server_exit();
}
  
  
