// Some DJGPP-specific helpers for CVS
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <crt0.h>

#include <system.h>

void
djgpp_cvs_init(int* pargc, char*** pargv)
{
  // Set program name
  { char PathBuffer[1024]; char* s = PathBuffer;
    _truename((*pargv)[0], PathBuffer);
    while(*s) { if(*s == '\\') *s = '/'; ++s; }
    if(!_USE_LFN) strlwr(PathBuffer);
    s = strrchr(PathBuffer, '.');
    if(s != 0 && stricmp(s, ".exe") == 0) *s = 0;
    free((*pargv)[0]); (*pargv)[0] = strdup(PathBuffer);
  }
  // Needed so cvs correctly recognizes files (and CVS dirs in particular)
  // Doesn't actually seem to work. CVS probably uses functions that don't
  //  care about this flag.
  // Using _CRT0_FLAG_PRESERVE_FILENAME_CASE is probably undesirable too, as
  //  it causes all-uppercase filenames on MSDOS, which is ugly and probably
  //  breaks more than it fixes.
  __opendir_flags = __OPENDIR_PRESERVE_CASE;
}

char
foldchar(char c)
{
  if(c == '\\') return '/';
  return tolower(c);
}

void
fnfold (char *filename)
{
  if(filename == 0) return;
  while(*filename) { *filename = foldchar(*filename); ++filename; }
}

int
fncmp(const char* a, const char* b)
{
int cdif = 0;
  if(a == 0 || b == 0) return -1;
  while((cdif = (foldchar(*b) - foldchar(*a))) == 0 && *a && *b) ++a, ++b;
  return cdif;
}
