#include <stdio.h>
#include <io.h>
#include <string.h>
#include <direct.h>
#include "common.h"

void getWorkDir(char *buf, int len)
{
  _getcwd(buf,len);
}

BOOL loseFile( char *buf)
{
  char *pos;
  // verify format and Get location of last '\'
  if (!(pos = strrchr(buf, '\\')) && (buf[1] != ':'))
    // Not a valid string, exit
    return(FALSE);

  // if has a '\' position after last
  // otherwise we position after the drive spec
  if (pos)
    *pos = '\0';
  else
    buf[2] = '\0';

  return(TRUE);
}

int SetDir(char *buf, BOOL has_file)
{
  char dbuf[DIR_BUFFER];
  int validDrive = DIR_OK;
  int drive = _getdrive();

  strcpy(dbuf, buf);
  // if it has a file strip it out
  if (has_file) {
    if (!loseFile(dbuf))
      // Don't know how to go to this directory
      return(DIR_BADFORMAT);
  }

  // We're not worried if invalid string
  if (buf[1] == ':') {
    // has a drive spec, change the drive
    if (_chdrive(buf[0] - '@'))
      validDrive = DRIVE_INVALID;
    buf+= 2;
  }

  if (validDrive == DIR_OK)
    // Drive set ok
    if (_chdir( dbuf) == -1) {
      // If dir set fails go back to old drive
      _chdrive(drive);
      validDrive = DIR_INVALID;
    }

  return(validDrive);
}
