/* ---------------------------------------------------------------------------
 * FAT_public.c                                                (C)ChaN, 2008
 * ---------------------------------------------------------------------------
 * Micro-key bv
 * Industrieweg 28, 9804 TG Noordhorn
 * Postbus 92, 9800 AB Zuidhorn
 * The Netherlands
 * Tel: +31 594 503020
 * Fax: +31 594 505825
 * Email: support@microkey.nl  
 * Web: www.microkey.nl
 * ---------------------------------------------------------------------------
 * 
 * 
 * Description: FatFs - FAT file system module  R0.06        
 * 
 * The FatFs module is an experimenal project to implement FAT file system to
 * cheap microcontrollers. This is a free software and is opened for education,
 * research and development under license policy of following trems.
 * 
 *  Copyright (C) 2008, ChaN, all right reserved.
 * 
 * The FatFs module is a free software and there is no warranty.
 * You can use, modify and/or redistribute it for personal, non-profit or
 * commercial use without restriction under your responsibility.
 * Redistributions of source code must retain the above copyright notice.             
 * ---------------------------------------------------------------------------
 * Last Change:     0.2, Aug 11, 2008, MMi
 *                  Edited to fit into LAN_2636 Project
 *
 *----------------------------------------------------------------------------
 * Feb 26,'06 R0.00  Prototype.
 *
 * Apr 29,'06 R0.01  First stable version.
 *
 * Jun 01,'06 R0.02  Added FAT12 support.
 *                   Removed unbuffered mode.
 *                   Fixed a problem on small (<32M) patition.
 * Jun 10,'06 R0.02a Added a configuration option (_FS_MINIMUM).
 *
 * Sep 22,'06 R0.03  Added f_rename().
 *                   Changed option _FS_MINIMUM to _FS_MINIMIZE.
 * Dec 11,'06 R0.03a Improved cluster scan algolithm to write files fast.
 *                   Fixed f_mkdir() creates incorrect directory on FAT32.
 *
 * Feb 04,'07 R0.04  Supported multiple drive system.
 *                   Changed some interfaces for multiple drive system.
 *                   Changed f_mountdrv() to f_mount().
 *                   Added f_mkfs().
 * Apr 01,'07 R0.04a Supported multiple partitions on a plysical drive.
 *                   Added a capability of extending file size to f_lseek().
 *                   Added minimization level 3.
 *                   Fixed an endian sensitive code in f_mkfs().
 * May 05,'07 R0.04b Added a configuration option _USE_NTFLAG.
 *                   Added FSInfo support.
 *                   Fixed DBCS name can result FR_INVALID_NAME.
 *                   Fixed short seek (<= csize) collapses the file object.
 *
 * Aug 25,'07 R0.05  Changed arguments of f_read(), f_write() and f_mkfs().
 *                   Fixed f_mkfs() on FAT32 creates incorrect FSInfo.
 *                   Fixed f_mkdir() on FAT32 creates incorrect directory.
 * Feb 03,'08 R0.05a Added f_truncate() and f_utime().
 *                   Fixed off by one error at FAT sub-type determination.
 *                   Fixed btr in f_read() can be mistruncated.
 *                   Fixed cached sector is not flushed when create and close
 *                   without write.
 *
 * Apr 01,'08 R0.06  Added fputc(), fputs(), fprintf() and fgets().
 *                   Improved performance of f_lseek() on moving to the same
 *                   or following cluster.
 *---------------------------------------------------------------------------
 */


/* ---------------------------------------------------------------------------
 * System include files
 * ---------------------------------------------------------------------------
 */
/* Compiler includes */
#include <string.h>

#include "LPC23xx.h"
#include "types.h"

/* FreeRTOS includes */
#include "FreeRTOS.h"
#include "task.h"
/* ---------------------------------------------------------------------------
 * Application include files
 * ---------------------------------------------------------------------------
 */
#include "fat_intern.h" /* FatFs declarations                               */
#include "fat_public.h"
#include "fat_diskio.h"     /* Include file for user provided disk functions    */
#include "fat_time.h"   /* Get time from RTC                                */

#include "dio.h"
#include "SerOut.h"

/* ---------------------------------------------------------------------------
 * Local constant and macro definitions
 * ---------------------------------------------------------------------------
 */

/* ---------------------------------------------------------------------------
 * Global variable definitions
 * ---------------------------------------------------------------------------
 */
extern FATFS *FatFs[_DRIVES];           /* Pointer to file system objects   */
                                        /* (logical drives)                 */
extern UINT16 fsid;                     /* File system mount ID             */
/* ---------------------------------------------------------------------------
 * Local variable definitions
 * ---------------------------------------------------------------------------
 */


/* ---------------------------------------------------------------------------
 * Local function definitions
 * ---------------------------------------------------------------------------
 */

void FAT_StatusOut (FRESULT result)
{
    switch (result)
        {
        case FR_OK: 
            debugPrint ("\n\rOperation suceeded");
            break;
        case FR_NOT_READY:
            debugPrint ("\n\rNot ready");
            break;
        case FR_NO_FILE:
            debugPrint ("\n\rNo file");
            break;
        case FR_NO_PATH:
            debugPrint ("\n\rNo path");
            break;
        case FR_INVALID_NAME:
            debugPrint ("\n\rInvalid name");
            break;
        case FR_INVALID_DRIVE:
            debugPrint ("\n\rInvalid drive");
            break;
        case FR_DENIED:
            debugPrint ("\n\rOperation denied");
            break;
        case FR_EXIST:
            debugPrint ("\n\rAlready exists");
            break;
        case FR_RW_ERROR:
            debugPrint ("\n\rOperation error");
            break;
        case FR_WRITE_PROTECTED:
            debugPrint ("\n\rWrite-protected");
            break;
        case FR_NOT_ENABLED:
            debugPrint ("\n\rNot enabled");
            break;
        case FR_NO_FILESYSTEM:
            debugPrint ("\n\rNo filesystem");
            break;
        case FR_INVALID_OBJECT:
            debugPrint ("\n\rInvalid object");
            break;
        case FR_MKFS_ABORTED:
            debugPrint ("\n\rOperation aborted");
            break;
        }
}


FRESULT f_mount(UINT8 drive, FATFS *fs)
{
    
    if (drive >= _DRIVES)
        {
        return FR_INVALID_DRIVE;
        }
    
    if (FatFs[drive])
        {
        FatFs[drive]->fs_type = 0;      /* Clear old object                 */
        }
    FatFs[drive] = fs;                  /* Register and clear new object    */
    
    if (fs)
        {
        fs->fs_type = 0;
        }
    return FR_OK;
}


FRESULT f_open (FIL *fp, const char *path, UINT8 mode)
{
    char fn[8+3+1];
    UINT32 ps;
    UINT32 rs;
    UINT8 *dir;
    FRESULT res;
    DIR dj;

    fp->fs = NULL;                      /* Clear file object                */
#if !_FS_READONLY
    mode &= (FA_READ|FA_WRITE|FA_CREATE_ALWAYS|FA_OPEN_ALWAYS|FA_CREATE_NEW);
    res = auto_mount(&path, &dj.fs, (UINT8)(mode & (FA_WRITE|FA_CREATE_ALWAYS
            |FA_OPEN_ALWAYS|FA_CREATE_NEW)));
#else
    mode &= FA_READ;
    res = auto_mount(&path, &dj.fs, 0);
#endif
    if (res != FR_OK)
        {
        return res;
        }
    res = trace_path(&dj, fn, path, &dir);  /* Trace the file path          */

#if !_FS_READONLY
    /* Create or Open a file                                                */
    if (mode & (FA_CREATE_ALWAYS|FA_OPEN_ALWAYS|FA_CREATE_NEW))
        {
        if (res != FR_OK)
            { 
            /* No file, create new                                          */
            if (res != FR_NO_FILE)
                {
                return res;
                }
            res = reserve_direntry(&dj, &dir);
            if (res != FR_OK)
                {
                return res;
                }
            memset(dir, 0, 32);         /* Initialize new entry with name   */
            memcpy(&dir[DIR_Name], fn, 8+3);
            dir[DIR_NTres] = fn[11];
            mode |= FA_CREATE_ALWAYS;
            } 
        else
            { 
            /* Any object is already existing                               */
            if (mode & FA_CREATE_NEW)   /* Cannot create new                */
                {
                return FR_EXIST;
                }
            /* Cannot overwrite it (R/O or DIR)                             */
            if (!dir || (dir[DIR_Attr] & (AR_RDO|AR_DIR)))
                {
                return FR_DENIED;
                }
            if (mode & FA_CREATE_ALWAYS)
                { 
                /* Resize it to zero if needed                              */
                rs = ((UINT32)LD_WORD(&dir[DIR_FstClusHI]) << 16)
                        | LD_WORD(&dir[DIR_FstClusLO]); /* Get start cluster*/
                ST_WORD(&dir[DIR_FstClusHI], 0); /* cluster = 0             */
                ST_WORD(&dir[DIR_FstClusLO], 0);
                ST_DWORD(&dir[DIR_FileSize], 0); /* size = 0                */
                dj.fs->winflag = 1;
                ps = dj.fs->winsect;    /* Remove the cluster chain         */
                if (!remove_chain(dj.fs, rs) || !move_window(dj.fs, ps))
                    {
                    return FR_RW_ERROR;
                    }
                dj.fs->last_clust = rs - 1; /* Reuse the cluster hole       */
                }
            }
        if (mode & FA_CREATE_ALWAYS)
            {
            dir[DIR_Attr] = 0;          /* Reset attribute                  */
            ps = get_fattime();
            ST_DWORD(&dir[DIR_CrtTime], ps); /* Created time                */
            dj.fs->winflag = 1;
            mode |= FA__WRITTEN;        /* Set file changed flag            */
            }
        }
    /* Open an existing file */
    else
        {
#endif /* !_FS_READONLY */
        if (res != FR_OK)
            {
            return res;                 /* Trace failed                     */
            }
        if (!dir || (dir[DIR_Attr] & AR_DIR)) /* It is a directory          */
            {
            return FR_NO_FILE;
            }
#if !_FS_READONLY
        if ((mode & FA_WRITE) && (dir[DIR_Attr] & AR_RDO)) /* R/O violation */
            {
            return FR_DENIED;
            }
        }
    fp->dir_sect = dj.fs->winsect;      /* Pointer to the directory entry   */
    fp->dir_ptr = dir;
#endif
    fp->flag = mode;                    /* File access mode                 */
    fp->org_clust =                     /* File start cluster               */
    ((UINT32)LD_WORD(&dir[DIR_FstClusHI]) << 16) | LD_WORD(&dir[DIR_FstClusLO]);
    fp->fsize = LD_DWORD(&dir[DIR_FileSize]); /* File size                  */
    fp->fptr = 0;
    fp->csect = 255;                    /* File pointer                     */
    fp->curr_sect = 0;
    fp->fs = dj.fs;
    fp->id = dj.fs->id;                 /* Owner file system object of file */

    return FR_OK;
}


FRESULT f_read(FIL *fp, void *buff, UINT32 btr, UINT32 *br)
{
    UINT32 clust;
    UINT32 sect;
    UINT32 remain;
    UINT32 rcnt;
    UINT32 cc;
    UINT8 *rbuff = buff;
    FRESULT res;

    *br = 0;
    res = validate(fp->fs, fp->id);     /* Check validity of the object     */
    if (res != FR_OK)
        {
        return res;
        }
    if (fp->flag & FA__ERROR)
        {
        return FR_RW_ERROR;             /* Check error flag                 */
        }
    if (!(fp->flag & FA_READ))
        {
        return FR_DENIED;               /* Check access mode                */
        }
    remain = fp->fsize - fp->fptr;
    if (btr > remain)
        {
        btr = (UINT32)remain;           /* Truncate btr by remaining bytes  */
        }
    
    /* Repeat until all data transferred */    
    for (; btr; rbuff += rcnt, fp->fptr += rcnt, *br += rcnt, btr -= rcnt)
        {
        if ((fp->fptr % SS(fp->fs)) == 0)
            { 
            /* On the sector boundary?                                      */
            if (fp->csect >= fp->fs->csize)
                { 
                /* On the cluster boundary?                                 */
                
                /* On the top of the file? */
                clust = (fp->fptr == 0) ? 
                fp->org_clust : get_cluster(fp->fs, fp->curr_clust);
                if (clust < 2 || clust >= fp->fs->max_clust)
                    {
                    goto fr_error;      /* GOTO LABEL AT END OF FUNCTION    */
                    }
                fp->curr_clust = clust; /* Update current cluster           */
                fp->csect = 0;          /* Reset sector address in cluster  */
                }
            
            /* Get current sector */
            sect = clust2sect(fp->fs, fp->curr_clust) + fp->csect; 
            cc = btr / SS(fp->fs);      /* remaining bytes >= sector size   */
            if (cc)
                { 
                /* Read maximum contiguous sectors directly                 */
                
                /* Clip at cluster boundary */
                if (fp->csect + cc > fp->fs->csize)
                    {
                    cc = fp->fs->csize - fp->csect;
                    }
                if (disk_read(fp->fs->drive, rbuff, sect, (UINT8)cc) != RES_OK)
                    {
                    goto fr_error;
                    }
                fp->csect += (UINT8)cc; /* Next sector address in cluster   */
                rcnt = SS(fp->fs) * cc; /* Number of bytes transferred      */
                continue;
                }
            if (sect != fp->curr_sect)
                { 
                /* Is window offset changed?                                */
#if !_FS_READONLY
                if (fp->flag & FA__DIRTY)
                    { 
                    /* Write back file I/O buffer if needed                 */
                    if (disk_write(fp->fs->drive, fp->buffer, fp->curr_sect, 1)
                            != RES_OK)
                        {
                        goto fr_error;  /* GOTO LABEL AT END OF FUNCTION    */
                        }
                    fp->flag &= (UINT8)~FA__DIRTY;
                    }
#endif
                /* Fill file I/O buffer with file data */
                if (disk_read(fp->fs->drive, fp->buffer, sect, 1) != RES_OK) 
                    {
                    goto fr_error;      /* GOTO LABEL AT END OF FUNCTION    */
                    }
                fp->curr_sect = sect;
                }
            fp->csect++;                /* Next sector address in cluster   */
            }
        
        /* Get partial sector from file I/O buffer */
        rcnt = SS(fp->fs) - (fp->fptr % SS(fp->fs)); 
        if (rcnt > btr)
            {
            rcnt = btr;
            }
        memcpy(rbuff, &fp->buffer[fp->fptr % SS(fp->fs)], rcnt);
        }

    return FR_OK;

    /* GOTO LABEL                                                           */
    /* Abort this file due to an unrecoverable error                        */
    fr_error:
    fp->flag |= FA__ERROR;
    return FR_RW_ERROR;
}


#if !_FS_READONLY
FRESULT f_write (FIL *fp, const void *buff, UINT32 btw, UINT32 *bw)
{
    UINT32 clust;
    UINT32 sect;
    UINT32 wcnt;
    UINT32 cc;
    const UINT8 *wbuff = buff;
    FRESULT res;


    *bw = 0;
    res = validate(fp->fs, fp->id);     /* Check validity of the object     */
    if (res != FR_OK)
        {
        return res;
        }
    if (fp->flag & FA__ERROR)
        {
        return FR_RW_ERROR;             /* Check error flag                 */
        }
    if (!(fp->flag & FA_WRITE))
        {
        return FR_DENIED;               /* Check access mode                */
        }
    if (fp->fsize + btw < fp->fsize)
        {
        return FR_OK;                   /* File size cannot reach 4GB       */
        }

    /* Repeat until all data transferred                                    */
    for (; btw; wbuff += wcnt, fp->fptr += wcnt, *bw += wcnt, btw -= wcnt)
        {
        if ((fp->fptr % SS(fp->fs)) == 0)
            {
            /* On the sector boundary?                                      */
            if (fp->csect >= fp->fs->csize)
                {
                /* On the cluster boundary?                                 */
                if (fp->fptr == 0)
                    { 
                    /* On the top of the file?                              */
                    clust = fp->org_clust; /* Follow from the origin        */
                    if (clust == 0)     /* When there is no cluster chain   */
                        {
                        /* Create a new cluster chain                       */
                        fp->org_clust = clust = create_chain(fp->fs, 0); 
                        }
                    } 
                else
                    { 
                    /* Middle or end of the file                            */
                    /* Trace or streach cluster chain                       */
                    clust = create_chain(fp->fs, fp->curr_clust); 
                    }
                if (clust == 0)
                    {
                    /* Could not allocate a new cluster (disk full)         */
                    break; 
                    }
                if (clust == 1 || clust >= fp->fs->max_clust)
                    {
                    goto fw_error;      /* GOTO LABEL AT END OF FUNCTION    */
                    }
                fp->curr_clust = clust; /* Update current cluster           */
                fp->csect = 0;          /* Reset sector address in cluster  */
                }
            
            /* Get current sector                                           */
            sect = clust2sect(fp->fs, fp->curr_clust) + fp->csect; 
            cc = btw / SS(fp->fs);      /* When remaining bytes>=sector size*/
            if (cc)
                { 
                /* Write maximum contiguous sectors directly */
                if (fp->csect + cc > fp->fs->csize)
                    {
                    /* Clip at cluster boundary                             */
                    cc = fp->fs->csize - fp->csect;
                    }
                if (disk_write(fp->fs->drive, wbuff, sect, (UINT8)cc) != RES_OK)
                    {
                    goto fw_error;      /* GOTO LABEL AT END OF FUNCTION    */
                    }
                fp->csect += (UINT8)cc; /* Next sector address in cluster   */
                wcnt = SS(fp->fs) * cc; /* Number of bytes transferred      */
                continue;
                }
            if (sect != fp->curr_sect)
                { 
                /* Is window offset changed? */
                if (fp->flag & FA__DIRTY)
                    { 
                    /* Write back file I/O buffer if needed */
                    if (disk_write(fp->fs->drive, fp->buffer, fp->curr_sect, 1)
                            != RES_OK)
                        {
                        goto fw_error;  /* GOTO LABEL AT END OF FUNCTION    */
                        }
                    fp->flag &= (UINT8)~FA__DIRTY;
                    }
                
                /* Fill file I/O buffer with file data                      */
                if (fp->fptr < fp->fsize && disk_read(fp->fs->drive,
                        fp->buffer, sect, 1) != RES_OK)
                    {
                    goto fw_error;      /* GOTO LABEL AT END OF FUNCTION    */
                    }
                fp->curr_sect = sect;
                }
            fp->csect++;                /* Next sector address in cluster   */
            }
        
        /* Put partial sector into file I/O buffer                          */
        wcnt = SS(fp->fs) - (fp->fptr % SS(fp->fs)); 
        if (wcnt > btw)
            {
            wcnt = btw;
            }
        memcpy(&fp->buffer[fp->fptr % SS(fp->fs)], wbuff, wcnt);
        fp->flag |= FA__DIRTY;
        }

    if (fp->fptr > fp->fsize)
        {
        fp->fsize = fp->fptr;           /* Update file size if needed       */
        }
    fp->flag |= FA__WRITTEN;            /* Set file changed flag            */
    return FR_OK;

    /* GOTO LABEL                                                           */
    fw_error: 
    /* Abort this file due to an unrecoverable error                        */
    fp->flag |= FA__ERROR;
    return FR_RW_ERROR;
}


FRESULT f_sync(FIL *fp)
{
    UINT32 tim;
    UINT8 *dir;
    FRESULT res;

    res = validate(fp->fs, fp->id);     /* Check validity of the object     */
    if (res == FR_OK)
        {
        if (fp->flag & FA__WRITTEN)
            { 
            /* Has the file been written?                                   */
            /* Write back data buffer if needed                             */
            if (fp->flag & FA__DIRTY)
                {
                if (disk_write(fp->fs->drive, fp->buffer, fp->curr_sect, 1)
                        != RES_OK)
                    {
                    return FR_RW_ERROR;
                    }
                fp->flag &= (UINT8)~FA__DIRTY;
                }
            /* Update the directory entry                                   */
            if (!move_window(fp->fs, fp->dir_sect))
                {
                return FR_RW_ERROR;
                }
            dir = fp->dir_ptr;
            dir[DIR_Attr] |= AR_ARC;    /* Set archive bit                  */
            ST_DWORD(&dir[DIR_FileSize], fp->fsize); /* Update file size    */
            ST_WORD(&dir[DIR_FstClusLO], fp->org_clust); /* Update start cl.*/
            ST_WORD(&dir[DIR_FstClusHI], fp->org_clust >> 16);
            tim = get_fattime();
            ST_DWORD(&dir[DIR_WrtTime], tim);
            fp->flag &= (UINT8)~FA__WRITTEN;
            res = sync(fp->fs);
            }
        }
    return res;
}
#endif /* !_FS_READONLY */


FRESULT f_close(FIL *fp)
{
    FRESULT res;

#if !_FS_READONLY
    res = f_sync(fp);
#else
    res = validate(fp->fs, fp->id);
#endif
    if (res == FR_OK)
        fp->fs = NULL;
    return res;
}
#if _FS_MINIMIZE <= 2


FRESULT f_lseek(FIL *fp, UINT32 ofs)
{
    UINT32 clust;
    UINT32 csize;
    UINT32 nsect;
    UINT32 ifptr;
    FRESULT res;


    res = validate(fp->fs, fp->id);     /* Check validity of the object     */
    if (res != FR_OK)
        {
        return res;
        }
    if (fp->flag & FA__ERROR)
        {
        return FR_RW_ERROR;
        }
    if (ofs > fp->fsize 
#if !_FS_READONLY
        /* In read-only mode, clip offset with the file size                */
        && !(fp->flag & FA_WRITE)
#endif
       )
        {
        ofs = fp->fsize;
        }

    ifptr = fp->fptr;
    fp->fptr = 0;
    fp->csect = 255;
    nsect = 0;
    if (ofs > 0)
        {
        csize = (UINT32)fp->fs->csize * SS(fp->fs); /* Cluster size (byte)  */
        if (ifptr > 0 && (ofs - 1) / csize >= (ifptr - 1) / csize)
            {
            /* When seek to same or following cluster                       */
            fp->fptr = (ifptr - 1) & ~(csize - 1); /*start at current clstr */
            ofs -= fp->fptr;
            clust = fp->curr_clust;
            } 
        else
            { 
            /* When seek to back cluster,                                   */
            clust = fp->org_clust;      /* start from the first cluster     */
#if !_FS_READONLY
            if (clust == 0)
                { 
                /* If no cluster chain, create a new chain                  */
                clust = create_chain(fp->fs, 0);
                if (clust == 1)
                    {
                    goto fk_error;      /* GOTO LABEL AT END OF FUNCTION    */
                    }
                fp->org_clust = clust;
                }
#endif
            fp->curr_clust = clust;
            }
        if (clust != 0)
            {
            while (ofs > csize)
                { 
                /* Cluster following loop                                   */
#if !_FS_READONLY
                if (fp->flag & FA_WRITE)
                    { 
                    /* Check if in write mode or not                        */
                    /* Force streached if in write mode                     */
                    clust = create_chain(fp->fs, clust); 
                    if (clust == 0)
                        {
                        /* When disk gets full, clip file size              */
                        ofs = csize;
                        break;
                        }
                    } 
                else
#endif
                    {
                    /* Follow cluster chain if not in write mode */
                    clust = get_cluster(fp->fs, clust); 
                    }
                if (clust < 2 || clust >= fp->fs->max_clust)
                    {
                    goto fk_error;      /* GOTO LABEL AT END OF FUNCTION    */
                    }
                fp->curr_clust = clust;
                fp->fptr += csize;
                ofs -= csize;
                }
            fp->fptr += ofs;
            fp->csect = (UINT8)(ofs / SS(fp->fs)); /*Sect offset in cluster */
            if (ofs & (SS(fp->fs) - 1))
                {
                /* Current sector                                           */
                nsect = clust2sect(fp->fs, clust) + fp->csect; 
                fp->csect++;
                }
            }
        }
    if (nsect && nsect != fp->curr_sect)
        {
#if !_FS_READONLY
        if (fp->flag & FA__DIRTY)
            { 
            /* Write-back dirty buffer if needed                            */
            if (disk_write(fp->fs->drive, fp->buffer, fp->curr_sect, 1)
                    != RES_OK)
                {
                goto fk_error;          /* GOTO LABEL AT END OF FUNCTION    */
                }
            fp->flag &= (UINT8)~FA__DIRTY;
            }
#endif
        if (disk_read(fp->fs->drive, fp->buffer, nsect, 1) != RES_OK)
            {
            goto fk_error;              /* GOTO LABEL AT END OF FUNCTION    */
            }
        fp->curr_sect = nsect;
        }

#if !_FS_READONLY
    if (fp->fptr > fp->fsize)
        { 
        /* Set changed flag if the file was extended                        */
        fp->fsize = fp->fptr;
        fp->flag |= FA__WRITTEN;
        }
#endif

    return FR_OK;

    /* GOTO LABEL                                                           */
    fk_error:
    /* Abort this file due to an unrecoverable error                        */
    fp->flag |= FA__ERROR;
    return FR_RW_ERROR;
}
#if _FS_MINIMIZE <= 1


FRESULT f_opendir(DIR *dj, const char *path)
{
    char fn[8+3+1];
    UINT8 *dir;
    FRESULT res;
    
    
    res = auto_mount(&path, &dj->fs, 0);
    if (res == FR_OK)
        {
        res = trace_path(dj, fn, path, &dir); /* Trace the directory path   */
        if (res == FR_OK)
            { 
            /* Trace completed                                              */
            if (dir)
                { 
                /* It is not the root dir                                   */
                if (dir[DIR_Attr] & AR_DIR)
                    { 
                    /* The entry is a directory                             */
                    dj->clust = ((UINT32)LD_WORD(&dir[DIR_FstClusHI]) << 16)
                            | LD_WORD(&dir[DIR_FstClusLO]);
                    dj->sect = clust2sect(dj->fs, dj->clust);
                    dj->index = 2;
                    } 
                else
                    { 
                    /* The entry is not a directory                         */
                    res = FR_NO_FILE;
                    }
                }
            dj->id = dj->fs->id;
            }
        }

    return res;
}


FRESULT f_readdir(DIR *dj, FILINFO *finfo)
{
    UINT8 *dir;
    UINT8 c;
    UINT8 res;

    res = validate(dj->fs, dj->id);     /* Check validity of the object     */
    if (res != FR_OK)
        {
        return res;
        }

    finfo->fname[0] = 0;
    while (dj->sect)
        {
        if (!move_window(dj->fs, dj->sect))
            {
            return FR_RW_ERROR;
            }
        /* pointer to the directory entry                                   */
        dir = &dj->fs->win[(dj->index & ((SS(dj->fs) - 1) >> 5)) * 32]; 
        c = dir[DIR_Name];
        if (c == 0)
            {
            break;                      /* Has it reached to end of dir?    */
            }
        if (c != 0xE5 && !(dir[DIR_Attr] & AR_VOL)) /* Is it a valid entry? */
            {
            get_fileinfo(finfo, dir);
            }
        if (!next_dir_entry(dj))
            {
            dj->sect = 0;               /* Next entry                       */
            }
        if (finfo->fname[0])
            {
            break;                      /* Found valid entry                */
            }
        }

    return FR_OK;
}
#if _FS_MINIMIZE == 0


FRESULT f_stat(const char *path, FILINFO *finfo)
{
    UINT8 *dir;
    char fn[8+3+1];
    FRESULT res;
    DIR dj;


    res = auto_mount(&path, &dj.fs, 0);
    if (res == FR_OK)
        {
        res = trace_path(&dj, fn, path, &dir); /* Trace the file path       */
        if (res == FR_OK)
            { 
            /* Trace completed                                              */
            if (dir)                    /* Found an object                  */
                {
                get_fileinfo(finfo, dir);
                }
            else
                {
                /* It is root dir */
                res = FR_INVALID_NAME;
                }
            }
        }

    return res;
}
#if !_FS_READONLY


FRESULT f_truncate(FIL *fp)
{
    UINT32 ncl;
    FRESULT res;


    res = validate(fp->fs, fp->id);     /* Check validity of the object     */
    if (res != FR_OK)
        {
        return res;
        }
    if (fp->flag & FA__ERROR)
        {
        return FR_RW_ERROR;             /* Check error flag                 */
        }
    if (!(fp->flag & FA_WRITE))
        {
        return FR_DENIED;               /* Check access mode                */
        }

    if (fp->fsize > fp->fptr)
        {
        fp->fsize = fp->fptr;           /* ile size to current R/W point    */
        fp->flag |= FA__WRITTEN;
        if (fp->fptr == 0)
            { 
            /* When set file size to zero, remove entire cluster chain      */
            if (!remove_chain(fp->fs, fp->org_clust))
                {
                goto ft_error;
                }
            fp->org_clust = 0;
            } 
        else
            { 
            /* When truncate a part of the file, remove remaining clusters  */
            ncl = get_cluster(fp->fs, fp->curr_clust);
            if (ncl < 2)
                {
                goto ft_error;          /* GOTO LABEL AT END OF FUNCTION    */
                }
            if (ncl < fp->fs->max_clust)
                {
                if (!put_cluster(fp->fs, fp->curr_clust, 0x0FFFFFFF))
                    {
                    goto ft_error;      /* GOTO LABEL AT END OF FUNCTION    */
                    }
                if (!remove_chain(fp->fs, ncl))
                    {
                    goto ft_error;      /* GOTO LABEL AT END OF FUNCTION    */
                    }
                }
            }
        }

    return FR_OK;
    
    /* GOTO LABEL                                                           */
    ft_error: 
    /* Abort this file due to an unrecoverable error                        */
    fp->flag |= FA__ERROR;
    return FR_RW_ERROR;
}


FRESULT f_getfree(const char *drive, UINT32 *nclust, FATFS **fatfs)
{
    UINT32 n;
    UINT32 clust;
    UINT32 sect;
    UINT8 fat;
    UINT8 f;
    UINT8 *p;
    FRESULT res;
    

    /* Get drive number                                                     */
    res = auto_mount(&drive, fatfs, 0);
    if (res != FR_OK)
        {
        return res;
        }

    /* If number of free cluster is valid, return it without cluster scan.  */
    if ((*fatfs)->free_clust <= (*fatfs)->max_clust - 2)
        {
        *nclust = (*fatfs)->free_clust;
        return FR_OK;
        }

    /* Get number of free clusters                                          */
    fat = (*fatfs)->fs_type;
    n = 0;
    if (fat == FS_FAT12)
        {
        clust = 2;
        do
            {
            if ((UINT16)get_cluster(*fatfs, clust) == 0)
                {
                n++;
                }
            } while (++clust < (*fatfs)->max_clust);
        }
    else
        {
        clust = (*fatfs)->max_clust;
        sect = (*fatfs)->fatbase;
        f = 0;
        p = 0;
        do
            {
            if (!f)
                {
                if (!move_window(*fatfs, sect++))
                    {
                    return FR_RW_ERROR;
                    }
                p = (*fatfs)->win;
                }
            if (fat == FS_FAT16)
                {
                if (LD_WORD(p) == 0)
                    {
                    n++;
                    }
                p += 2;
                f += 1;
                } 
            else
                {
                if (LD_DWORD(p) == 0)
                    {
                    n++;
                    }
                p += 4;
                f += 2;
                }
            } while (--clust);
        }
    (*fatfs)->free_clust = n;
#if _USE_FSINFO
    if (fat == FS_FAT32)
        {
        (*fatfs)->fsi_flag = 1;
        }
#endif

    *nclust = n;
    return FR_OK;
}


FRESULT f_unlink(const char *path)
{
    UINT32 dclust;
    UINT32 dsect;
    char fn[8+3+1];
    UINT8 *dir;
    UINT8 *sdir;
    FRESULT res;
    DIR dj;


    res = auto_mount(&path, &dj.fs, 1);
    if (res != FR_OK)
        {
        return res;
        }
    res = trace_path(&dj, fn, path, &dir); /* Trace the file path           */
    if (res != FR_OK)
        {
        return res;                     /* Trace failed                     */
        }
    if (!dir)
        {
        return FR_INVALID_NAME;         /* It is the root directory         */
        }
    if (dir[DIR_Attr] & AR_RDO)
        {
        return FR_DENIED;               /* It is a R/O object               */
        }
    dsect = dj.fs->winsect;
    dclust = ((UINT32)LD_WORD(&dir[DIR_FstClusHI]) << 16)
            | LD_WORD(&dir[DIR_FstClusLO]);

    if (dir[DIR_Attr] & AR_DIR)
        { 
        /* It is a sub-directory                                            */
        dj.clust = dclust;              /* Check if sub-dir is empty or not */
        dj.sect = clust2sect(dj.fs, dclust);
        dj.index = 2;
        do
            {
            if (!move_window(dj.fs, dj.sect))
                {
                return FR_RW_ERROR;
                }
            sdir = &dj.fs->win[(dj.index & ((SS(dj.fs) - 1) >> 5)) * 32];
            if (sdir[DIR_Name] == 0)
                {
                break;
                }
            if (sdir[DIR_Name] != 0xE5 && !(sdir[DIR_Attr] & AR_VOL))
                {
                return FR_DENIED;       /* The directory is not empty       */
                }
            } while (next_dir_entry(&dj));
        }

    if (!move_window(dj.fs, dsect))
        {
        return FR_RW_ERROR;             /* Mark directory entry 'deleted'   */
        }
    dir[DIR_Name] = 0xE5;
    dj.fs->winflag = 1;
    if (!remove_chain(dj.fs, dclust))
        {
        return FR_RW_ERROR;             /* Remove the cluster chain         */
        }

    return sync(dj.fs);
}


FRESULT f_mkdir(const char *path)
{
    UINT32 sect;
    UINT32 dsect;
    UINT32 dclust;
    UINT32 pclust;
    UINT32 tim;
    char fn[8+3+1];
    UINT8 *dir;
    UINT8 *fw;
    UINT8 n;
    FRESULT res;
    DIR dj;


    res = auto_mount(&path, &dj.fs, 1);
    if (res != FR_OK)
        {
        return res;
        }
    res = trace_path(&dj, fn, path, &dir); /* Trace the file path           */
    if (res == FR_OK)
        {
        return FR_EXIST;                /* Any file or directory is existing*/
        }
    if (res != FR_NO_FILE)
        {
        return res;
        }

    res = reserve_direntry(&dj, &dir);  /* Reserve a directory entry        */
    if (res != FR_OK)
        {
        return res;
        }
    sect = dj.fs->winsect;
    /* Allocate a cluster for new directory table                           */
    dclust = create_chain(dj.fs, 0);    
    if (dclust == 1)
        {
        return FR_RW_ERROR;
        }
    dsect = clust2sect(dj.fs, dclust);
    if (!dsect)
        {
        return FR_DENIED;
        }
    if (!move_window(dj.fs, dsect))
        {
        return FR_RW_ERROR;
        }

    fw = dj.fs->win;
    memset(fw, 0, SS(dj.fs));           /* Clear the new directory table    */
    for (n = 1; n < dj.fs->csize; n++)
        {
        if (disk_write(dj.fs->drive, fw, ++dsect, 1) != RES_OK)
            {
            return FR_RW_ERROR;
            }
        }
    memset(&fw[DIR_Name], ' ', 8+3);    /* Create "." entry                 */
    fw[DIR_Name] = '.';
    fw[DIR_Attr] = AR_DIR;
    tim = get_fattime();
    ST_DWORD(&fw[DIR_WrtTime], tim);
    memcpy(&fw[32], &fw[0], 32);
    fw[33] = '.';                       /* Create ".." entry                */
    ST_WORD(&fw[ DIR_FstClusLO], dclust);
    ST_WORD(&fw[ DIR_FstClusHI], dclust >> 16);
    pclust = dj.sclust;
    if (dj.fs->fs_type == FS_FAT32 && pclust == dj.fs->dirbase)
        {
        pclust = 0;
        }
    ST_WORD(&fw[32+DIR_FstClusLO], pclust);
    ST_WORD(&fw[32+DIR_FstClusHI], pclust >> 16);
    dj.fs->winflag = 1;

    if (!move_window(dj.fs, sect))
        {
        return FR_RW_ERROR;
        }
    memset(&dir[0], 0, 32);             /* Initialize the new entry         */
    memcpy(&dir[DIR_Name], fn, 8+3);    /* Name                             */
    dir[DIR_NTres] = fn[11];
    dir[DIR_Attr] = AR_DIR;             /* Attribute                        */
    ST_DWORD(&dir[DIR_WrtTime], tim);   /* Crated time                      */
    ST_WORD(&dir[DIR_FstClusLO], dclust); /* Table start cluster            */
    ST_WORD(&dir[DIR_FstClusHI], dclust >> 16);

    return sync(dj.fs);
}



FRESULT f_chmod(const char *path, UINT8 value, UINT8 mask)
{
    char fn[8+3+1];
    UINT8 *dir;
    FRESULT res;
    DIR dj;

    res = auto_mount(&path, &dj.fs, 1);
    if (res == FR_OK)
        {
        res = trace_path(&dj, fn, path, &dir); /* Trace the file path       */
        if (res == FR_OK)
            {
            /* Trace completed                                              */
            if (!dir)
                {
                res = FR_INVALID_NAME;  /* Root directory                   */
                } 
            else
                {
                mask &= AR_RDO|AR_HID|AR_SYS|AR_ARC; /* Valid attribute mask*/
                /* Apply attribute change                                   */
                dir[DIR_Attr] = (value & mask) | (dir[DIR_Attr] & (UINT8)~mask); 
                res = sync(dj.fs);
                }
            }
        }
    return res;
}


FRESULT f_utime(const char *path, const FILINFO *finfo)
{
    char fn[8+3+1];
    UINT8 *dir;
    FRESULT res;
    DIR dj;
    
    
    res = auto_mount(&path, &dj.fs, 1);
    if (res == FR_OK)
        {
        res = trace_path(&dj, fn, path, &dir); /* Trace the file path       */
        if (res == FR_OK)
            { 
            /* Trace completed                                              */
            if (!dir)
                {
                res = FR_INVALID_NAME;  /* Root directory                   */
                } 
            else
                {
                ST_WORD(&dir[DIR_WrtTime], finfo->ftime);
                ST_WORD(&dir[DIR_WrtDate], finfo->fdate);
                res = sync(dj.fs);
                }
            }
        }
    return res;
}


FRESULT f_rename(const char *path_old, const char *path_new)
{
    UINT32 sect_old;
    char fn[8+3+1];
    UINT8 *dir_old;
    UINT8 *dir_new;
    UINT8 direntry[32-11];
    FRESULT res;
    DIR dj;

    res = auto_mount(&path_old, &dj.fs, 1);
    if (res != FR_OK)
        {
        return res;
        }

    res = trace_path(&dj, fn, path_old, &dir_old); /* Check old object      */
    if (res != FR_OK)
        {
        return res;                     /* The old object is not found      */
        }
    if (!dir_old)
        {
        return FR_NO_FILE;
        }
    sect_old = dj.fs->winsect;          /* Save the object information      */
    memcpy(direntry, &dir_old[DIR_Attr], 32-11);

    res = trace_path(&dj, fn, path_new, &dir_new); /* Check new object      */
    if (res == FR_OK)
        {
        return FR_EXIST;                /*New object name already existing  */
        }
    if (res != FR_NO_FILE)
        {
        return res;                     /* Is there no old name?            */
        }
    res = reserve_direntry(&dj, &dir_new); /* Reserve a directory entry     */
    if (res != FR_OK)
        {
        return res;
        }

    memcpy(&dir_new[DIR_Attr], direntry, 32-11); /* Create new entry        */
    memcpy(&dir_new[DIR_Name], fn, 8+3);
    dir_new[DIR_NTres] = fn[11];
    dj.fs->winflag = 1;

    if (!move_window(dj.fs, sect_old))
        {
        return FR_RW_ERROR;             /* Delete old entry                 */
        }
    dir_old[DIR_Name] = 0xE5;

    return sync(dj.fs);
}

#endif /* !_FS_READONLY */
#endif /* _FS_MINIMIZE == 0 */
#endif /* _FS_MINIMIZE <= 1 */
#endif /* _FS_MINIMIZE <= 2 */

#if _USE_MKFS && !_FS_READONLY
/*-----------------------------------------------------------------------*/
/* Create File System on the Drive                                       */
/*-----------------------------------------------------------------------*/
#define N_ROOTDIR   512         /* Multiple of 32 and <= 2048 */
#define N_FATS      1           /* 1 or 2 */
#define MAX_SECTOR  64000000UL  /* Maximum partition size */
#define MIN_SECTOR  2000UL      /* Minimum partition size */

FRESULT f_mkfs (
        UINT8 drv, /* Logical drive number */
        UINT8 partition, /* Partitioning rule 0:FDISK, 1:SFD */
        UINT16 allocsize /* Allocation unit size [bytes] */
)
    {
    UINT8 fmt, m, *tbl;
    UINT32 b_part, b_fat, b_dir, b_data; /* Area offset (LBA) */
    UINT32 n_part, n_rsv, n_fat, n_dir; /* Area size */
    UINT32 n_clust, n;
    FATFS *fs;
    DSTATUS stat;

    /* Check validity of the parameters */
    if (drv >= _DRIVES) return FR_INVALID_DRIVE;
    if (partition >= 2) return FR_MKFS_ABORTED;
    for (n = 512; n <= 32768U && n != allocsize; n <<= 1);
    if (n != allocsize) return FR_MKFS_ABORTED;

    /* Check mounted drive and clear work area */
    fs = FatFs[drv];
    if (!fs) return FR_NOT_ENABLED;
    fs->fs_type = 0;
    drv = LD2PD(drv);

    /* Get disk statics */
    stat = disk_initialize(drv);
    if (stat & STA_NOINIT) return FR_NOT_READY;
    if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
    if (disk_ioctl(drv, GET_SECTOR_COUNT, &n_part) != RES_OK || n_part < MIN_SECTOR)
    return FR_MKFS_ABORTED;
    if (n_part> MAX_SECTOR) n_part = MAX_SECTOR;
    b_part = (!partition) ? 63 : 0; /* Boot sector */
    n_part -= b_part;
#if S_MAX_SIZ > 512                     /* Check disk sector size */
    if (disk_ioctl(drv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK
            || SS(fs)> S_MAX_SIZ
            || SS(fs)> allocsize)
    return FR_MKFS_ABORTED;
#endif
    allocsize /= SS(fs); /* Number of sectors per cluster */

    /* Pre-compute number of clusters and FAT type */
    n_clust = n_part / allocsize;
    fmt = FS_FAT12;
    if (n_clust >= 0xFF5) fmt = FS_FAT16;
    if (n_clust >= 0xFFF5) fmt = FS_FAT32;

    /* Determine offset and size of FAT structure */
    switch (fmt)
        {
        case FS_FAT12:
        n_fat = ((n_clust * 3 + 1) / 2 + 3 + SS(fs) - 1) / SS(fs);
        n_rsv = 1 + partition;
        n_dir = N_ROOTDIR * 32 / SS(fs);
        break;
        case FS_FAT16:
        n_fat = ((n_clust * 2) + 4 + SS(fs) - 1) / SS(fs);
        n_rsv = 1 + partition;
        n_dir = N_ROOTDIR * 32 / SS(fs);
        break;
        default:
        n_fat = ((n_clust * 4) + 8 + SS(fs) - 1) / SS(fs);
        n_rsv = 33 - partition;
        n_dir = 0;
        }
    b_fat = b_part + n_rsv; /* FATs start sector */
    b_dir = b_fat + n_fat * N_FATS; /* Directory start sector */
    b_data = b_dir + n_dir; /* Data start sector */

    /* Align data start sector to erase block boundary (for flash memory media) */
    if (disk_ioctl(drv, GET_BLOCK_SIZE, &n) != RES_OK) return FR_MKFS_ABORTED;
    n = (b_data + n - 1) & ~(n - 1);
    n_fat += (n - b_data) / N_FATS;
    /* b_dir and b_data are no longer used below */

    /* Determine number of cluster and final check of validity of the FAT type */
    n_clust = (n_part - n_rsv - n_fat * N_FATS - n_dir) / allocsize;
    if ( (fmt == FS_FAT16 && n_clust < 0xFF5)
            || (fmt == FS_FAT32 && n_clust < 0xFFF5))
    return FR_MKFS_ABORTED;

    /* Create partition table if needed */
    if (!partition)
        {
        UINT32 n_disk = b_part + n_part;

        tbl = &fs->win[MBR_Table];
        ST_DWORD(&tbl[0], 0x00010180); /* Partition start in CHS */
        if (n_disk < 63UL * 255 * 1024)
            { /* Partition end in CHS */
            n_disk = n_disk / 63 / 255;
            tbl[7] = (UINT8)n_disk;
            tbl[6] = (UINT8)((n_disk >> 2) | 63);
            } else
            {
            ST_WORD(&tbl[6], 0xFFFF);
            }
        tbl[5] = 254;
        if (fmt != FS_FAT32) /* System ID */
        tbl[4] = (n_part < 0x10000) ? 0x04 : 0x06;
        else
        tbl[4] = 0x0c;
        ST_DWORD(&tbl[8], 63); /* Partition start in LBA */
        ST_DWORD(&tbl[12], n_part); /* Partition size in LBA */
        ST_WORD(&tbl[64], 0xAA55); /* Signature */
        if (disk_write(drv, fs->win, 0, 1) != RES_OK)
        return FR_RW_ERROR;
        }

    /* Create boot record */
    tbl = fs->win; /* Clear buffer */
    memset(tbl, 0, SS(fs));
    ST_DWORD(&tbl[BS_jmpBoot], 0x90FEEB); /* Boot code (jmp $, nop) */
    ST_WORD(&tbl[BPB_BytsPerSec], SS(fs)); /* Sector size */
    tbl[BPB_SecPerClus] = (UINT8)allocsize; /* Sectors per cluster */
    ST_WORD(&tbl[BPB_RsvdSecCnt], n_rsv); /* Reserved sectors */
    tbl[BPB_NumFATs] = N_FATS; /* Number of FATs */
    ST_WORD(&tbl[BPB_RootEntCnt], SS(fs) / 32 * n_dir); /* Number of rootdir entries */
    if (n_part < 0x10000)
        { /* Number of total sectors */
        ST_WORD(&tbl[BPB_TotSec16], n_part);
        } else
        {
        ST_DWORD(&tbl[BPB_TotSec32], n_part);
        }
    tbl[BPB_Media] = 0xF8; /* Media descripter */
    ST_WORD(&tbl[BPB_SecPerTrk], 63); /* Number of sectors per track */
    ST_WORD(&tbl[BPB_NumHeads], 255); /* Number of heads */
    ST_DWORD(&tbl[BPB_HiddSec], b_part); /* Hidden sectors */
    n = get_fattime(); /* Use current time as a VSN */
    if (fmt != FS_FAT32)
        {
        ST_DWORD(&tbl[BS_VolID], n); /* Volume serial number */
        ST_WORD(&tbl[BPB_FATSz16], n_fat); /* Number of secters per FAT */
        tbl[BS_DrvNum] = 0x80; /* Drive number */
        tbl[BS_BootSig] = 0x29; /* Extended boot signature */
        memcpy(&tbl[BS_VolLab], "NO NAME    FAT     ", 19); /* Volume lavel, FAT signature */
        } else
        {
        ST_DWORD(&tbl[BS_VolID32], n); /* Volume serial number */
        ST_DWORD(&tbl[BPB_FATSz32], n_fat); /* Number of secters per FAT */
        ST_DWORD(&tbl[BPB_RootClus], 2); /* Root directory cluster (2) */
        ST_WORD(&tbl[BPB_FSInfo], 1); /* FSInfo record (bs+1) */
        ST_WORD(&tbl[BPB_BkBootSec], 6); /* Backup boot record (bs+6) */
        tbl[BS_DrvNum32] = 0x80; /* Drive number */
        tbl[BS_BootSig32] = 0x29; /* Extended boot signature */
        memcpy(&tbl[BS_VolLab32], "NO NAME    FAT32   ", 19); /* Volume lavel, FAT signature */
        }
    ST_WORD(&tbl[BS_55AA], 0xAA55); /* Signature */
    if (disk_write(drv, tbl, b_part+0, 1) != RES_OK)
    return FR_RW_ERROR;
    if (fmt == FS_FAT32)
    disk_write(drv, tbl, b_part+6, 1);

    /* Initialize FAT area */
    for (m = 0; m < N_FATS; m++)
        {
        memset(tbl, 0, SS(fs)); /* 1st sector of the FAT  */
        if (fmt != FS_FAT32)
            {
            n = (fmt == FS_FAT12) ? 0x00FFFFF8 : 0xFFFFFFF8;
            ST_DWORD(&tbl[0], n); /* Reserve cluster #0-1 (FAT12/16) */
            } else
            {
            ST_DWORD(&tbl[0], 0xFFFFFFF8); /* Reserve cluster #0-1 (FAT32) */
            ST_DWORD(&tbl[4], 0xFFFFFFFF);
            ST_DWORD(&tbl[8], 0x0FFFFFFF); /* Reserve cluster #2 for root dir */
            }
        if (disk_write(drv, tbl, b_fat++, 1) != RES_OK)
        return FR_RW_ERROR;
        memset(tbl, 0, SS(fs)); /* Following FAT entries are filled by zero */
        for (n = 1; n < n_fat; n++)
            {
            if (disk_write(drv, tbl, b_fat++, 1) != RES_OK)
            return FR_RW_ERROR;
            }
        }

    /* Initialize Root directory */
    m = (UINT8)((fmt == FS_FAT32) ? allocsize : n_dir);
    do
        {
        if (disk_write(drv, tbl, b_fat++, 1) != RES_OK)
        return FR_RW_ERROR;
        }while (--m);

    /* Create FSInfo record if needed */
    if (fmt == FS_FAT32)
        {
        ST_WORD(&tbl[BS_55AA], 0xAA55);
        ST_DWORD(&tbl[FSI_LeadSig], 0x41615252);
        ST_DWORD(&tbl[FSI_StrucSig], 0x61417272);
        ST_DWORD(&tbl[FSI_Free_Count], n_clust - 1);
        ST_DWORD(&tbl[FSI_Nxt_Free], 0xFFFFFFFF);
        disk_write(drv, tbl, b_part+1, 1);
        disk_write(drv, tbl, b_part+7, 1);
        }

    return (disk_ioctl(drv, CTRL_SYNC, NULL) == RES_OK) ? FR_OK : FR_RW_ERROR;
    }

#endif /* _USE_MKFS && !_FS_READONLY */

#if _USE_STRFUNC >= 1
/*-----------------------------------------------------------------------*/
/* Get a string from the file                                            */
/*-----------------------------------------------------------------------*/
char* fgets (
        char* buff, /* Pointer to the string buffer to read */
        int len, /* Size of string buffer */
        FIL* fil /* Pointer to the file object */
)
    {
    int i = 0;
    char *p = buff;
    UINT rc;

    while (i < len - 1)
        { /* Read bytes until buffer gets filled */
        f_read(fil, p, 1, &rc);
        if (rc != 1) break; /* Break when no data to read */
#if _USE_STRFUNC >= 2
        if (*p == '\r') continue; /* Strip '\r' */
#endif
        i++;
        if (*p++ == '\n') break; /* Break when reached end of line */
        }
    *p = 0;
    return i ? buff : 0; /* When no data read (eof or error), return with error. */
    }

#if !_FS_READONLY
#include <stdarg.h>
/*-----------------------------------------------------------------------*/
/* Put a character to the file                                           */
/*-----------------------------------------------------------------------*/
int fputc (
        int chr, /* A character to be output */
        FIL* fil /* Ponter to the file object */
)
    {
    UINT bw;
    char c;

#if _USE_STRFUNC >= 2
    if (chr == '\n') fputc ('\r', fil); /* LF -> CRLF conversion */
#endif
    if (!fil)
        { /* Special value may be used to switch the destination to any other device */
        /*  put_console(chr);   */
        return chr;
        }
    c = (char)chr;
    f_write(fil, &c, 1, &bw); /* Write a byte to the file */
    return bw ? chr : EOF; /* Return the resulut */
    }

/*-----------------------------------------------------------------------*/
/* Put a string to the file                                              */
/*-----------------------------------------------------------------------*/
int fputs (
        const char* str, /* Pointer to the string to be output */
        FIL* fil /* Pointer to the file object */
)
    {
    int n;

    for (n = 0; *str; str++, n++)
        {
        if (fputc(*str, fil) == EOF) return EOF;
        }
    return n;
    }

/*-----------------------------------------------------------------------*/
/* Put a formatted string to the file                                    */
/*-----------------------------------------------------------------------*/
int fprintf (
        FIL* fil, /* Pointer to the file object */
        const char* str, /* Pointer to the format string */
        ... /* Optional arguments... */
)
    {
    va_list arp;
    UCHAR c, f, r;
    ULONG val;
    char s[16];
    int i, w, res, cc;

    va_start(arp, str);

    for (cc = res = 0; cc != EOF; res += cc)
        {
        c = *str++;
        if (c == 0) break; /* End of string */
        if (c != '%')
            { /* Non escape cahracter */
            cc = fputc(c, fil);
            if (cc != EOF) cc = 1;
            continue;
            }
        w = f = 0;
        c = *str++;
        if (c == '0')
            { /* Flag: '0' padding */
            f = 1; c = *str++;
            }
        while (c >= '0' && c <= '9')
            { /* Precision */
            w = w * 10 + (c - '0');
            c = *str++;
            }
        if (c == 'l')
            { /* Prefix: Size is long int */
            f |= 2; c = *str++;
            }
        if (c == 's')
            { /* Type is string */
            cc = fputs(va_arg(arp, char*), fil);
            continue;
            }
        if (c == 'c')
            { /* Type is character */
            cc = fputc(va_arg(arp, char), fil);
            if (cc != EOF) cc = 1;
            continue;
            }
        r = 0;
        if (c == 'd') r = 10; /* Type is signed decimal */
        if (c == 'u') r = 10; /* Type is unsigned decimal */
        if (c == 'X') r = 16; /* Type is unsigned hexdecimal */
        if (r == 0) break; /* Unknown type */
        if (f & 2)
            { /* Get the value */
            val = (ULONG)va_arg(arp, long);
            } else
            {
            val = (c == 'd') ? (ULONG)(long)va_arg(arp, int) : (ULONG)va_arg(arp, unsigned int);
            }
        /* Put numeral string */
        if (c == 'd')
            {
            if (val >= 0x80000000)
                {
                val = 0 - val;
                f |= 4;
                }
            }
        i = sizeof(s) - 1; s[i] = 0;
        do
            {
            c = (UCHAR)(val % r + '0');
            if (c> '9') c += 7;
            s[--i] = c;
            val /= r;
            }while (i && val);
        if (i && (f & 4)) s[--i] = '-';
        w = sizeof(s) - 1 - w;
        while (i && i> w) s[--i] = (f & 1) ? '0' : ' ';
        cc = fputs(&s[i], fil);
        }

    va_end(arp);
    return (cc == EOF) ? cc : res;
    }

#endif /* !_FS_READONLY */
#endif /* _USE_STRFUNC >= 1*/
