/*
 * cleandsk.c
 * clean the erased data area of a disk - Philip J. Erdelsky
 */

#define BUFFER_SIZE 16*1024
 
#include <stdio.h>
#include <dos.h>
#include <io.h>
 
static void error_exit(char *s) { fputs(s, stderr); exit(1); }
 
void main(unsigned argc, char **argv)
{
    static char FILESPEC[] = "X:\\CLEANDSK.$$$";
    char *filespec;
    unsigned long free_bytes;
    int drive, handle;
    static char buffer[BUFFER_SIZE];
    struct dfree d;

    if (argc < 2)
    {
        drive = 0;
        filespec = FILESPEC+2;
    }
    else
    {
        FILESPEC[0] = argv[1][0] & 0xDF;
        drive = FILESPEC[0] - ('A'-1);
        filespec = FILESPEC;
    }

    printf("Writing %s\n", filespec);
    handle = _creat(filespec, 0);
    if (handle < 0)
        error_exit("File creation error\n");

    getdfree(drive, &d);
    if (d.df_sclus == 0xFFFF)
        error_exit("Disk error\n");
    free_bytes =
        (unsigned long )(d.df_bsec * d.df_sclus) * d.df_avail;
    printf("%ld free bytes to be cleaned\n", free_bytes);

    while (free_bytes > 0)
    {
        unsigned size =
            free_bytes < BUFFER_SIZE ? free_bytes : BUFFER_SIZE;

        if (_write(handle, buffer, size) < size)
            error_exit("\nFile write error\n");
        free_bytes -= size;
        printf("%11ld\r", free_bytes);
    }

    if (_close(handle))
        error_exit("\nFile write error\n");

    unlink(filespec);
    puts("\rDone       ");
    exit(0);
}
