#include <stdio.h>
#include <dir.h>
#include <dos.h>
#include <io.h>
#include <sys\stat.h>

/* cleanup wipes everything in the given directory including subdirectories */
/* It doesn't remove the directory itself                                   */
/* The cleanup procedure calls itself again for removing subdirectories     */

void cleanup(char *dir)
{
	char	fname[BUFSIZ];
	char	finame[BUFSIZ];
	static	int	level=0;

	struct  ffblk	fcblk;

	sprintf (fname,"%s\\*.*",dir);

	if (findfirst(fname,&fcblk,FA_DIREC|FA_HIDDEN|FA_SYSTEM|FA_RDONLY) == 0)
	{
		if (fcblk.ff_attrib == FA_DIREC)
		{
			if (strcmp(fcblk.ff_name,"."))
			{
				if (strcmp(fcblk.ff_name,".."))
				{
					sprintf (fname,"%s\\%s",dir,fcblk.ff_name);
					level++;
					cleanup(fname);
				}
			}
		}
		else
		{
			printf ("Removing %s\\%s\n",dir,fcblk.ff_name);
			sprintf (finame,"%s\\%s",dir,fcblk.ff_name);
			_chmod (finame,1,0);
			unlink (finame);
		}

		while (findnext(&fcblk) == 0)
		{
			if (fcblk.ff_attrib == FA_DIREC)
			{
				if (strcmp(fcblk.ff_name,"."))
				{
					if (strcmp(fcblk.ff_name,".."))
					{
						sprintf (fname,"%s\\%s",dir,fcblk.ff_name);
						level++;
						cleanup(fname);
					}
				}
			}
			else
			{
				printf ("Removing %s\\%s\n",dir,fcblk.ff_name);
				sprintf (finame,"%s\\%s",dir,fcblk.ff_name);
				_chmod (finame,1,0);
				unlink (finame);
			}
		}
	}

	if (level > 0)
	{
		printf ("Removing dir %s\n",dir);
		rmdir (dir);
	}

	level--;
}

