/* DOS wrapper to simulate un*x opendir/readdir/closedir.
   *Hobbit*, 9409.  Idea mine; examples lifted from msc's "extdir.c". _H*/

#include "dosdir.h"

char dot[] = ".";
char dotdot[] = "..";

DIR * opendir (name)
char * name;
{
DIR * fakedir;
char matchname [128];
int x;

  fakedir = (DIR *) malloc (sizeof (DIR));	/* sigh... */
  strcpy (matchname, name);
  x = strlen (matchname) - 1;
  if ((matchname[x] == ':') ||		/* try and be vaguely */
      (matchname[x] == '\\') ||		/* intelligent about what */
      (matchname[x] == '/'))		/* we were handed... */
	strcat (matchname, "*.*");
  else
	strcat (matchname, "/*.*");
  
  if ( ! _dos_findfirst (matchname, 0xffff, &fakedir->find)) {
    fakedir->context = 0;
    fakedir->fent.d_name = (char *) 0;	/* clear this for now */
    return (fakedir);
  } else {
    return 0;
  } /* findfirst */
} /* opendir */

/* And now, pointer hell! */
struct dirent *
readdir (foo)
DIR * foo;
{
/* We have to play a context game here, since you don't get . and .. if
   you're reading the root dir.  Fake them out if they don't appear. */

  if (foo->context == 3) {	/* normal */
    if ( ! _dos_findnext (&foo->find)) {
      foo->fent.d_name = foo->find.name;
      return (&foo->fent);
    } else {
      return (DIR *) 0;
    } /* findnext */
  } /* ctx = 3 */

  if (foo->context == 0) {	/* which it will be on first readdir */
    if ((strcmp (foo->find.name, dot)) == 0) {
      foo->context = 3;		/* switch straight to normal mode */
      foo->fent.d_name = foo->find.name;
    } else {  /* dot? */
      foo->context = 1;
      foo->fent.d_name = dot;		/* first fakeout */
    } /* strcmp dot */
    return (&foo->fent);
  } /* ctx = 0 */

  if (foo->context == 1) {		/* second fakeout */
    foo->context = 2;
    foo->fent.d_name = dotdot;
    return (&foo->fent);
  } /* ctx = 1 */

  if (foo->context == 2) {		/* first real name */
    foo->context = 3;
    foo->fent.d_name = foo->find.name;
    return (&foo->fent);
  } /* ctx = 2 */

/* something must have gone horribly wrong if context is something random! */
  return (DIR *) 0;

} /* readdir */

closedir ()
{}
