Subversion Repositories NaviCtrl

Rev

Rev 378 | Rev 380 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1 ingob 1
/*#######################################################################################*/
2
/* !!! THIS IS NOT FREE SOFTWARE !!!                                                     */
3
/*#######################################################################################*/
4
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
5
// + www.MikroKopter.com
6
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
360 holgerb 7
// + Software Nutzungsbedingungen (english version: see below)
8
// + der Fa. HiSystems GmbH, Flachsmeerstrasse 2, 26802 Moormerland - nachfolgend Lizenzgeber genannt -
9
// + Der Lizenzgeber räumt dem Kunden ein nicht-ausschließliches, zeitlich und räumlich* unbeschränktes Recht ein, die im den
10
// + Mikrocontroller verwendete Firmware für die Hardware Flight-Ctrl, Navi-Ctrl, BL-Ctrl, MK3Mag & PC-Programm MikroKopter-Tool 
11
// + - nachfolgend Software genannt - nur für private Zwecke zu nutzen.
12
// + Der Einsatz dieser Software ist nur auf oder mit Produkten des Lizenzgebers zulässig.
1 ingob 13
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
360 holgerb 14
// + Die vom Lizenzgeber gelieferte Software ist urheberrechtlich geschützt. Alle Rechte an der Software sowie an sonstigen im
15
// + Rahmen der Vertragsanbahnung und Vertragsdurchführung überlassenen Unterlagen stehen im Verhältnis der Vertragspartner ausschließlich dem Lizenzgeber zu.
16
// + Die in der Software enthaltenen Copyright-Vermerke, Markenzeichen, andere Rechtsvorbehalte, Seriennummern sowie
17
// + sonstige der Programmidentifikation dienenden Merkmale dürfen vom Kunden nicht verändert oder unkenntlich gemacht werden.
18
// + Der Kunde trifft angemessene Vorkehrungen für den sicheren Einsatz der Software. Er wird die Software gründlich auf deren
19
// + Verwendbarkeit zu dem von ihm beabsichtigten Zweck testen, bevor er diese operativ einsetzt.
20
// + Die Haftung des Lizenzgebers wird - soweit gesetzlich zulässig - begrenzt in Höhe des typischen und vorhersehbaren
21
// + Schadens. Die gesetzliche Haftung bei Personenschäden und nach dem Produkthaftungsgesetz bleibt unberührt. Dem Lizenzgeber steht jedoch der Einwand 
22
// + des Mitverschuldens offen.
23
// + Der Kunde trifft angemessene Vorkehrungen für den Fall, dass die Software ganz oder teilweise nicht ordnungsgemäß arbeitet.
24
// + Er wird die Software gründlich auf deren Verwendbarkeit zu dem von ihm beabsichtigten Zweck testen, bevor er diese operativ einsetzt.
25
// + Der Kunde wird er seine Daten vor Einsatz der Software nach dem Stand der Technik sichern.
26
// + Der Kunde ist darüber unterrichtet, dass der Lizenzgeber seine Daten im zur Vertragsdurchführung erforderlichen Umfang
27
// + und auf Grundlage der Datenschutzvorschriften erhebt, speichert, verarbeitet und, sofern notwendig, an Dritte übermittelt.
28
// + *) Die räumliche Nutzung bezieht sich nur auf den Einsatzort, nicht auf die Reichweite der programmierten Software.
29
// + #### ENDE DER NUTZUNGSBEDINGUNGEN ####'
30
// +  Hinweis: Informationen über erweiterte Nutzungsrechte (wie z.B. Nutzung für nicht-private Zwecke) sind auf Anfrage per Email an info(@)hisystems.de verfügbar.
1 ingob 31
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
360 holgerb 32
// + Software LICENSING TERMS
1 ingob 33
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
360 holgerb 34
// + of HiSystems GmbH, Flachsmeerstrasse 2, 26802 Moormerland, Germany - the Licensor -
35
// + The Licensor grants the customer a non-exclusive license to use the microcontroller firmware of the Flight-Ctrl, Navi-Ctrl, BL-Ctrl, and MK3Mag hardware 
36
// + (the Software) exclusively for private purposes. The License is unrestricted with respect to time and territory*.
37
// + The Software may only be used with the Licensor's products.
38
// + The Software provided by the Licensor is protected by copyright. With respect to the relationship between the parties to this
39
// + agreement, all rights pertaining to the Software and other documents provided during the preparation and execution of this
40
// + agreement shall be the property of the Licensor.
41
// + The information contained in the Software copyright notices, trademarks, other legal reservations, serial numbers and other
42
// + features that can be used to identify the program may not be altered or defaced by the customer.
43
// + The customer shall be responsible for taking reasonable precautions
44
// + for the safe use of the Software. The customer shall test the Software thoroughly regarding its suitability for the
45
// + intended purpose before implementing it for actual operation. The Licensor's liability shall be limited to the extent of typical and
46
// + foreseeable damage to the extent permitted by law, notwithstanding statutory liability for bodily injury and product
47
// + liability. However, the Licensor shall be entitled to the defense of contributory negligence.
48
// + The customer will take adequate precautions in the case, that the software is not working properly. The customer will test
49
// + the software for his purpose before any operational usage. The customer will backup his data before using the software.
50
// + The customer understands that the Licensor collects, stores and processes, and, where required, forwards, customer data
51
// + to third parties to the extent necessary for executing the agreement, subject to applicable data protection and privacy regulations.
52
// + *) The territory aspect only refers to the place where the Software is used, not its programmed range.
53
// + #### END OF LICENSING TERMS ####
54
// + Note: For information on license extensions (e.g. commercial use), please contact us at info(@)hisystems.de.
1 ingob 55
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
41 ingob 56
#include <stdio.h>
379 holgerb 57
#include <string.h>
41 ingob 58
#include "91x_lib.h"
119 killagreg 59
#include "timer1.h"
41 ingob 60
#include "fat16.h"
61
#include "sdc.h"
62
#include "uart1.h"
379 holgerb 63
#include "main.h"
64
 
1 ingob 65
//________________________________________________________________________________________________________________________________________
88 killagreg 66
// Module name:                 fat16.c
1 ingob 67
// Compiler used:               avr-gcc 3.4.5
211 killagreg 68
// Last Modifikation:   20.03.2010
69
// Version:                             2.10
88 killagreg 70
// Authors:                             Stephan Busker & Gregor Stobrawa
41 ingob 71
// Description:                 Source files for FAT16 implementation with read and write-access
72
//                                              Copyright (C) 2008 Stephan Busker & Gregor Stobrawa
1 ingob 73
//........................................................................................................................................
41 ingob 74
// Functions:                   extern s16              Fat16_Init(void);
88 killagreg 75
//                                              extern s16              Fat16_Deinit(void);
211 killagreg 76
//                                              extern s8*              FAT16_GetVolumeLabel(void);
41 ingob 77
//                                              extern File_t * fopen_(const u8 *filename, const s8 mode);
78
//                                              extern s16              fclose_(File_t *File);
211 killagreg 79
//                                              extern u8               fexist_(s8 * const filename);
41 ingob 80
//                                              extern s16              fflush_(File_t *File);
81
//                                              extern s16      fseek_(File_t *File, s32 offset, s16 origin);
82
//                                              extern s16              fgetc_(File_t *File);
83
//                                              extern s16              fputc_(u8 c, File_t *File);
88 killagreg 84
//                                              extern u32              fread_(void *buffer, u32 size, u32 count, File_t *File);
41 ingob 85
//                                              extern u32              fwrite_(void *buffer, u32 size, u32 count, File_t *File);
86
//                                              extern s16              fputs_(const u8 *string, File_t *File);
87
//                                              extern u8 *     fgets_(u8 *string, s16 length, File_t *File);
211 killagreg 88
//                                              extern u8               feof_(File_t * const file);
1 ingob 89
//........................................................................................................................................
41 ingob 90
// ext. functions:              extern SD_Result_t SDC_Init(void;)
91
//                                              extern SD_Result_t SDC_Deinit(void);
88 killagreg 92
//                      extern SD_Result_t SDC_GetSector (u32,u8 *);
41 ingob 93
//                                              extern SD_Result_t SDC_PutSector (u32,u8 *);
1 ingob 94
//........................................................................................................................................
95
//
96
// URL:                                 www.Mikro-Control.de
97
// mailto:                              stephan.busker@mikro-control.de
98
//________________________________________________________________________________________________________________________________________
99
 
41 ingob 100
/*
101
FAT16 Drive Layout:
102
Description                                             Offset
103
Volume Boot Sector                                      Start of Partition
104
Fat Tables                                                      Start + # of Reserved Sectors
105
Root Directory Entry                            Start + # of Reserved + (# of Sectors Per FAT * 2)
106
Data Area (Starts with Cluster #2)      Start + # of Reserved + (# of Sectors Per FAT * 2) + ((Maximum Root Directory Entries * 32) / Bytes per Sector)
107
*/
1 ingob 108
 
109
 
379 holgerb 110
 
41 ingob 111
/*
112
________________________________________________________________________________________________________________________________________
88 killagreg 113
 
114
        Structure of an partition entry
41 ingob 115
________________________________________________________________________________________________________________________________________
1 ingob 116
 
41 ingob 117
        Partition Entry is 16 bytes long
118
*/
119
typedef struct
120
{
121
        u8      PartitionState;                         // Current State of Partition (00h=Inactive, 80h=Active)
122
        u8      BeginningHead;                          // Beginning of Partition - Head
123
        u16     BeginningCylSec;                        // Beginning of Partition - Cylinder/Sector (See Below)
124
        u8      Type;                                           // Type of Partition (See List Below)
125
        u8      EndHead;                                        // End of Partition - Head
126
        u16     EndCylSec;                                      // End of Partition - Cylinder/Sector
127
        u32     NoSectorsBeforePartition;       // Number of Sectors between the MBR and the First Sector in the Partition
128
        u32     NoSectorsPartition      ;               // Number of Sectors in the Partition
88 killagreg 129
} __attribute__((packed)) PartitionEntry_t;
1 ingob 130
 
379 holgerb 131
 
132
 
41 ingob 133
/*
134
Coding of Cylinder/Sector words
1 ingob 135
 
41 ingob 136
Cylinder is 10 bits:  [7:0] at [15:8] and [9:8] at [7:6]
88 killagreg 137
Sector is 5 bits:  [5:0] at [5:0]
41 ingob 138
*/
1 ingob 139
 
41 ingob 140
// Partition Types:
141
#define PART_TYPE_UNKNOWN                       0x00
142
#define PART_TYPE_FAT12                         0x01
143
#define PART_TYPE_XENIX                         0x02
144
#define PART_TYPE_FAT16_ST_32_MB        0x04
145
#define PART_TYPE_EXTDOS                        0x05
146
#define PART_TYPE_FAT16_LT_32_MB        0x06
147
#define PART_TYPE_NTFS                          0x07
148
#define PART_TYPE_FAT32                         0x0B
149
#define PART_TYPE_FAT32LBA                      0x0C
150
#define PART_TYPE_FAT16LBA                      0x0E
151
#define PART_TYPE_EXTDOSLBA                     0x0F
152
#define PART_TYPE_EISA                          0x12
153
#define PART_TYPE_ONTRACK                       0x33
154
#define PART_TYPE_NOVELL                        0x40
155
#define PART_TYPE_DYNAMIC                       0x42
156
#define PART_TYPE_PCIX                          0x4B
157
#define PART_TYPE_LINUX_SWAP            0x82
158
#define PART_TYPE_LINUX_NATIVE          0x83
159
#define PART_TYPE_LINUX_LVM                     0x8E
160
#define PART_TYPE_PHOENIXSAVE           0xA0
161
#define PART_TYPE_FREEBSD                       0xA5
162
#define PART_TYPE_OPENBSD                       0xA6
163
#define PART_TYPE_NETNBSD                       0xA9
164
#define PART_TYPE_CPM                           0xDB
165
#define PART_TYPE_DBFS                          0xE0
166
#define PART_TYPE_BBT                           0xFF
1 ingob 167
 
168
 
41 ingob 169
/*
170
________________________________________________________________________________________________________________________________________
88 killagreg 171
 
172
        Structure of the MasterBootRecord
41 ingob 173
________________________________________________________________________________________________________________________________________
1 ingob 174
 
41 ingob 175
        Master Boot Record is 512 bytes long
176
        The Master Boot Record is the same for pretty much all Operating Systems.
177
        It is located on the first Sector of the Hard Drive, at Cylinder 0, Head 0, Sector 1
178
*/
179
typedef struct
180
{
88 killagreg 181
        u8                              ExecutableCode[446];    // 446 bytes for machine start code
182
        PartitionEntry_t        PartitionEntry1;                // 16 bytes for partition entry 1
183
        PartitionEntry_t        PartitionEntry2;                // 16 bytes for partition entry 2
184
        PartitionEntry_t        PartitionEntry3;                // 16 bytes for partition entry 3
185
        PartitionEntry_t        PartitionEntry4;                // 16 bytes for partition entry 4
186
        u16                                     ExecutableMarker;               // BIOS-Signature (0x55 0xAA)
187
} __attribute__((packed)) MBR_Entry_t;
1 ingob 188
 
189
 
41 ingob 190
/*
191
________________________________________________________________________________________________________________________________________
88 killagreg 192
 
193
        Structure of the VolumeBootRecord
41 ingob 194
________________________________________________________________________________________________________________________________________
24 StephanB 195
 
41 ingob 196
        The Volume Boot Record is 512 bytes long
197
        This information is located in the first sector of every partition.
198
*/
199
typedef struct
200
{
201
        u8  JumpCode[3];                        // Jump Code + NOP
88 killagreg 202
        s8  OEMName[8];                         // OEM Name
41 ingob 203
        u16 BytesPerSector;                     // Bytes Per Sector
204
        u8  SectorsPerCluster;          // Sectors Per Cluster
205
        u16 ReservedSectors;            // Reserved Sectors
206
        u8  NoFATCopies;                        // Number of Copies of FAT
88 killagreg 207
        u16 MaxRootEntries;                     // Maximum Root Directory Entries
41 ingob 208
        u16 NoSectorsInPartSml32MB;     // Number of Sectors in Partition Smaller than 32 MB
209
        u8  MediaDescriptor;            // Media Descriptor (0xF8 for Hard Disks)
210
        u16 SectorsPerFAT;                      // Sectors Per FAT
211
        u16 SectorsPerTrack;            // Sectors Per Track
212
        u16 NoHeads;                            // Number of Heads
213
        u32 NoHiddenSectors;            // Number of Hidden Sectors     in Partition
214
        u32 NoSectors;                          // Number of Sectors in Partition
215
        u16     DriveNo;                                // Logical Drive Number of Partition
216
        u8  ExtendedSig;                        // Extended Signature (0x29)
217
        u32 SerialNo;                           // Serial Number of the Partition
218
        s8  VolumeName[11];                     // Volume Name of the Partititon
219
        s8  FATName[8];                         // FAT Name (FAT16)
88 killagreg 220
        u8  ExecutableCode[446];        // 446 bytes for machine start code
221
        u16 ExecutableMarker;           // Executable Marker (0x55 0xAA)
222
} __attribute__((packed)) VBR_Entry_t;
1 ingob 223
 
224
 
225
 
41 ingob 226
/*
227
________________________________________________________________________________________________________________________________________
228
 
88 killagreg 229
        Structure of an directory entry
41 ingob 230
________________________________________________________________________________________________________________________________________
231
 
232
        Directory entry is 32 bytes.
233
*/
234
typedef struct
1 ingob 235
{
41 ingob 236
        s8      Name[8];                                        // 8 bytes name, padded with spaces.
237
        u8      Extension[3];                           // 3 bytes extension, padded with spaces.
238
        u8      Attribute;                                      // attribute of the directory entry (unused,archive,read-only,system,directory,volume)
211 killagreg 239
        u8  Res1;                                               // should be zero
240
        u8  CreationTime10ms;                   // subsecond resolution of creation time
241
        u16 CreationTime;                               // Time of creation h:m:s
242
        u16 CreationDate;                               // Date of creation Y.M.D
243
        u16 LastAccessDate;             // The date where the file was last accessed
244
        u8      Res2[2];                                    // should be zero
245
        u16 ModTime;                                    // date of last write access
246
        u16 ModDate;                                    // date of last write access to the file or directory.
41 ingob 247
        u16 StartCluster;                               // first cluster of the file or directory.
248
        u32 Size;                                               // size of the file or directory in bytes.
249
}  __attribute__((packed)) DirEntry_t;
1 ingob 250
 
41 ingob 251
#define SLOT_EMPTY              0x00    // slot has never been used
252
#define SLOT_E5                 0x05    // the real value is 0xe5
253
#define SLOT_DELETED            0xE5    // file in this slot deleted
1 ingob 254
 
41 ingob 255
#define ATTR_NONE               0x00    // normal file
256
#define ATTR_READONLY           0x01    // file is readonly
257
#define ATTR_HIDDEN                     0x02    // file is hidden
258
#define ATTR_SYSTEM                     0x04    // file is a system file
259
#define ATTR_VOLUMELABEL        0x08    // entry is a volume label
260
#define ATTR_LONG_FILENAME      0x0F    // this is a long filename entry
261
#define ATTR_SUBDIRECTORY       0x10    // entry is a directory name
262
#define ATTR_ARCHIVE            0x20    // file is new or modified
24 StephanB 263
 
264
 
41 ingob 265
/*
266
________________________________________________________________________________________________________________________________________
88 killagreg 267
 
268
        Structure of an entry within the fileallocationtable.
41 ingob 269
________________________________________________________________________________________________________________________________________
270
*/
271
typedef struct
272
{
273
        u16  NextCluster;                               // the next cluster of the file.
274
} __attribute__((packed)) Fat16Entry_t;
1 ingob 275
 
41 ingob 276
// secial fat entries
277
#define FAT16_CLUSTER_FREE                      0x0000
278
#define FAT16_CLUSTER_RESERVED          0x0001
279
#define FAT16_CLUSTER_USED_MIN          0x0002
280
#define FAT16_CLUSTER_USED_MAX          0xFFEF
281
#define FAT16_CLUSTER_ROOTDIR_MIN       0xFFF0
282
#define FAT16_CLUSTER_ROOTDIR_MAX       0xFFF6
283
#define FAT16_CLUSTER_BAD                       0xFFF7
284
#define FAT16_CLUSTER_LAST_MIN          0xFFF8
285
#define FAT16_CLUSTER_LAST_MAX          0xFFFF
286
 
88 killagreg 287
/*****************************************************************************************************************************************/
41 ingob 288
/*                                                                                                                                                                                                                                                                               */
289
/*      Global variables needed for read- or write-acces to the FAT16- filesystem.                                                                                                                       */
290
/*                                                                                                                                                                                                                                                                               */
291
/*****************************************************************************************************************************************/
292
 
293
#define MBR_SECTOR                                      0x00    // the masterboot record is located in sector 0.
294
#define DIRENTRY_SIZE                           32              //bytes
295
#define DIRENTRIES_PER_SECTOR           BYTES_PER_SECTOR/DIRENTRY_SIZE
296
#define FAT16_BYTES                                     2
297
#define FAT16_ENTRIES_PER_SECTOR        BYTES_PER_SECTOR/FAT16_BYTES
298
 
211 killagreg 299
#define SECTOR_UNDEFINED        0x00000000L
300
#define CLUSTER_UNDEFINED       0x0000
301
 
88 killagreg 302
#define FSTATE_UNUSED   0
41 ingob 303
#define FSTATE_USED             1
304
 
305
typedef struct
1 ingob 306
{
41 ingob 307
        u8      IsValid;                                // 0 means invalid, else valid
308
        u8      SectorsPerCluster;              // how many sectors does a cluster contain?
309
        u8      FatCopies;                              // Numbers of copies of the FAT
310
        u16     MaxRootEntries;                 // Possible number of entries in the root directory.
311
        u16     SectorsPerFat;                  // how many sectors does a fat16 contain?
312
        u32 FirstFatSector;                     // sector of the start of the fat
313
        u32 FirstRootDirSector;         // sector of the rootdirectory
314
        u32 FirstDataSector;            // sector of the first cluster containing data (cluster2).
315
        u32 LastDataSector;                     // the last data sector of the partition
379 holgerb 316
        u8  VolumeLabel[12];        // the volume label
317
        u32     CurrentWorkingDirectory;// A pointer to the directory we are actual using 
318
        s8      PathToCwd[256];                 // a string containing the complete path to the current working directory                               
319
}   __attribute__((packed)) Partition_t;
1 ingob 320
 
379 holgerb 321
Partition_t     Partition;              // Structure holds partition information
1 ingob 322
 
41 ingob 323
File_t FilePointer[FILE_MAX_OPEN];      // Allocate Memmoryspace for each filepointer used.
1 ingob 324
 
41 ingob 325
 
379 holgerb 326
 
327
 
41 ingob 328
/****************************************************************************************************************************************/
211 killagreg 329
/*      Function:               FileDate(DateTime_t *);                                                                                                                                                                                         */
41 ingob 330
/*                                                                                                                                                                                                                                                                              */
211 killagreg 331
/*      Description:    This function calculates the DOS date from a pointer to a time structure.                                                                                       */
41 ingob 332
/*                                                                                                                                                                                                                                                                              */
211 killagreg 333
/*      Returnvalue:    Returns the DOS date.                                                                                                                                                                                           */
41 ingob 334
/****************************************************************************************************************************************/
211 killagreg 335
u16 FileDate(DateTime_t * pTimeStruct)
336
{
337
        u16 date = 0;
338
        if(pTimeStruct == NULL)   return date;
339
        if(!(pTimeStruct->Valid)) return date;
41 ingob 340
 
211 killagreg 341
        date |= (0x007F & (u16)(pTimeStruct->Year - 1980))<<9; // set year
342
        date |= (0x000F & (u16)(pTimeStruct->Month))<<5; // set month
343
        date |= (0x001F & (u16)(pTimeStruct->Day));
344
        return date;
345
}
346
 
347
/****************************************************************************************************************************************/
348
/*      Function:               FileTime(DateTime_t *);                                                                                                                                                                                         */
349
/*                                                                                                                                                                                                                                                                              */
350
/*      Description:    This function calculates the DOS time from a pointer to a time structure.                                                                                       */
351
/*                                                                                                                                                                                                                                                                              */
352
/*      Returnvalue:    Returns the DOS time.                                                                                                                                                                                           */
353
/****************************************************************************************************************************************/
354
 
355
u16 FileTime(DateTime_t * pTimeStruct)
1 ingob 356
{
211 killagreg 357
        u16 time = 0;
358
        if(pTimeStruct == NULL)   return time;
359
        if(!(pTimeStruct->Valid)) return time;
24 StephanB 360
 
211 killagreg 361
        time |= (0x001F & (u16)(pTimeStruct->Hour))<<11;
362
        time |= (0x003F & (u16)(pTimeStruct->Min))<<5;
363
        time |= (0x001F & (u16)(pTimeStruct->Sec/2));
364
        return time;
1 ingob 365
}
366
 
41 ingob 367
/****************************************************************************************************************************************/
368
/*      Function:               LockFilePointer();                                                                                                                                                                                                      */
369
/*                                                                                                                                                                                                                                                                              */
370
/*      Description:    This function trys to lock a free file pointer.                                                                                                                                         */
371
/*                                                                                                                                                                                                                                                                              */
372
/*      Returnvalue:    Returns the Filepointer on success or 0.                                                                                                                                                        */
373
/****************************************************************************************************************************************/
374
File_t * LockFilePointer(void)
1 ingob 375
{
41 ingob 376
        u8 i;
377
        File_t * File = 0;
378
        for(i = 0; i < FILE_MAX_OPEN; i++)
1 ingob 379
        {
88 killagreg 380
                if(FilePointer[i].State == FSTATE_UNUSED)               // found an unused one
1 ingob 381
                {
88 killagreg 382
                        File = &FilePointer[i];                                         // set pointer to that entry
41 ingob 383
                        FilePointer[i].State = FSTATE_USED;                     // mark it as used
384
                        break;
1 ingob 385
                }
41 ingob 386
        }
387
        return(File);
1 ingob 388
}
389
 
41 ingob 390
/****************************************************************************************************************************************/
391
/*      Function:               UnlockFilePointer(file_t *);                                                                                                                                                                            */
392
/*                                                                                                                                                                                                                                                                              */
393
/*      Description:    This function trys to unlock a file pointer.                                                                                                                                            */
394
/*                                                                                                                                                                                                                                                                              */
395
/*      Returnvalue:    Returns 1 if file pointer was freed else 0.                                                                                                                                                     */
396
/****************************************************************************************************************************************/
397
u8 UnlockFilePointer(File_t * file)
1 ingob 398
{
41 ingob 399
        u8 cnt;
400
        if(file == NULL) return(0);
401
        for(cnt = 0; cnt < FILE_MAX_OPEN; cnt++)
1 ingob 402
        {
41 ingob 403
                if(&FilePointer[cnt] == file)                                           // filepointer to be freed found?
1 ingob 404
                {
88 killagreg 405
                        file->State = FSTATE_UNUSED;
211 killagreg 406
                        file->FirstSectorOfFirstCluster = SECTOR_UNDEFINED;                     // Sectorpointer to the first sector of the first datacluster of the file.
407
                        file->FirstSectorOfCurrCluster  = SECTOR_UNDEFINED;                     // Pointer to the cluster which is edited at the moment.
41 ingob 408
                        file->SectorOfCurrCluster               = 0;                    // The sector which is edited at the moment (cluster_pointer + sector_index).
409
                        file->ByteOfCurrSector                  = 0;                    // The bytelocation within the current sector (cluster_pointer + sector_index + byte_index).
410
                        file->Mode                                              = 0;                    // mode of fileoperation (read,write)
411
                        file->Size                                              = 0;                    // the size of the opend file in bytes.
412
                        file->Position                                  = 0;                    // pointer to a character within the file 0 < fileposition < filesize
211 killagreg 413
                        file->SectorInCache                     = SECTOR_UNDEFINED;                     // the last sector read, wich is still in the sectorbuffer.
414
                        file->DirectorySector                   = SECTOR_UNDEFINED;                     // the sectorposition where the directoryentry has been made.
41 ingob 415
                        file->DirectoryIndex                    = 0;                    // the index to the directoryentry within the specified sector.
416
                        file->Attribute                                 = 0;                    // the attribute of the file opened.
88 killagreg 417
                        file = NULL;
41 ingob 418
                        return(1);
1 ingob 419
                }
41 ingob 420
        }
421
        return(0);
422
}
1 ingob 423
 
41 ingob 424
/****************************************************************************************************************************************/
425
/*      Function:               SeperateDirName(s8*, s8*);                                                                                                                                                                              */
426
/*                                                                                                                                                                                                                                                                              */
427
/*      Description:    This function seperates the first dirname from filepath and brings them                                                                                         */
428
/*                                      into the needed format ('test.txt' -> 'TEST    TXT')                                                                                                                            */
210 killagreg 429
/*                                      The subpath is the pointer to the remaining substring of the filepath                                                                                           */
41 ingob 430
/*                                                                                                                                                                                                                                                                              */
431
/*      Returnvalue:    Return NULL on error or pointer to subpath                                                                                                                                                                                                      */
432
/****************************************************************************************************************************************/
433
s8* SeperateDirName(const s8 *filepath, s8 *dirname)
434
{
435
        s8* subpath = NULL;
436
        u8 readpointer  = 0;
437
        u8 writepointer = 0;
1 ingob 438
 
88 killagreg 439
        // search subpath from beginning of filepath
41 ingob 440
        subpath = NULL;
441
        readpointer     = 0;
442
        if(filepath[0] == '/') readpointer = 1; // ignore first '/'
368 holgerb 443
        while(subpath == NULL)  // search the filepath until a subpath was found.
1 ingob 444
        {
88 killagreg 445
                if(((filepath[readpointer] == 0) || (filepath[readpointer] == '/')))    // if '/' found or end of filepath reached
446
                {
41 ingob 447
                        subpath = (s8*)&filepath[readpointer];                          // store the position of the first "/" found after the beginning of the filenpath
448
                }
449
                readpointer++;
450
        }
1 ingob 451
 
41 ingob 452
        // clear dirname with spaces
453
        dirname[11] = 0; // terminate dirname
454
        for(writepointer = 0; writepointer < 11; writepointer++) dirname[writepointer] = ' ';
379 holgerb 455
 
456
        // handle the special dirnames "." and ".." seperately
457
        readpointer = 0;
458
        if(filepath[0] == '/') readpointer++;
459
        // if we are trying to enter directories "." or ".." 
460
        if(filepath[readpointer] == '.')
461
        {
462
                // directory '.'
463
                if(filepath[readpointer+1] == 0)
464
                {
465
                        dirname[0] = '.';
466
                        return((s8*)&filepath[readpointer]);
467
                }
468
                // directory '..'               
469
                if((filepath[readpointer+1] == '.') &&  (filepath[readpointer+2] == 0))
470
                {
471
                        dirname[0] = '.';
472
                        dirname[1] = '.';
473
                        return((s8*)&filepath[readpointer]);
474
                }
475
        }
476
 
41 ingob 477
        writepointer = 0;
478
        // start seperating the dirname from the filepath.
479
        readpointer = 0;
480
        if(filepath[0] == '/') readpointer = 1; // ignore first '/'
368 holgerb 481
        while( &filepath[readpointer] < subpath)
1 ingob 482
        {
41 ingob 483
                if(writepointer >= 11) return(NULL);            // dirname to long
484
                if(filepath[readpointer] == '.')                        // seperating dirname and extension.
1 ingob 485
                {
41 ingob 486
                        if(writepointer <= 8)
1 ingob 487
                        {
41 ingob 488
                                readpointer++;                                          // next character in filename
489
                                writepointer = 8;                                       // jump to start of extension
1 ingob 490
                        }
88 killagreg 491
                        else return(NULL);                                              // dirbasename to long
41 ingob 492
                }
493
                else
494
                {
495
                        if((0x60 < filepath[readpointer]) && (filepath[readpointer] < 0x7B))
496
                        {
497
                                dirname[writepointer] = (filepath[readpointer] - 0x20);                                 // all characters must be upper case.
498
                        }
1 ingob 499
                        else
500
                        {
41 ingob 501
                                dirname[writepointer] = filepath[readpointer];
88 killagreg 502
                        }
41 ingob 503
                        readpointer++;
504
                        writepointer++;
1 ingob 505
                }
41 ingob 506
        }
88 killagreg 507
        return(subpath);
1 ingob 508
}
509
 
510
 
41 ingob 511
/**************************************************************************************************************************************+*/
512
/*      Function:       Fat16ClusterToSector( u16 cluster);                                                                                                                                                                             */
513
/*                                                                                                                                                                                                                                                                              */
514
/*      Description:    This function converts a cluster number given by the fat to the corresponding                                                                           */
515
/*                                      sector that points to the start of the data area that is represented by the cluster number.                                                     */
516
/*                                                                                                                                                                                                                                                                              */
517
/*      Returnvalue: The sector number with the data area of the given cluster                                                                                                                          */
518
/****************************************************************************************************************************************/
519
u32     Fat16ClusterToSector(u16 cluster)
520
{
211 killagreg 521
        if(!Partition.IsValid) return SECTOR_UNDEFINED;
218 killagreg 522
        if ((cluster < 2) || (cluster == CLUSTER_UNDEFINED))
211 killagreg 523
        {
524
                return SECTOR_UNDEFINED;
525
        }
526
        else
527
        {
528
                return ( (cluster - 2) * Partition.SectorsPerCluster) + Partition.FirstDataSector; // the first data sector     is represented by the 2nd cluster
529
        }
41 ingob 530
}
531
 
532
/****************************************************************************************************************************************/
533
/*      Function:       SectorToFat16Cluster( u32 sector);                                                                                                                                                                              */
534
/*                                                                                                                                                                                                                                                                              */
535
/*      Description:    This function converts a given sector number given to the corresponding                                                                                         */
536
/*                                      cluster number in the fat that represents this data area.                                                                                                                       */
537
/*                                                                                                                                                                                                                                                                              */
538
/*      Returnvalue: The cluster number representing the data area of the sector.                                                                                                                       */
539
/****************************************************************************************************************************************/
540
u16     SectorToFat16Cluster(u32 sector)
541
{
211 killagreg 542
        if(!Partition.IsValid) return CLUSTER_UNDEFINED;
543
        if((sector == SECTOR_UNDEFINED) || (sector < Partition.FirstDataSector)) return CLUSTER_UNDEFINED;
544
        else return ((u16)((sector - Partition.FirstDataSector) / Partition.SectorsPerCluster) + 2);
41 ingob 545
}
546
 
547
 
548
/****************************************************************************************************************************************/
210 killagreg 549
/*      Function:       Fat16_IsValid(void);                                                                                                                                                                                                    */
90 killagreg 550
/*                                                                                                                                                                                                                                                                              */
210 killagreg 551
/*      Description:    This function return the Fat 16 filesystem state                                                                                                                                        */
90 killagreg 552
/*                                                                                                                                                                                                                                                                              */
553
/*      Returnvalue: The function returns "1" on success                                                                                                                                                                        */
554
/****************************************************************************************************************************************/
555
u8 Fat16_IsValid(void)
556
{
557
        return(Partition.IsValid);
558
}
559
 
560
/****************************************************************************************************************************************/
41 ingob 561
/*      Function:       Fat16_Deinit(void);                                                                                                                                                                                                             */
562
/*                                                                                                                                                                                                                                                                              */
563
/*      Description:    This function uninitializes the fat 16 api                                                                                                                                                      */
564
/*                                                                                                                                                                                                                                                                              */
565
/*      Returnvalue: The function returns "0" on success                                                                                                                                                                        */
566
/****************************************************************************************************************************************/
567
u8 Fat16_Deinit(void)
568
{
569
        s16 returnvalue = 0;
570
        u8 cnt;
146 killagreg 571
 
572
        UART1_PutString("\r\n FAT16 deinit...");
41 ingob 573
        // declare the filepointers as unused.
574
        for(cnt = 0; cnt < FILE_MAX_OPEN; cnt++)
324 killagreg 575
        {      
576
                UnlockFilePointer(&FilePointer[cnt]);
1 ingob 577
        }
324 killagreg 578
        returnvalue = SDC_Deinit();                     // uninitialize interface to sd-card
41 ingob 579
        Partition.IsValid = 0;  // mark data in partition structure as invalid
210 killagreg 580
        Partition.VolumeLabel[0]='\0';
146 killagreg 581
        UART1_PutString("ok");
379 holgerb 582
SD_WatchDog = 0;
41 ingob 583
        return(returnvalue);
1 ingob 584
}
585
 
41 ingob 586
/****************************************************************************************************************************************/
587
/*      Function:               Fat16_Init(void);                                                                                                                                                                                                       */
588
/*                                                                                                                                                                                                                                                                          */
589
/*      Description:    This function reads the Masterbootrecord and finds the position of the Volumebootrecord, the FAT and the Rootdir    */
590
/*                                      and stores the information in global variables.                                                                                                                                     */
591
/*                                                                                                                                                                                                                                                                          */
592
/*      Returnvalue:    The function returns "0" if the filesystem is initialized.                                                                                                                      */
593
/****************************************************************************************************************************************/
594
u8 Fat16_Init(void)
88 killagreg 595
{
41 ingob 596
    u8  cnt     = 0;
597
        u32     partitionfirstsector;
88 killagreg 598
        VBR_Entry_t *VBR;
41 ingob 599
        MBR_Entry_t *MBR;
600
        File_t *file;
601
        u8 result = 0;
1 ingob 602
 
110 killagreg 603
        UART1_PutString("\r\n FAT16 init...");
41 ingob 604
        Partition.IsValid = 0;
605
        // declare the filepointers as unused.
606
        for(cnt = 0; cnt < FILE_MAX_OPEN; cnt++)
1 ingob 607
        {
211 killagreg 608
                UnlockFilePointer(&FilePointer[cnt]);
1 ingob 609
        }
41 ingob 610
        // set current file pinter to first position in list
88 killagreg 611
        file = &FilePointer[0];
612
 
211 killagreg 613
        // try to initialize the sd-card.
88 killagreg 614
        if(SD_SUCCESS != SDC_Init())
615
        {
110 killagreg 616
                UART1_PutString("SD-Card could not be initialized.");
41 ingob 617
                result = 1;
88 killagreg 618
                goto end;
41 ingob 619
        }
1 ingob 620
 
41 ingob 621
        // SD-Card is initialized successfully
622
        if(SD_SUCCESS != SDC_GetSector((u32)MBR_SECTOR,file->Cache))    // Read the MasterBootRecord
1 ingob 623
        {
110 killagreg 624
                UART1_PutString("Error reading the MBR.");
41 ingob 625
                result = 2;
88 killagreg 626
                goto end;
1 ingob 627
        }
41 ingob 628
        MBR = (MBR_Entry_t *)file->Cache;                                               // Enter the MBR using the structure MBR_Entry_t.
88 killagreg 629
        if((MBR->PartitionEntry1.Type == PART_TYPE_FAT16_ST_32_MB) ||
41 ingob 630
           (MBR->PartitionEntry1.Type == PART_TYPE_FAT16_LT_32_MB) ||
631
           (MBR->PartitionEntry1.Type == PART_TYPE_FAT16LBA))
1 ingob 632
        {
41 ingob 633
                // get sector offset 1st partition
634
                partitionfirstsector = MBR->PartitionEntry1.NoSectorsBeforePartition;
635
                // Start of Partition is the Volume Boot Sector
636
                if(SD_SUCCESS != SDC_GetSector(partitionfirstsector,file->Cache)) // Read the volume boot record
1 ingob 637
                {
110 killagreg 638
                        UART1_PutString("Error reading the VBR.");
41 ingob 639
                        result = 3;
88 killagreg 640
                        goto end;
641
                }
1 ingob 642
        }
41 ingob 643
        else  // maybe the medium has no partition assuming sector 0 is the vbr
644
        {
645
                partitionfirstsector = 0;
646
        }
88 killagreg 647
 
41 ingob 648
        VBR = (VBR_Entry_t *) file->Cache;                                              // Enter the VBR using the structure VBR_Entry_t.
649
        if(VBR->BytesPerSector != BYTES_PER_SECTOR)
650
        {
110 killagreg 651
                UART1_PutString("VBR: Sector size not supported.");
41 ingob 652
                result = 4;
88 killagreg 653
                goto end;
41 ingob 654
        }
655
        Partition.SectorsPerCluster             = VBR->SectorsPerCluster;                       // Number of sectors per cluster. Depends on the memorysize of the sd-card.
656
        Partition.FatCopies                     = VBR->NoFATCopies;                                     // Number of fatcopies.
657
        Partition.MaxRootEntries                = VBR->MaxRootEntries;                          // How many Entries are possible in the rootdirectory (FAT16 allows max. 512 entries).
210 killagreg 658
        Partition.SectorsPerFat                 = VBR->SectorsPerFAT;                           // The number of sectors per FAT                                // copy volume label
659
        Partition.VolumeLabel[0] = '\0';                                                                        // set string terminator
41 ingob 660
 
661
        /* Calculate the sectorpositon of the FAT, the Rootdirectory and the first Datacluster. */
88 killagreg 662
        // Calculate the position of the FileAllocationTable:
41 ingob 663
        // Start + # of Reserved Sectors
88 killagreg 664
        Partition.FirstFatSector        =   (u32)(partitionfirstsector + (u32)(VBR->ReservedSectors));
665
        // Calculate the position of the Rootdirectory:
666
        // Start + # of Reserved Sectors + (# of Sectors Per FAT * # of FAT Copies)
41 ingob 667
        Partition.FirstRootDirSector    =   Partition.FirstFatSector + (u32)((u32)Partition.SectorsPerFat*(u32)Partition.FatCopies);
668
        // Calculate the position of the first datacluster:
88 killagreg 669
        // Start + # of Reserved + (# of Sectors Per FAT * # of FAT Copies) + ((Maximum Root Directory Entries * 32) / Bytes per Sector)
41 ingob 670
        Partition.FirstDataSector       =   Partition.FirstRootDirSector + (u32)(Partition.MaxRootEntries>>4);  // assuming 512 Byte Per Sector
671
        // Calculate the last data sector
672
        if(VBR->NoSectors == 0)
673
        {
110 killagreg 674
                UART1_PutString("VBR: Bad number of sectors.");
41 ingob 675
                result = 5;
88 killagreg 676
                goto end;
41 ingob 677
        }
678
        Partition.LastDataSector = Partition.FirstDataSector + VBR->NoSectors - 1;
679
        // check for FAT16 in VBR of first partition
680
        if(!((VBR->FATName[0]=='F') && (VBR->FATName[1]=='A') && (VBR->FATName[2]=='T') && (VBR->FATName[3]=='1')&&(VBR->FATName[4]=='6')))
681
        {
110 killagreg 682
                UART1_PutString("VBR: Partition ist not FAT16 type.");
41 ingob 683
                result = 6;
684
                goto end;
685
        }
686
        Partition.IsValid = 1; // mark data in partition structure as valid
379 holgerb 687
        Partition.CurrentWorkingDirectory = Partition.FirstRootDirSector;
688
        strcpy(Partition.PathToCwd,"/");       
41 ingob 689
        result = 0;
690
        end:
691
        if(result != 0) Fat16_Deinit();
110 killagreg 692
        else UART1_PutString("ok");
88 killagreg 693
        return(result);
1 ingob 694
}
695
 
696
 
41 ingob 697
 
698
/****************************************************************************************************************************************/
699
/* Function:    ClearCurrCluster(File_t*);                                                                                                                                                                                      */
700
/*                                                                                                                                                                                                                                                                              */
701
/* Description: This function fills the current cluster with 0.                                                                                                                                                 */
702
/*                                                                                                                                                                                                                                                                              */
703
/* Returnvalue: The function returns 1 on success else 0.                                                                                                                                                               */
704
/****************************************************************************************************************************************/
705
u8 ClearCurrCluster(File_t * file)
1 ingob 706
{
41 ingob 707
        u8 retvalue = 1;
708
        u32 i;
88 killagreg 709
 
41 ingob 710
        if((!Partition.IsValid) || (file == NULL)) return(0);
711
 
712
        for(i = 0; i < BYTES_PER_SECTOR; i++) file->Cache[i] = 0; // clear file cache
211 killagreg 713
        if(file->FirstSectorOfCurrCluster == SECTOR_UNDEFINED) return (0); // nothing to do 
41 ingob 714
        for(i = 0; i < Partition.SectorsPerCluster; i++)
1 ingob 715
        {
41 ingob 716
                file->SectorInCache = file->FirstSectorOfCurrCluster + i;
717
                if(SD_SUCCESS != SDC_PutSector(file->SectorInCache, file->Cache))
718
                {
88 killagreg 719
                        Fat16_Deinit();
379 holgerb 720
                        return(0);
41 ingob 721
                }
1 ingob 722
        }
88 killagreg 723
        return(retvalue);
1 ingob 724
}
725
 
41 ingob 726
/*****************************************************************************************************************************************/
727
/* Function:    GetNextCluster(File_t* );                                                                                                                                                                                        */
728
/*                                                                                                                                                                                                                                                                               */
729
/* Description: This function finds the next datacluster of the file specified with File *File.                                                                                  */
730
/*                                                                                                                                                                                                                                                                               */
731
/* Returnvalue: The function returns the next cluster or 0 if the last cluster has already reached.                                                                                                      */
732
/*****************************************************************************************************************************************/
733
u16 GetNextCluster(File_t * file)
1 ingob 734
{
211 killagreg 735
        u16 cluster = CLUSTER_UNDEFINED;
41 ingob 736
        u32 fat_byte_offset, sector, byte;
737
        Fat16Entry_t * fat;
88 killagreg 738
 
41 ingob 739
        if((!Partition.IsValid) || (file == NULL)) return(cluster);
211 killagreg 740
        if(file->FirstSectorOfCurrCluster == SECTOR_UNDEFINED) return(cluster);
41 ingob 741
        // if sector is within the data area
742
        if((Partition.FirstDataSector <= file->FirstSectorOfCurrCluster)&& (file->FirstSectorOfCurrCluster <= Partition.LastDataSector))
1 ingob 743
        {
41 ingob 744
                // determine current file cluster
745
                cluster = SectorToFat16Cluster(file->FirstSectorOfCurrCluster);
746
                // calculate byte offset in the fat for corresponding entry
747
                fat_byte_offset = ((u32)cluster)<<1; // two FAT bytes (16 bits) for every cluster
748
                // calculate the sector that contains the current cluster within the fat
749
                sector = Partition.FirstFatSector + ( fat_byte_offset / BYTES_PER_SECTOR);
750
                // calculate byte offset of the current cluster within that fat sector
751
                byte = fat_byte_offset % BYTES_PER_SECTOR;
752
                // read this sector to the file cache
753
                if(file->SectorInCache != sector)
1 ingob 754
                {
41 ingob 755
                        file->SectorInCache = sector;                                           // update sector stored in buffer
756
                        if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))       // read sector from sd-card
24 StephanB 757
                        {
41 ingob 758
                                Fat16_Deinit();
379 holgerb 759
                                return (CLUSTER_UNDEFINED);
88 killagreg 760
                        }
761
                }
41 ingob 762
                // read the next cluster from cache
763
                fat = (Fat16Entry_t *)(&(file->Cache[byte]));
764
                cluster = fat->NextCluster;
211 killagreg 765
                // if no next cluster exist
41 ingob 766
                if(FAT16_CLUSTER_LAST_MIN <= cluster)
767
                {
211 killagreg 768
                         cluster = CLUSTER_UNDEFINED; // next cluster is undefined
1 ingob 769
                }
24 StephanB 770
                else
771
                {
41 ingob 772
                        file->FirstSectorOfCurrCluster = Fat16ClusterToSector(cluster);
773
                        file->SectorOfCurrCluster = 0;
774
                        file->ByteOfCurrSector = 0;
24 StephanB 775
                }
88 killagreg 776
        }
41 ingob 777
        return(cluster);
1 ingob 778
}
779
 
780
 
379 holgerb 781
 
41 ingob 782
/****************************************************************************************************************************************/
783
/* Function:    FindNextFreeCluster(File_t *);                                                                                                                                                                          */
784
/*                                                                                                                                                                                                                                                                              */
785
/* Description: This function looks in the fat to find the next free cluster                                                                                                                    */
786
/*                                                                                                                                                                                                                                                                              */
787
/* Returnvalue: The function returns the cluster number of the next free cluster found within the fat.                                                                  */
788
/****************************************************************************************************************************************/
789
u16 FindNextFreeCluster(File_t *file)
1 ingob 790
{
41 ingob 791
        u32 fat_sector;                                 // current sector within the fat relative to the first sector of the fat.
792
        u32     curr_sector;                            // current sector
793
        u16     fat_entry;                                      // index to an fatentry within the actual sector (256 fatentries are possible within one sector).
211 killagreg 794
        u16     free_cluster    = CLUSTER_UNDEFINED;    // next free cluster number.
41 ingob 795
        Fat16Entry_t * fat;
88 killagreg 796
 
41 ingob 797
        if((!Partition.IsValid) || (file == NULL)) return(0);
24 StephanB 798
 
41 ingob 799
        // start searching for an empty cluster at the beginning of the fat.
88 killagreg 800
        fat_sector = 0;
801
        do
1 ingob 802
        {
41 ingob 803
                curr_sector = Partition.FirstFatSector + fat_sector;    // calculate sector to read
804
                file->SectorInCache = curr_sector;                                              // upate the sector number of file cache.
805
                if( SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))              // read sector of fat from sd-card.
806
                {
807
                        Fat16_Deinit();
379 holgerb 808
                        return(CLUSTER_UNDEFINED);
41 ingob 809
                }
810
 
811
                fat = (Fat16Entry_t *)file->Cache;                                              // set fat pointer to file cache
812
 
88 killagreg 813
                for(fat_entry = 0; fat_entry < FAT16_ENTRIES_PER_SECTOR; fat_entry++)                                           // look for an free cluster at all entries in this sector of the fat.
41 ingob 814
                {
815
                        if(fat[fat_entry].NextCluster == FAT16_CLUSTER_FREE)            // empty cluster found!!
88 killagreg 816
                        {
817
                                fat[fat_entry].NextCluster = FAT16_CLUSTER_LAST_MAX;    // mark this fat-entry as used
41 ingob 818
                                if(SD_SUCCESS != SDC_PutSector(file->SectorInCache, file->Cache))               // and save the sector at the sd-card.
819
                                {
820
                                        Fat16_Deinit();
379 holgerb 821
                                        return(CLUSTER_UNDEFINED);
41 ingob 822
                                }
88 killagreg 823
                                free_cluster = (u16)(fat_sector * FAT16_ENTRIES_PER_SECTOR + (u32)fat_entry);
41 ingob 824
                                fat_entry = FAT16_ENTRIES_PER_SECTOR;                                   // terminate the search for a free cluster in this sector.
825
                        }
826
                }
827
                fat_sector++;                                                                                                   // continue the search in next fat sector
88 killagreg 828
        // repeat until the end of the fat is  reached and no free cluster has been found so far
368 holgerb 829
        }while((fat_sector < Partition.SectorsPerFat) && (!free_cluster));
41 ingob 830
        return(free_cluster);
1 ingob 831
}
832
 
833
 
41 ingob 834
/****************************************************************************************************************************************************/
835
/* Function:    s16 fseek_(File_t *, s32 *, u8)                                                                                                                                                                                                         */
836
/*                                                                                                                                                                                                                                                                                                      */
837
/* Description: This function sets the pointer of the stream relative to the position                                                                                                                           */
838
/*                              specified by origin (SEEK_SET, SEEK_CUR, SEEK_END)                                                                                                                                                                      */
211 killagreg 839
/* Returnvalue: Is 0 if seek was successful                                                                                                                                                                                                                                                                     */
41 ingob 840
/****************************************************************************************************************************************************/
841
s16 fseek_(File_t *file, s32 offset, s16 origin)
1 ingob 842
{
41 ingob 843
        s32             fposition       = 0;
844
        s16     retvalue        = 1;
88 killagreg 845
 
211 killagreg 846
        if((!Partition.IsValid) || (file == NULL)) return(retvalue);
41 ingob 847
        switch(origin)
848
        {
849
                case SEEK_SET:                          // Fileposition relative to the beginning of the file.
88 killagreg 850
                        fposition = 0;
41 ingob 851
                        break;
852
                case SEEK_END:                          // Fileposition relative to the end of the file.
853
                        fposition = (s32)file->Size;
854
                        break;
855
                case SEEK_CUR:                          // Fileposition relative to the current position of the file.
856
                default:
857
                        fposition = file->Position;
858
                        break;
1 ingob 859
        }
41 ingob 860
 
861
        fposition += offset;
862
 
863
        if((fposition >= 0) && (fposition <= (s32)file->Size))          // is the pointer still within the file?
1 ingob 864
        {
41 ingob 865
                // reset file position to start of the file
866
                file->FirstSectorOfCurrCluster = file->FirstSectorOfFirstCluster;
867
                file->SectorOfCurrCluster       = 0;
868
                file->ByteOfCurrSector          = 0;
869
                file->Position                          = 0;
211 killagreg 870
                if(file->FirstSectorOfCurrCluster == SECTOR_UNDEFINED) return(retvalue);
368 holgerb 871
                while(file->Position < fposition)       // repeat until the current position is less than target
1 ingob 872
                {
41 ingob 873
                        file->Position++;                               // increment file position
88 killagreg 874
                        file->ByteOfCurrSector++;               // next byte in current sector
875
                        if(file->ByteOfCurrSector >= BYTES_PER_SECTOR)
41 ingob 876
                        {
877
                                file->ByteOfCurrSector = 0;                                                                             // reading at the beginning of new sector.
878
                                file->SectorOfCurrCluster++;                                                                    // continue reading in next sector
879
                                if(file->SectorOfCurrCluster >= Partition.SectorsPerCluster)    // if end of cluster is reached, the next datacluster has to be searched in the FAT.
880
                                {
881
                                        if(GetNextCluster(file))                                                                        // Sets the clusterpointer of the file to the next datacluster.
882
                                        {
88 killagreg 883
                                                file->SectorOfCurrCluster = 0;
41 ingob 884
                                        }
885
                                        else // the last cluster was allready reached
886
                                        {
211 killagreg 887
                                                file->SectorOfCurrCluster--;                                                    // jump back to the last sector in the last cluster
41 ingob 888
                                                file->ByteOfCurrSector = BYTES_PER_SECTOR;                              // set ByteOfCurrSector one byte over sector end
889
                                        }
890
                                }
88 killagreg 891
                        }
892
                }
1 ingob 893
        }
88 killagreg 894
        if(file->Position == fposition) retvalue = 0;
1 ingob 895
        return(retvalue);
896
}
897
 
898
 
41 ingob 899
/****************************************************************************************************************************************/
900
/* Function:    u16 DeleteClusterChain(File *file);                                                                                                                                                                             */
901
/*                                                                                                                                                                                                                                                                              */
902
/* Description: This function trances along a cluster chain in the fat and frees all clusters visited.                                                                  */
903
/*                                                                                                                                                                                                                                                                              */
904
/****************************************************************************************************************************************/
905
u8 DeleteClusterChain(u16 StartCluster)
1 ingob 906
{
88 killagreg 907
        u16 cluster;
41 ingob 908
        u32 fat_byte_offset, sector, byte;
909
        Fat16Entry_t * fat;
910
        u8 buffer[BYTES_PER_SECTOR];
911
        u32 sector_in_buffer = 0;
912
        u8 repeat = 0;
913
 
211 killagreg 914
        if(!Partition.IsValid) return(0);
915
        if(StartCluster == CLUSTER_UNDEFINED) return(0);
210 killagreg 916
        cluster = StartCluster; // init chain trace
211 killagreg 917
        // if start cluster is no real cluster
918
    if(FAT16_CLUSTER_LAST_MIN <= cluster) return 1;
41 ingob 919
 
920
        // calculate byte offset in the fat for corresponding entry
921
        fat_byte_offset = ((u32)cluster)<<1; // two FAT bytes (16 bits) for every cluster
922
        // calculate the sector that contains the current cluster within the fat
923
        sector = Partition.FirstFatSector + ( fat_byte_offset / BYTES_PER_SECTOR);
924
        // calculate byte offset of the current cluster within that fat sector
925
        byte = fat_byte_offset % BYTES_PER_SECTOR;
88 killagreg 926
        do
1 ingob 927
        {
41 ingob 928
                if(sector != sector_in_buffer)
1 ingob 929
                {
41 ingob 930
                        // read this sector to buffer
931
                        sector_in_buffer = sector;
932
                        if(SD_SUCCESS != SDC_GetSector(sector_in_buffer, buffer)) return 0;     // read sector from sd-card
88 killagreg 933
                }
41 ingob 934
                // read the next cluster from cache
935
                fat = (Fat16Entry_t *)(&(buffer[byte]));
936
                cluster = fat->NextCluster;
211 killagreg 937
                fat->NextCluster =      FAT16_CLUSTER_FREE; // mark current cluster as free
938
 
939
                if((FAT16_CLUSTER_USED_MIN <= cluster) && (cluster <= FAT16_CLUSTER_USED_MAX) )
940
                {
941
                        repeat = 1;
942
                        // calculate sector byte and byte offset in the fat for the next cluster
943
                        fat_byte_offset = ((u32)cluster)<<1; // two FAT bytes (16 bits) for every cluster
944
                        // calculate the sector that contains the current cluster within the fat
945
                        sector = Partition.FirstFatSector + ( fat_byte_offset / BYTES_PER_SECTOR);
946
                        // calculate byte offset of the current cluster within that fat sector
947
                        byte = fat_byte_offset % BYTES_PER_SECTOR;
948
                }
41 ingob 949
                else repeat = 0;
950
 
951
                // if new sector is not the sector in buffer or the last cluster in the chain was traced
952
                if((sector != sector_in_buffer) || !repeat)
953
                {       // write sector in buffer
210 killagreg 954
                        if(SD_SUCCESS != SDC_PutSector(sector_in_buffer,buffer))
146 killagreg 955
                        {
956
                                Fat16_Deinit();
211 killagreg 957
                                return(0);
146 killagreg 958
                        }
1 ingob 959
                }
41 ingob 960
        }
368 holgerb 961
        while(repeat);
41 ingob 962
 
963
        return 1;
1 ingob 964
}
965
 
966
 
41 ingob 967
/****************************************************************************************************************************************/
968
/* Function:    u16 AppendCluster(File *file);                                                                                                                                                                                  */
969
/*                                                                                                                                                                                                                                                                              */
970
/* Description: This function looks in the fat to find the next free cluster and appends it to the file.                                                                */
971
/*                                                                                                                                                                                                                                                                              */
211 killagreg 972
/* Returnvalue: The function returns the appened cluster number or CLUSTER_UNDEFINED of no cluster was appended.                                                */
41 ingob 973
/****************************************************************************************************************************************/
974
u16 AppendCluster(File_t *file)
1 ingob 975
{
211 killagreg 976
        u16 last_cluster, new_cluster = CLUSTER_UNDEFINED;
41 ingob 977
        u32 fat_byte_offset, sector, byte;
978
        Fat16Entry_t * fat;
88 killagreg 979
 
41 ingob 980
        if((!Partition.IsValid) || (file == NULL)) return(new_cluster);
1 ingob 981
 
41 ingob 982
        new_cluster = FindNextFreeCluster(file);        // the next free cluster found on the disk.
211 killagreg 983
        if(new_cluster != CLUSTER_UNDEFINED)
88 killagreg 984
        {       // A free cluster was found and can be added to the end of the file.
41 ingob 985
                fseek_(file, 0, SEEK_END);                                                                                                      // jump to the end of the file
88 killagreg 986
                last_cluster = SectorToFat16Cluster(file->FirstSectorOfCurrCluster);            // determine current file cluster
211 killagreg 987
                if(last_cluster != CLUSTER_UNDEFINED)
41 ingob 988
                {
211 killagreg 989
                        // update FAT entry of last cluster
990
                        fat_byte_offset = ((u32)last_cluster)<<1;
991
                        sector = Partition.FirstFatSector + ( fat_byte_offset / BYTES_PER_SECTOR);
992
                        byte = fat_byte_offset % BYTES_PER_SECTOR;
993
                        // read the sector containing the last cluster of the file
994
                        if(file->SectorInCache != sector)
41 ingob 995
                        {
211 killagreg 996
                                file->SectorInCache = sector;   // update sector stored in buffer
997
                                if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))       // read sector from sd-card
998
                                {
999
                                        Fat16_Deinit();
1000
                                        return(0);
1001
                                }
1002
                        }
1003
                        fat = (Fat16Entry_t *)(&(file->Cache[byte]));
1004
                        fat->NextCluster = new_cluster;                                                 // append the free cluster to the end of the file in the FAT.
1005
                        if(SD_SUCCESS != SDC_PutSector(file->SectorInCache, file->Cache))               // save the modified sector to the FAT.
1006
                        {
41 ingob 1007
                                Fat16_Deinit();
211 killagreg 1008
                                return(0);
88 killagreg 1009
                        }
1010
                }
211 killagreg 1011
                else // last cluster of the file is undefined
1012
                {   // then the new cluster must be the first one of the file
1013
                    // and its cluster number must be set in the direntry
1014
                        DirEntry_t * dir;
1015
                        file->SectorInCache = file->DirectorySector;                            // update the sector number of file cache.
1016
                        if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))// read in the sector.
1017
                        {
1018
                                Fat16_Deinit();
1019
                                return(CLUSTER_UNDEFINED);
1020
                        }
1021
                        dir = (DirEntry_t *)file->Cache;                                                        // set pointer to directory
1022
                        dir[file->DirectoryIndex].Res1 = 0;
1023
                        dir[file->DirectoryIndex].Res2[0] = 0;
1024
                        dir[file->DirectoryIndex].Res2[1] = 0;
1025
                        dir[file->DirectoryIndex].StartCluster = new_cluster;           // update startcluster 
1026
                    dir[file->DirectoryIndex].ModTime   = FileTime(&SystemTime);// set time
1027
                        dir[file->DirectoryIndex].ModDate       = FileDate(&SystemTime);// and date of modification
1028
                        dir[file->DirectoryIndex].LastAccessDate = dir[file->DirectoryIndex].ModDate;
1029
                        dir[file->DirectoryIndex].Size          = 0;
1030
                        // write sector containing the direntry
1031
                        if(SD_SUCCESS != SDC_PutSector(file->SectorInCache, file->Cache))
1032
                        {
1033
                                Fat16_Deinit();
1034
                                return(CLUSTER_UNDEFINED);
1035
                        }
1036
                        // update file info     
1037
                        file->FirstSectorOfFirstCluster = Fat16ClusterToSector(new_cluster);
1038
                        file->Size = 0;
1039
                        file->Position = 0;
41 ingob 1040
                }
211 killagreg 1041
                // update file pointes
41 ingob 1042
                file->FirstSectorOfCurrCluster = Fat16ClusterToSector(new_cluster);
1043
                file->SectorOfCurrCluster = 0;
1044
                file->ByteOfCurrSector = 0;
1045
        }
1046
        return(new_cluster);
1 ingob 1047
}
1048
 
41 ingob 1049
/****************************************************************************************************************************************************/
1050
/* Function:    DirectoryEntryExist(s8 *, u8, u8, File_t *)                                                                                                                                                                                     */
1051
/*                                                                                                                                                                                                                                                                                                      */
1052
/* Description: This function searches all possible dir entries until the file or directory is found or the end of the directory is reached                     */
1053
/*                                                                                                                                                                                                                                                                                                      */
1054
/* Returnvalue: This function returns 1 if the directory entry specified was found.                                                                                                                                     */
1055
/****************************************************************************************************************************************************/
1056
u8 DirectoryEntryExist(s8 *dirname, u8 attribfilter, u8 attribmask, File_t *file)
1057
{
1058
        u32             dir_sector, max_dir_sector, curr_sector;
1059
        u16     dir_entry = 0;
24 StephanB 1060
 
41 ingob 1061
        u16     end_of_directory_not_reached = 0;
1062
        u8              i = 0;
1063
        u8      direntry_exist = 0;
1064
        DirEntry_t * dir;
24 StephanB 1065
 
41 ingob 1066
        // if incomming pointers are useless return immediatly
88 killagreg 1067
        if((!Partition.IsValid) || (file == NULL) || (dirname == NULL)) return(direntry_exist);
41 ingob 1068
 
88 killagreg 1069
        // dir entries can be searched only in filesclusters that have
1070
        // a corresponding dir entry with adir-flag set in its attribute
41 ingob 1071
        // or direct within the root directory area
211 killagreg 1072
        file->FirstSectorOfFirstCluster = SECTOR_UNDEFINED;
41 ingob 1073
        // no current directory exist therefore assume searching in the root
211 killagreg 1074
        if(file->DirectorySector == SECTOR_UNDEFINED)
24 StephanB 1075
        {
41 ingob 1076
                max_dir_sector = (Partition.MaxRootEntries * DIRENTRY_SIZE)/BYTES_PER_SECTOR;
1077
                file->FirstSectorOfFirstCluster = Partition.FirstRootDirSector;
1078
        }
1079
        // within the root directory area we can read sectors sequentially until the end of this area
1080
        else if((Partition.FirstRootDirSector <= file->DirectorySector) && (file->DirectorySector < Partition.FirstDataSector))
1081
        {
1082
                max_dir_sector = (Partition.MaxRootEntries * DIRENTRY_SIZE)/BYTES_PER_SECTOR;
1083
        }
88 killagreg 1084
        // within the data clusters we can read sectors sequentially only within the cluster
41 ingob 1085
        else if((Partition.FirstDataSector <= file->DirectorySector) && (file->DirectorySector <= Partition.LastDataSector))
1086
        {
1087
                max_dir_sector = Partition.SectorsPerCluster;                           // limit max secters before next cluster
1088
        }
1089
        else return (direntry_exist); // bad sector range for directory sector of the file
1090
        // if search area is not defined yet
211 killagreg 1091
        if(file->FirstSectorOfFirstCluster == SECTOR_UNDEFINED)
41 ingob 1092
        {
1093
                // check if the directory entry of current file is existent and has the dir-flag set
1094
                file->SectorInCache = file->DirectorySector;                            // update the sector number of file cache.
1095
                if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))// read in the sector.
24 StephanB 1096
                {
41 ingob 1097
                        Fat16_Deinit();
379 holgerb 1098
                        return(0);
24 StephanB 1099
                }
41 ingob 1100
                dir = (DirEntry_t *)file->Cache;                                                        // set pointer to directory
211 killagreg 1101
                switch((u8)dir[file->DirectoryIndex].Name[0])                           // check if current directory exist
24 StephanB 1102
                {
41 ingob 1103
                        case SLOT_EMPTY:
1104
                        case SLOT_DELETED:
1105
                                // the directrory pointer of this file points to a deleted or not existen directory
1106
                                // therefore no file or subdirectory can be created
1107
                                return (direntry_exist);
1108
                                break;
88 killagreg 1109
                        default:        // and is a real directory
41 ingob 1110
                                if((dir[file->DirectoryIndex].Attribute & ATTR_SUBDIRECTORY) != ATTR_SUBDIRECTORY)
1111
                                {       // current file is not a directory therefore no file or subdirectory can be created here
1112
                                        return (direntry_exist);
1113
                                }
1114
                                break;
24 StephanB 1115
                }
41 ingob 1116
                file->FirstSectorOfFirstCluster = Fat16ClusterToSector(dir[file->DirectoryIndex].StartCluster);
24 StephanB 1117
        }
1118
 
41 ingob 1119
        // update current file data area position to start of first cluster
88 killagreg 1120
        file->FirstSectorOfCurrCluster  = file->FirstSectorOfFirstCluster;
1121
        file->SectorOfCurrCluster               = 0;
41 ingob 1122
        file->ByteOfCurrSector                  = 0;
24 StephanB 1123
 
41 ingob 1124
        do // loop over all data clusters of the current directory entry
88 killagreg 1125
        {
379 holgerb 1126
                dir_sector = 0;
41 ingob 1127
                do // loop over all sectors of a cluster or all sectors of the root directory
88 killagreg 1128
                {
41 ingob 1129
                        curr_sector = file->FirstSectorOfCurrCluster + dir_sector;      // calculate sector number
1130
                        file->SectorInCache = curr_sector;                                                      // upate the sector number of file cache.
1131
                        if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))// read the sector
1132
                        {
1133
                                Fat16_Deinit();
379 holgerb 1134
                                return(0);
41 ingob 1135
                        }
1136
                        dir = (DirEntry_t *)file->Cache;                                                        // set pointer to directory
1137
                        // search all directory entries within that sector
1138
                        for(dir_entry = 0; dir_entry < DIRENTRIES_PER_SECTOR; dir_entry++)
1139
                        {   // check for existing dir entry
1140
                                switch((u8)dir[dir_entry].Name[0])
1141
                                {
1142
                                        case SLOT_EMPTY:
1143
                                        case SLOT_DELETED:
1144
                                                // ignore empty or deleted dir entries
1145
                                                break;
1146
                                        default:
1147
                                                // if existing check attributes before names are compared will safe performance
1148
                                                if ((dir[dir_entry].Attribute & attribmask) != attribfilter) break; // attribute must match
1149
                                                // then compare the name to the giveb dirname (first 11 characters include 8 chars of basename and 3 chars extension.)
1150
                                                i = 0;
1151
                                                while((i < 11) && (dir[dir_entry].Name[i] == dirname[i])) i++;
1152
                                                if (i < 10) break; // names does not match
1153
                                                // if dirname and attribute have matched
1154
                                                file->Attribute = dir[dir_entry].Attribute; // store attribute of found dir entry
88 killagreg 1155
                                                file->FirstSectorOfFirstCluster = Fat16ClusterToSector(dir[dir_entry].StartCluster); // set sector of first data cluster
41 ingob 1156
                                                file->FirstSectorOfCurrCluster = file->FirstSectorOfFirstCluster;
1157
                                                file->SectorOfCurrCluster = 0;
1158
                                                file->ByteOfCurrSector = 0;
1159
                                                file->DirectorySector = curr_sector; // current sector
1160
                                                file->DirectoryIndex  = dir_entry; // current direntry in current sector
88 killagreg 1161
                                                file->Size = dir[dir_entry].Size;
1162
                                                direntry_exist = 1; // mark as found
1163
                                                dir_entry = DIRENTRIES_PER_SECTOR;      // stop for-loop
41 ingob 1164
                                } // end of first byte of name check
1165
                        }
1166
                        dir_sector++; // search next sector
1167
                // stop if we reached the end of the cluster or the end of the root dir
368 holgerb 1168
                }while((dir_sector < max_dir_sector) && (!direntry_exist));
1 ingob 1169
 
41 ingob 1170
                // if we are seaching in the data area and the file not found in this cluster so take next cluster.
88 killagreg 1171
                if(!direntry_exist && ( Partition.FirstDataSector <= file->FirstSectorOfCurrCluster))
41 ingob 1172
                {
1173
                        end_of_directory_not_reached = GetNextCluster(file);  // updates File->FirstSectorOfCurrCluster
1174
                }
368 holgerb 1175
        }while((end_of_directory_not_reached) && (!direntry_exist)); // repeat until a next cluster exist an no
41 ingob 1176
        return(direntry_exist);
1 ingob 1177
}
1178
 
1179
 
41 ingob 1180
/****************************************************************************************************************************************/
1181
/*      Function:               CreateDirectoryEntry(s8 *, u16, File_t *)                                                                                                                                                       */
1182
/*                                                                                                                                                                                                                                                                              */
1183
/*      Description:    This function looks for the next free position in the directory and creates an entry.                                                           */
1184
/*                                      The type of an directory entry is specified by the file attribute.                                                                                                      */
1185
/*                                                                                                                                                                                                                                                                              */
1186
/*      Returnvalue:    Return 0 on error                                                                                                                                                                                                       */
1187
/****************************************************************************************************************************************/
1188
u8 CreateDirectoryEntry(s8 *dirname, u8 attrib, File_t *file)
1 ingob 1189
{
41 ingob 1190
        u32 dir_sector, max_dir_sector, curr_sector;
1191
        u16 dir_entry   = 0;
1192
        u16 subdircluster, dircluster = 0;
1193
        u16 end_of_directory_not_reached = 0;
1194
        u8      i                       = 0;
88 killagreg 1195
        u8      retvalue        = 0;
41 ingob 1196
        DirEntry_t *dir;
1197
 
1198
        if((!Partition.IsValid) || (file == NULL) || (dirname == NULL)) return (retvalue);
1199
        // It is not checked here that the dir entry that should be created is already existent!
88 killagreg 1200
 
1201
        // Dir entries can be created only in file-clusters that have
41 ingob 1202
        // the dir-flag set in its attribute or within the root directory
88 killagreg 1203
 
211 killagreg 1204
        file->FirstSectorOfFirstCluster = SECTOR_UNDEFINED;
41 ingob 1205
        // no current directory exist therefore assume creating in the root
211 killagreg 1206
        if(file->DirectorySector == SECTOR_UNDEFINED)
24 StephanB 1207
        {
41 ingob 1208
                max_dir_sector = (Partition.MaxRootEntries * DIRENTRY_SIZE)/BYTES_PER_SECTOR;
1209
                dircluster = 0;
1210
                file->FirstSectorOfFirstCluster = Partition.FirstRootDirSector;
1211
        }
1212
        // within the root directory area we can read sectors sequentially until the end of this area
1213
        else if((Partition.FirstRootDirSector <= file->DirectorySector) && (file->DirectorySector < Partition.FirstDataSector))
1214
        {
1215
                max_dir_sector = (Partition.MaxRootEntries * DIRENTRY_SIZE)/BYTES_PER_SECTOR;
1216
        }
88 killagreg 1217
        // within the data clusters we can read sectors sequentially only within the cluster
41 ingob 1218
        else if((Partition.FirstDataSector <= file->DirectorySector) && (file->DirectorySector <= Partition.LastDataSector))
1219
        {
1220
                max_dir_sector = Partition.SectorsPerCluster;
1221
        }
88 killagreg 1222
        else return (retvalue); // bad sector range for directory sector of the file
41 ingob 1223
        // if search area is not defined yet
211 killagreg 1224
        if(file->FirstSectorOfFirstCluster == SECTOR_UNDEFINED)
41 ingob 1225
        {
1226
            // check if the directory entry of current file is existent and has the dir-flag set
1227
                file->SectorInCache = file->DirectorySector;                            // update the sector number of file cache.
88 killagreg 1228
                if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))// read in the sector.
41 ingob 1229
                {
1230
                        Fat16_Deinit();
379 holgerb 1231
                        return(0);
88 killagreg 1232
                }
41 ingob 1233
                dir = (DirEntry_t *)file->Cache;                                                        // set pointer to directory
218 killagreg 1234
                switch((u8)dir[file->DirectoryIndex].Name[0])                           // check if current directory exist
41 ingob 1235
                {
1236
                        case SLOT_EMPTY:
1237
                        case SLOT_DELETED:
1238
                                return (retvalue);
1239
                                break;
88 killagreg 1240
                        default:        // and is a real directory
41 ingob 1241
                                if((dir[file->DirectoryIndex].Attribute & ATTR_SUBDIRECTORY) != ATTR_SUBDIRECTORY)
1242
                                {       // current file is not a directory therefore no file or subdirectory can be created here
1243
                                        return (retvalue);
1244
                                }
1245
                                break;
1246
                }
1247
                dircluster = dir[file->DirectoryIndex].StartCluster;
88 killagreg 1248
                file->FirstSectorOfFirstCluster = Fat16ClusterToSector(dircluster);
41 ingob 1249
        }
88 killagreg 1250
 
218 killagreg 1251
        // if the new direntry is a subdirectory
1252
        if((attrib & ATTR_SUBDIRECTORY) == ATTR_SUBDIRECTORY)
1253
        {       // get a free clutser for its content
1254
                subdircluster = FindNextFreeCluster(file);      // get the next free cluster on the disk and mark it as used.
1255
        }
1256
        else // a normal file
1257
        {       // has no data cluster after creation
1258
                subdircluster = CLUSTER_UNDEFINED;
1259
        }
1260
 
211 killagreg 1261
        file->FirstSectorOfCurrCluster  = file->FirstSectorOfFirstCluster;
1262
        file->SectorOfCurrCluster               = 0;
1263
        do // loop over all clusters of current directory
41 ingob 1264
        {
211 killagreg 1265
                dir_sector = 0; // reset sector counter within a new cluster
1266
                do // loop over all sectors of a cluster or all sectors of the root directory
88 killagreg 1267
                {
211 killagreg 1268
                        curr_sector = file->FirstSectorOfCurrCluster + dir_sector;      // calculate sector number
1269
                        file->SectorInCache = curr_sector;                                                      // upate the sector number of file cache.
1270
                        if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))// read in the sector.
1 ingob 1271
                        {
211 killagreg 1272
                                Fat16_Deinit();
379 holgerb 1273
                                return(0);
211 killagreg 1274
                        }
1275
 
1276
                        dir = (DirEntry_t *)file->Cache;                                                        // set pointer to directory
1277
                        // search all directory entries of a sector
1278
                        for(dir_entry = 0; dir_entry < DIRENTRIES_PER_SECTOR; dir_entry++)
1279
                        {       // check if current direntry is available
1280
                                if(((u8)dir[dir_entry].Name[0] == SLOT_EMPTY) || ((u8)dir[dir_entry].Name[0] == SLOT_DELETED))
1281
                                {       // a free direntry was found
1282
                                        for(i = 0; i < 11; i++) dir[dir_entry].Name[i] = dirname[i];            // Set dir name
1283
                                        dir[dir_entry].Attribute    = attrib;
1284
                                        dir[dir_entry].Res1 = 0;
1285
                                        dir[dir_entry].CreationTime10ms = (u8)(SystemTime.mSec/10);
1286
                                        dir[dir_entry].CreationTime     = FileTime(&SystemTime);
1287
                                        dir[dir_entry].CreationDate     = FileDate(&SystemTime);
1288
                                        dir[dir_entry].LastAccessDate = dir[dir_entry].CreationDate;
1289
                                        dir[dir_entry].Res2[0] = 0;
1290
                                        dir[dir_entry].Res2[1] = 0;
1291
                                        dir[dir_entry].ModTime = dir[dir_entry].CreationTime;
1292
                                        dir[dir_entry].ModDate = dir[dir_entry].CreationDate;
1293
                                        // Set the attribute of the new directoryentry.
1294
                                        dir[dir_entry].StartCluster = subdircluster;                                            // copy the location of the first datacluster to the directoryentry.
1295
                                        dir[dir_entry].Size             = 0;                                                                    // the new createted file has no content yet.
1296
                                        if(SD_SUCCESS != SDC_PutSector(file->SectorInCache, file->Cache))       // write back to card
1297
                                        {
1298
                                                Fat16_Deinit();
379 holgerb 1299
                                                return(0);
211 killagreg 1300
                                        }
218 killagreg 1301
                                        file->FirstSectorOfFirstCluster = Fat16ClusterToSector(subdircluster);  // Calculate absolute sectorposition of first datacluster.
211 killagreg 1302
                                        file->FirstSectorOfCurrCluster  = file->FirstSectorOfFirstCluster;      // Start reading the file with the first sector of the first datacluster.
1303
                                        file->SectorOfCurrCluster               = 0;                                                            // reset sector of cureen cluster
1304
                                        file->ByteOfCurrSector                  = 0;                                                            // reset the byte location within the current sector
1305
                                        file->Attribute                                 = attrib;                                               // set file attribute to dir attribute
1306
                                        file->Size                                              = 0;                                                        // new file has no size
1307
                                        file->DirectorySector                   = curr_sector;
1308
                                        file->DirectoryIndex                    = dir_entry;
1309
                                        // prepare subdirectory data cluster
1310
                                        if((attrib & ATTR_SUBDIRECTORY) == ATTR_SUBDIRECTORY)                           // if a new directory was created then initilize the data area
1311
                                        {
1312
                                                ClearCurrCluster(file); // fill cluster with zeros
1313
                                                file->SectorInCache = file->FirstSectorOfFirstCluster;
1314
                                                if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))// read in the sector.
41 ingob 1315
                                                {
211 killagreg 1316
                                                        Fat16_Deinit();
379 holgerb 1317
                                                        return(0);
41 ingob 1318
                                                }
211 killagreg 1319
                                                dir = (DirEntry_t *)file->Cache;
1320
                                                // create direntry "." to current dir
1321
                                                dir[0].Name[0] = 0x2E;
1322
                                                for(i = 1; i < 11; i++) dir[0].Name[i] = ' ';
1323
                                                dir[0].Attribute = ATTR_SUBDIRECTORY;
1324
                                                dir[0].StartCluster = subdircluster;
1325
                                                dir[0].Size = 0;
1326
                                                // create direntry ".." to the upper dir
1327
                                                dir[1].Name[0] = 0x2E;
1328
                                                dir[1].Name[1] = 0x2E;
1329
                                                for(i = 2; i < 11; i++) dir[1].Name[i] = ' ';
1330
                                                dir[1].Attribute = ATTR_SUBDIRECTORY;
1331
                                                dir[1].StartCluster = dircluster;
1332
                                                dir[1].Size = 0;
1333
                                                if(SD_SUCCESS != SDC_PutSector(file->SectorInCache, file->Cache))// read in the sector.
88 killagreg 1334
                                                {
211 killagreg 1335
                                                        Fat16_Deinit();
379 holgerb 1336
                                                        return(0);
211 killagreg 1337
                                                }
1338
                                        }
1339
                                        retvalue = 1;
1340
                                        dir_entry = DIRENTRIES_PER_SECTOR;      // stop for-loop
88 killagreg 1341
                                }
211 killagreg 1342
                        }
1343
                        dir_sector++; // search next sector
1344
                // stop if we reached the end of the cluster or the end of the root dir
368 holgerb 1345
                }while((dir_sector < max_dir_sector) && (!retvalue));
88 killagreg 1346
 
211 killagreg 1347
                // if we are seaching in the data area and the file not found in this cluster so take next cluster.
1348
                if(!retvalue && ( Partition.FirstDataSector <= file->FirstSectorOfCurrCluster))
1349
                {
1350
                        end_of_directory_not_reached = GetNextCluster(file);  // updates File->FirstSectorOfCurrCluster
1351
                }
368 holgerb 1352
        }while((end_of_directory_not_reached) && (!retvalue));
211 killagreg 1353
        // Perhaps we are at the end of the last cluster of a directory file and have no free direntry found.
1354
        // Then we would need to add a cluster to that file and create the new direntry there.
1355
        // This code is not implemented yet, because its occurs only if more that 32*32=1024 direntries are
1356
        // within a subdirectory of root.
1357
 
41 ingob 1358
        return(retvalue);       // return 1 if file has been created otherwise return 0.
1 ingob 1359
}
1360
 
41 ingob 1361
/********************************************************************************************************************************************/
1362
/*      Function:               FileExist(const s8* filename, u8 attribfilter, u8 attribmask, File_t *file);                                                                                    */
1363
/*                                                                                                                                                                                                                                                                                      */
1364
/*      Description:    This function looks for the specified file including its subdirectories beginning                                                                               */
1365
/*                                      in the rootdirectory of the drive. If the file is found the Filepointer properties are                                                                  */
1366
/*                                      updated.                                                                                                                                                                                                                                */
1367
/*                                                                                                                                                                                                                                                                                      */
1368
/*      Returnvalue:    1 if file is found else 0.                                                                                                                                                                                              */
1369
/********************************************************************************************************************************************/
1370
u8 FileExist(const s8* filename, const u8 attribfilter, const u8 attribmask, File_t *file)
1 ingob 1371
{
41 ingob 1372
        s8* path = 0;
1373
        s8* subpath = 0;
1374
        u8 af, am, file_exist = 0;
1375
        s8 dirname[12]; // 8+3 + temination character
1 ingob 1376
 
41 ingob 1377
        // if incomming pointers are useless return immediatly
1378
        if ((filename == NULL) || (file == NULL) || (!Partition.IsValid)) return 0;
1 ingob 1379
 
41 ingob 1380
        // trace along the filepath
1381
        path = (s8*)filename;                                                           // start a the beginning of the filename string
1382
        file->DirectorySector = 0;                                                              // start at RootDirectory with file search
88 killagreg 1383
        file->DirectoryIndex = 0;
379 holgerb 1384
        /* if a path begins with a '/' at index 0 the search starts at the rootdirectory otherwise we will start relative to the cwd */
1385
        if(path[0] != '/')
1386
        {
1387
                /* is the current working directory the rootdirectory? */
1388
                if(Partition.CurrentWorkingDirectory == Partition.FirstRootDirSector) file->DirectorySector = 0;
1389
                /* otherwise we are working in an subdirectory */
1390
                else file->DirectorySector = Partition.CurrentWorkingDirectory;
1391
        }
41 ingob 1392
        // as long as the file was not found and the remaining path is not empty
368 holgerb 1393
        while((*path != 0) && !file_exist)
41 ingob 1394
        {       // separate dirname and subpath from filepath string
1395
                subpath = SeperateDirName(path, dirname);
1396
                if(subpath != NULL)
88 killagreg 1397
                {
1398
                        if(*subpath == 0)
41 ingob 1399
                        {       // empty subpath indicates last element of dir chain
1400
                                af = attribfilter;
1401
                                am = attribmask;
1402
                        }
1403
                        else  // it must be a subdirectory and no volume label
1 ingob 1404
                        {
41 ingob 1405
                                af = ATTR_SUBDIRECTORY;
1406
                                am = ATTR_SUBDIRECTORY|ATTR_VOLUMELABEL;
1407
                        }
1408
                        if(!DirectoryEntryExist(dirname, af, am, file))
1409
                        {
1410
                                return (file_exist); // subdirectory does not exist
1411
                        }
88 killagreg 1412
                        else
1413
                        {
41 ingob 1414
                                if (*subpath == 0)
24 StephanB 1415
                                {
41 ingob 1416
                                        file_exist = 1; // last element of path chain was found with the given attribute filter
24 StephanB 1417
                                }
1 ingob 1418
                        }
1419
                }
41 ingob 1420
                else // error seperating the subpath
1 ingob 1421
                {
41 ingob 1422
                        return file_exist; // bad subdir format
1 ingob 1423
                }
41 ingob 1424
                path = subpath;
1425
                subpath = 0;
1 ingob 1426
        }
41 ingob 1427
        return (file_exist);
1 ingob 1428
}
1429
 
24 StephanB 1430
 
41 ingob 1431
/********************************************************************************************************************************************/
1432
/*      Function:               FileCreate(const s8* filename, u8 attrib, File_t *file);                                                                                                                                */
1433
/*                                                                                                                                                                                                                                                                                      */
1434
/*      Description:    This function looks for the specified file including its subdirectories beginning                                                                               */
1435
/*                                      in the rootdirectory of the partition. If the file is found the Filepointer properties are                                                              */
88 killagreg 1436
/*                                      updated. If file or its subdirectories are not found they will be created                                                                                               */
41 ingob 1437
/*                                                                                                                                                                                                                                                                                      */
1438
/*      Returnvalue:    1 if file was created else 0.                                                                                                                                                                                   */
1439
/********************************************************************************************************************************************/
1440
u8 FileCreate(const s8* filename, const u8 attrib, File_t *file)
1441
{
1442
        s8 *path = 0;
1443
        s8 *subpath = 0;
1444
        u8 af, am, file_created = 0;
1445
        s8 dirname[12];
24 StephanB 1446
 
41 ingob 1447
        // if incomming pointers are useless return immediatly
1448
        if ((filename == NULL) || (file == NULL) || (!Partition.IsValid)) return 0;
1 ingob 1449
 
41 ingob 1450
        // trace along the filepath
1451
        path = (s8*)filename;                                                                   // start a the beginning of the filename string
1452
        file->DirectorySector = 0;                                                              // start at RootDirectory with file search
1453
        file->DirectoryIndex = 0;
1454
        // as long as the file was not created and the remaining file path is not empty
368 holgerb 1455
        while((*path != 0) && !file_created)
41 ingob 1456
        {   // separate dirname and subpath from filepath string
1457
                subpath = SeperateDirName(path, dirname);
1458
                if(subpath != NULL)
24 StephanB 1459
                {
88 killagreg 1460
                        if(*subpath == 0)
41 ingob 1461
                        {       // empty subpath indicates last element of dir chain
1462
                                af = ATTR_NONE;
1463
                                am = ATTR_SUBDIRECTORY|ATTR_VOLUMELABEL;  // any file that is no subdir or volume label
24 StephanB 1464
                        }
41 ingob 1465
                        else  // it must be a subdirectory and no volume label
24 StephanB 1466
                        {
41 ingob 1467
                                af = ATTR_SUBDIRECTORY;
1468
                                am = ATTR_SUBDIRECTORY|ATTR_VOLUMELABEL;
24 StephanB 1469
                        }
41 ingob 1470
                        if(!DirectoryEntryExist(dirname, af, am, file)) // if subdir or file is not existent
1471
                        {  // try to create subdir or file
1472
                                if(*subpath == 0) af = attrib; // if last element in dir chain take the given attribute
1473
                                if(!CreateDirectoryEntry(dirname, af, file))
1474
                                {       // could not be created
88 killagreg 1475
                                        return(file_created);
1476
                                }
41 ingob 1477
                                else if (*subpath == 0) file_created = 1; // last element of path chain was created
24 StephanB 1478
                        }
1479
                }
41 ingob 1480
                else // error seperating the subpath
24 StephanB 1481
                {
41 ingob 1482
                        return file_created; // bad subdir format
24 StephanB 1483
                }
41 ingob 1484
                path = subpath;
1485
                subpath = 0;
1486
        }
1487
        return (file_created);
24 StephanB 1488
}
1 ingob 1489
 
24 StephanB 1490
 
41 ingob 1491
/********************************************************************************************************************************************/
1492
/*      Function:               File_t * fopen_(s8* filename, s8 mode);                                                                                                                                                                 */
1493
/*                                                                                                                                                                                                                                                                                      */
1494
/*      Description:    This function looks for the specified file in the rootdirectory of the drive. If the file is found the number of the    */
1495
/*                                      corrosponding filepointer is returned. Only modes 'r' (reading) and 'a' append are implemented yet.                                             */
1496
/*                                                                                                                                                                                                                                                                                      */
1497
/*      Returnvalue:    The filepointer to the file or 0 if faild.                                                                                                                                                              */
1498
/********************************************************************************************************************************************/
89 killagreg 1499
File_t * fopen_(s8 * const filename, const s8 mode)
88 killagreg 1500
{
41 ingob 1501
        File_t *file    = 0;
379 holgerb 1502
        s8 *cptr;
88 killagreg 1503
 
41 ingob 1504
        if((!Partition.IsValid) || (filename == 0)) return(file);
1505
 
1506
        // Look for an unused filepointer in the file pointer list?
1507
        file = LockFilePointer();
1508
        // if no unused file pointer was found return 0
1509
        if(file == NULL) return(file);
1510
 
1511
        // now we have found a free filepointer and claimed it
1512
        // so let initiate its property values
211 killagreg 1513
        file->FirstSectorOfFirstCluster = SECTOR_UNDEFINED;             // Sectorpointer to the first sector of the first datacluster of the file.
1514
        file->FirstSectorOfCurrCluster  = SECTOR_UNDEFINED;             // Pointer to the cluster which is edited at the moment.
41 ingob 1515
        file->SectorOfCurrCluster               = 0;            // The sector which is edited at the moment (cluster_pointer + sector_index).
1516
        file->ByteOfCurrSector                  = 0;            // The bytelocation within the current sector (cluster_pointer + sector_index + byte_index).
1517
        file->Mode                                              = mode;         // mode of fileoperation (read,write)
1518
        file->Size                                              = 0;            // the size of the opened file in bytes.
1519
        file->Position                                  = 0;            // pointer to a byte within the file 0 < fileposition < filesize
211 killagreg 1520
        file->SectorInCache                             = SECTOR_UNDEFINED;             // the last sector read, wich is still in the sectorbuffer.
1521
        file->DirectorySector                   = SECTOR_UNDEFINED;             // the sectorposition where the directoryentry has been made.
41 ingob 1522
        file->DirectoryIndex                    = 0;            // the index to the directoryentry within the specified sector.
1523
        file->Attribute                                 = 0;            // the attribute of the file opened.
1524
 
379 holgerb 1525
        // bring the path into the correct syntax 
1526
        cptr = filename;
1527
        // search the whole string 
1528
        while(*cptr != 0)
1529
        {
1530
                // replace all '\' by '/'
1531
                if(*cptr == '\\') *cptr = '/';
1532
                cptr++;
1533
        }
41 ingob 1534
        // check if a real file (no directory) to the given filename exist
88 killagreg 1535
        if(FileExist(filename, ATTR_NONE, ATTR_SUBDIRECTORY|ATTR_VOLUMELABEL, file))
41 ingob 1536
        {  // file exist
1537
                switch(mode)  // check mode
1 ingob 1538
                {
41 ingob 1539
                        case 'a':       // if mode is: append to file
1540
                                if((file->Attribute & ATTR_READONLY) == ATTR_READONLY)
1541
                                {       // file is marked as readonly --> do not open this file
1542
                                        fclose_(file);
1543
                                        file = NULL;
1544
                                }
1545
                                else
1546
                                {       // file is not marked as read only --> goto end of file
1547
                                        fseek_(file, 0, SEEK_END);              // point to the end of the file
1548
                                }
1549
                                break;
1550
                        case 'w':       // if mode is: write to file
1551
                                if((file->Attribute & ATTR_READONLY) == ATTR_READONLY)
1552
                                {       // file is marked as readonly --> do not open this file
1553
                                        fclose_(file);
1554
                                        file = NULL;
1555
                                }
1556
                                else
211 killagreg 1557
                                {       // file is not marked as read only
1558
                                        DirEntry_t * dir;
41 ingob 1559
                                        // free all clusters of that file
1560
                                        DeleteClusterChain(SectorToFat16Cluster(file->FirstSectorOfFirstCluster));
211 killagreg 1561
                                        // update directory entry of that file
1562
                                        file->SectorInCache = file->DirectorySector;                            // update the sector number of file cache.
1563
                                        if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))// read in the sector.
1564
                                        {
1565
                                                Fat16_Deinit();
1566
                                                return(NULL);
1567
                                        }
1568
                                        dir = (DirEntry_t *)file->Cache;                                                                // set pointer to directory
1569
                                    dir[file->DirectoryIndex].ModTime   = FileTime(&SystemTime);        // set modification time
1570
                                        dir[file->DirectoryIndex].ModDate       = FileDate(&SystemTime);        // set modification date
1571
                                        dir[file->DirectoryIndex].LastAccessDate = dir[file->DirectoryIndex].ModDate;
1572
                                        dir[file->DirectoryIndex].StartCluster = CLUSTER_UNDEFINED;             // update startcluster 
1573
                                        dir[file->DirectoryIndex].Size          = 0;
1574
                                        // write sector containing the direntry
1575
                                        if(SD_SUCCESS != SDC_PutSector(file->SectorInCache, file->Cache))
1576
                                        {
1577
                                                Fat16_Deinit();
1578
                                                return(NULL);
1579
                                        }
1580
                                        file->FirstSectorOfFirstCluster = SECTOR_UNDEFINED;
41 ingob 1581
                                        file->FirstSectorOfCurrCluster = file->FirstSectorOfFirstCluster;
1582
                                        file->SectorOfCurrCluster = 0;
1583
                                        file->ByteOfCurrSector = 0;
1584
                                        file->Size = 0;
1585
                                        file->Position = 0;
1586
                                        fseek_(file, 0, SEEK_SET);
1587
                                }
1588
                                break;
1589
                        case 'r':       // if mode is: read from file
88 killagreg 1590
                                // goto end of file
41 ingob 1591
                                fseek_(file, 0, SEEK_SET);
1592
                                break;
1593
                        default: // other modes are not supported
1594
                                fclose_(file);
1595
                                file = NULL;
24 StephanB 1596
                        break;
1 ingob 1597
                }
88 killagreg 1598
                return(file);
1 ingob 1599
        }
41 ingob 1600
        else // file does not exist
1601
        {
1602
                switch(mode)  // check mode
1603
                {
1604
                        case 'a':
1605
                        case 'w': // if mode is write or append
1606
                                // try to create the file
1607
                                if(!FileCreate(filename, ATTR_ARCHIVE, file))
1608
                                { // if it could not be created
1609
                                        fclose_(file);
1610
                                        file = NULL;
379 holgerb 1611
                                }
41 ingob 1612
                                break;
1613
                        case 'r': // else opened for 'r'
218 killagreg 1614
                        default:  // if unsupported mode
41 ingob 1615
                                fclose_(file);
1616
                                file = NULL;
88 killagreg 1617
                                break;
41 ingob 1618
                }
88 killagreg 1619
                return(file);
41 ingob 1620
        }
1621
        // we should never come to this point
1622
        fclose_(file);
1623
        file = NULL;
24 StephanB 1624
        return(file);
1625
}
1626
 
41 ingob 1627
/****************************************************************************************************************************************************/
1628
/* Function:    fflush_(File *);                                                                                                                                                                                                                                        */
1629
/*                                                                                                                                                                                                                                                                                                      */
1630
/* Description: This function writes the data already in the buffer but not yet written to the file.                                                                                            */
1631
/*                                                                                                                                                                                                                                                                                                      */
1632
/* Returnvalue: 0 on success EOF on error                                                                                                                                                                                                                       */
1633
/****************************************************************************************************************************************************/
1634
s16     fflush_(File_t *file)
24 StephanB 1635
{
88 killagreg 1636
        DirEntry_t *dir;
1637
 
41 ingob 1638
        if((file == NULL) || (!Partition.IsValid)) return (EOF);
88 killagreg 1639
 
41 ingob 1640
        switch(file->Mode)
24 StephanB 1641
        {
41 ingob 1642
                case 'a':
1643
                case 'w':
88 killagreg 1644
                        if(file->ByteOfCurrSector > 0)                                                                          // has data been added to the file?
41 ingob 1645
                        {
88 killagreg 1646
                                if(SD_SUCCESS != SDC_PutSector(file->SectorInCache, file->Cache))// save the data still in the buffer
41 ingob 1647
                                {
88 killagreg 1648
                                        Fat16_Deinit();
1649
                                        return(EOF);
1650
                                }
41 ingob 1651
                        }
1652
                        file->SectorInCache     = file->DirectorySector;
1653
                        if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))                                       // read the directory entry for this file.
1654
                        {
1655
                                Fat16_Deinit();
88 killagreg 1656
                                return(EOF);
41 ingob 1657
                        }
88 killagreg 1658
 
41 ingob 1659
                        dir = (DirEntry_t *)file->Cache;
324 killagreg 1660
                        // update file size and modification time & date
211 killagreg 1661
                        dir[file->DirectoryIndex].ModTime = FileTime(&SystemTime);
1662
                        dir[file->DirectoryIndex].ModDate = FileDate(&SystemTime);
1663
                        dir[file->DirectoryIndex].LastAccessDate = dir[file->DirectoryIndex].ModDate;
41 ingob 1664
                        dir[file->DirectoryIndex].Size = file->Size;                                            // update file size
1665
                        if(SD_SUCCESS != SDC_PutSector(file->SectorInCache, file->Cache))       // write back to sd-card
1666
                        {
1667
                                Fat16_Deinit();
1668
                                return(EOF);
1669
                        }
1670
                        break;
1671
                case 'r':
1672
                default:
211 killagreg 1673
                        // do nothing!
41 ingob 1674
                        return(EOF);
1675
                        break;
1676
 
24 StephanB 1677
        }
41 ingob 1678
        return(0);
24 StephanB 1679
}
1 ingob 1680
 
41 ingob 1681
/****************************************************************************************************************************************/
1682
/*      Function:               fclose_(File *file);                                                                                                                                                                                            */
1683
/*                                                                                                                                                                                                                                                                              */
1684
/*      Description:    This function closes the open file by writing the remaining data                                                                                                        */
1685
/*                                      from the buffer to the device and entering the filesize in the directory entry.                                                                         */
1686
/*                                                                                                                                                                                                                                                                              */
1687
/*      Returnvalue:    0 on success EOF on error                                                                                                                                                                                       */
1688
/****************************************************************************************************************************************/
1689
s16 fclose_(File_t *file)
24 StephanB 1690
{
41 ingob 1691
        s16 returnvalue = EOF;
24 StephanB 1692
 
41 ingob 1693
        if(file == NULL) return(returnvalue);
1694
        returnvalue = fflush_(file);
1695
        UnlockFilePointer(file);
1696
        return(returnvalue);
24 StephanB 1697
}
1698
 
41 ingob 1699
/********************************************************************************************************************************************/
1700
/*      Function:               fgetc_(File *file);                                                                                                                                                                                                             */
1701
/*                                                                                                                                                                                                                                                                                      */
1702
/*      Description:    This function reads and returns one character from the specified file. Is the end of the actual sector reached the              */
1703
/*                                      next sector of the cluster is read. If the last sector of the cluster read the next cluster will be searched in FAT.    */
1704
/*                                                                                                                                                                                                                                                                                      */
1705
/*      Returnvalue:    The function returns the character read from the specified memorylocation as u8 casted to s16 or EOF.                                   */
1706
/********************************************************************************************************************************************/
1707
s16 fgetc_(File_t *file)
88 killagreg 1708
{
41 ingob 1709
        s16 c = EOF;
1710
        u32 curr_sector;
88 killagreg 1711
 
41 ingob 1712
        if( (!Partition.IsValid) || (file == NULL)) return(c);
1713
        // if the end of the file is not reached, get the next character.
379 holgerb 1714
        if((0 < file->Size) && ((file->Position) < file->Size) )
1 ingob 1715
        {
41 ingob 1716
                curr_sector  = file->FirstSectorOfCurrCluster;          // calculate the sector of the next character to be read.
88 killagreg 1717
                curr_sector += file->SectorOfCurrCluster;
1718
 
41 ingob 1719
                if(file->SectorInCache != curr_sector)
1 ingob 1720
                {
41 ingob 1721
                        file->SectorInCache = curr_sector;
1722
                        if(SD_SUCCESS != SDC_GetSector(file->SectorInCache,file->Cache))
1723
                        {
1724
                                Fat16_Deinit();
379 holgerb 1725
                                return(EOF);
88 killagreg 1726
                        }
1727
                }
41 ingob 1728
                c = (s16) file->Cache[file->ByteOfCurrSector];
1729
                file->Position++;                                                                       // increment file position
88 killagreg 1730
                file->ByteOfCurrSector++;                                                       // goto next byte in sector
41 ingob 1731
                if(file->ByteOfCurrSector >= BYTES_PER_SECTOR)          // if end of sector
24 StephanB 1732
                {
41 ingob 1733
                        file->ByteOfCurrSector = 0;                                             //  reset byte location
1734
                        file->SectorOfCurrCluster++;                                    //      next sector
1735
                        if(file->SectorOfCurrCluster >= Partition.SectorsPerCluster)    // if end of cluster is reached, the next datacluster has to be searched in the FAT.
24 StephanB 1736
                        {
88 killagreg 1737
 
41 ingob 1738
                                if(GetNextCluster(file))                                                                                // Sets the clusterpointer of the file to the next datacluster.
24 StephanB 1739
                                {
41 ingob 1740
                                        file->SectorOfCurrCluster = 0;                                                          // start reading new cluster at first sector of the cluster.
1741
                                }
1742
                                else // the last cluster was allready reached
1743
                                {
1744
                                        file->SectorOfCurrCluster--;                                                    // jump back to the last sector in the last cluster
1745
                                        file->ByteOfCurrSector = BYTES_PER_SECTOR;                              // set ByteOfCurrSector one byte over sector end
1746
                                }
1 ingob 1747
                        }
24 StephanB 1748
                }
1749
        }
41 ingob 1750
        return(c);
24 StephanB 1751
}
1752
 
41 ingob 1753
/********************************************************************************************************************************************/
1754
/*      Function:               fputc_( const s8 c, File *file);                                                                                                                                                                                */
1755
/*                                                                                                                                                                                                                                                                                      */
1756
/*      Description:    This function writes a byte to the specified file and takes care of writing the necessary FAT- Entries.                                 */
1757
/*                                      next sector of the cluster is read. If the last sector of the cluster read the next cluster will be searched in FAT.    */
1758
/*                                                                                                                                                                                                                                                                                      */
1759
/*      Returnvalue:    The function returns the character written to the stream or EOF on error.                                                                                               */
1760
/********************************************************************************************************************************************/
1761
s16 fputc_(const s8 c, File_t *file)
88 killagreg 1762
{
41 ingob 1763
        u32 curr_sector  = 0;
88 killagreg 1764
 
41 ingob 1765
        if((!Partition.IsValid) || (file == NULL)) return(EOF);
211 killagreg 1766
        switch(file->Mode)
41 ingob 1767
        {
211 killagreg 1768
                case 'w':
1769
                case 'a':
1770
                        // If file position equals to file size, then the end of file has been reached.
1771
                        // In this case it has to be checked that the ByteOfCurrSector is BYTES_PER_SECTOR
1772
                        // and a new cluster should be appended.
1773
                        // If the first sector of first cluster is unvalid, then the file claims no data clusters 
1774
                        // and size should be zero, therefore append a new Cluster too.
1775
                        if(((file->Position >= file->Size) && (file->ByteOfCurrSector >= BYTES_PER_SECTOR)) || (file->FirstSectorOfFirstCluster == SECTOR_UNDEFINED))
1776
                        {
1777
                                if(CLUSTER_UNDEFINED == AppendCluster(file)) return(EOF);
1778
                        }
1779
 
1780
                        curr_sector  = file->FirstSectorOfCurrCluster;
1781
                        curr_sector += file->SectorOfCurrCluster;
1782
                        if(file->SectorInCache != curr_sector)
1783
                        {
1784
                                file->SectorInCache = curr_sector;
1785
                                if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))
24 StephanB 1786
                                {
211 killagreg 1787
                                        Fat16_Deinit();
1788
                                        return(EOF);
24 StephanB 1789
                                }
1 ingob 1790
                        }
379 holgerb 1791
 
1792
                        file->Cache[file->ByteOfCurrSector] = (u8)c;            // write databyte into the buffer. The byte will be written to the device at once
211 killagreg 1793
                        if(file->Size == file->Position) file->Size++;          // a character has been written to the file so the size is incremented only when the character has been added at the end of the file.
1794
                        file->Position++;                                                                       // the actual positon within the file.
1795
                        file->ByteOfCurrSector++;                                                       // goto next byte in sector
1796
                        if(file->ByteOfCurrSector >= BYTES_PER_SECTOR)          // if the end of this sector is reached yet
1797
                        {       // save the sector to the sd-card
1798
                                if(SD_SUCCESS != SDC_PutSector(file->SectorInCache, file->Cache))
1799
                                {
1800
                                        Fat16_Deinit();
1801
                                        return(EOF);
1802
                                }
1803
                                file->ByteOfCurrSector = 0;                                             //  reset byte location
1804
                                file->SectorOfCurrCluster++;                                    //      next sector
1805
                                if(file->SectorOfCurrCluster >= Partition.SectorsPerCluster)// if end of cluster is reached, the next datacluster has to be searched in the FAT.
1806
                                {
1807
                                        if(!GetNextCluster(file))                                                               // Sets the clusterpointer of the file to the next datacluster.
1808
                                        { // if current cluster was the last cluster of the file
1809
                                                if(!AppendCluster(file))                                                // append a new and free cluster at the end of the file.
1810
                                                {
1811
                                                        file->SectorOfCurrCluster--;                            // jump back to last sector of last cluster
1812
                                                        file->ByteOfCurrSector = BYTES_PER_SECTOR;      // set byte location to 1 byte over sector len
1813
                                                        return(EOF);
1814
                                                }
1815
                                        }
1816
                                        else // next cluster
1817
                                        {
1818
                                                file->SectorOfCurrCluster = 0;                                                  // start reading new cluster at first sector of the cluster.
1819
                                        }
1820
                                }
88 killagreg 1821
                        }
211 killagreg 1822
                        break;
1823
                case 'r':
1824
                default:
1825
                        return(EOF);
1826
                        break;
1827
        } // EOF switch(file->Mode)
41 ingob 1828
        return(0);
24 StephanB 1829
}
1830
 
1831
 
41 ingob 1832
/****************************************************************************************************************************************/
1833
/*      Function:               fread_(void *buffer, s32 size, s32 count, File *File);                                                                                                                          */
1834
/*                                                                                                                                                                                                                                                                              */
1835
/*      Description:    This function reads count objects of the specified size                                                                                                                         */
1836
/*                                      from the actual position of the file to the specified buffer.                                                                                                           */
1837
/*                                                                                                                                                                                                                                                                              */
1838
/*      Returnvalue:    The function returns the number of objects (not bytes) read from the file.                                                                                      */
1839
/****************************************************************************************************************************************/
1840
u32 fread_(void *buffer, u32 size, u32 count, File_t *file)
1841
{
1842
        u32 object_cnt  = 0;                                                                                    // count the number of objects read from the file.
1843
        u32 object_size = 0;                                                                                    // count the number of bytes read from the actual object.
1844
        u8 *pbuff       = 0;                                                                                    // a pointer to the actual bufferposition.
1845
        u8 success      = 1;                                                                                    // no error occured during read operation to the file.
88 killagreg 1846
        s16 c;
24 StephanB 1847
 
41 ingob 1848
        if((!Partition.IsValid) || (file == NULL) || (buffer == NULL)) return(0);
24 StephanB 1849
 
41 ingob 1850
        pbuff = (u8 *) buffer;                                                                                  // cast the void pointer to an u8 *
88 killagreg 1851
 
368 holgerb 1852
        while((object_cnt < count) && success)
24 StephanB 1853
        {
41 ingob 1854
                object_size = size;
368 holgerb 1855
                while((size > 0) && success)
41 ingob 1856
                {
1857
                        c = fgetc_(file);
1858
                        if(c != EOF)
1859
                        {
1860
                                *pbuff = (u8)c;                                                                         // read a byte from the buffer to the opened file.
1861
                                pbuff++;
1862
                                size--;
1863
                        }
1864
                        else // error or end of file reached
1865
                        {
88 killagreg 1866
                                success = 0;
41 ingob 1867
                        }
1868
                }
1869
                if(success) object_cnt++;
88 killagreg 1870
        }
41 ingob 1871
        return(object_cnt);                                                                                             // return the number of objects succesfully read from the file
1 ingob 1872
}
1873
 
24 StephanB 1874
 
41 ingob 1875
/****************************************************************************************************************************************/
1876
/*      Function:               fwrite_(void *buffer, s32 size, s32 count, File *file);                                                                                                                         */
1877
/*                                                                                                                                                                                                                                                                              */
1878
/*      Description:    This function writes count objects of the specified size                                                                                                                        */
1879
/*                                      from the buffer pointer to the actual position in the file.                                                                                                                     */
1880
/*                                                                                                                                                                                                                                                                              */
1881
/*      Returnvalue:    The function returns the number of objects (not bytes) read from the file.                                                                                      */
1882
/****************************************************************************************************************************************/
1883
u32 fwrite_(void *buffer, u32 size, u32 count, File_t *file)
1 ingob 1884
{
41 ingob 1885
        u32 object_cnt  = 0;                                                                                                            // count the number of objects written to the file.
1886
        u32 object_size = 0;                                                                                                            // count the number of bytes written from the actual object.
1887
        u8 *pbuff           = 0;                                                                                                                // a pointer to the actual bufferposition.
1888
        u8 success      = 1;                                                                                                            // no error occured during write operation to the file.
88 killagreg 1889
        s16 c;
24 StephanB 1890
 
41 ingob 1891
        if((!Partition.IsValid) || (file == NULL) || (buffer == NULL)) return(0);
211 killagreg 1892
        if(file->Mode == 'r') return (0); // opened read only
41 ingob 1893
        pbuff = (u8 *) buffer;                                                                                                          // cast the void pointer to an u8 *
88 killagreg 1894
 
368 holgerb 1895
        while((object_cnt < count) && success)
1 ingob 1896
        {
41 ingob 1897
                object_size = size;
368 holgerb 1898
                while((size > 0) && success)
1 ingob 1899
                {
41 ingob 1900
                        c = fputc_(*pbuff, file);                                                                               // write a byte from the buffer to the opened file.
1901
                        if(c != EOF)
24 StephanB 1902
                        {
41 ingob 1903
                                pbuff++;
1904
                                size--;
24 StephanB 1905
                        }
41 ingob 1906
                        else
24 StephanB 1907
                        {
41 ingob 1908
                                success = 0;
24 StephanB 1909
                        }
1 ingob 1910
                }
41 ingob 1911
                if(success) object_cnt++;
88 killagreg 1912
        }
1913
 
41 ingob 1914
        return(object_cnt);                                                                                                                             // return the number of objects succesfully written to the file
88 killagreg 1915
}
1 ingob 1916
 
24 StephanB 1917
 
41 ingob 1918
/****************************************************************************************************************************************/
1919
/*      Function:               fputs_(const s8 *string, File_t *File);                                                                                                                                                         */
1920
/*                                                                                                                                                                                                                                                                              */
1921
/*      Description:    This function writes a string to the specified file.                                                                                                                            */
1922
/*                                                                                                                                                                                                                                                                              */
1923
/*      Returnvalue:    The function returns a no negative value or EOF on error.                                                                                                                       */
1924
/****************************************************************************************************************************************/
89 killagreg 1925
s16 fputs_(s8 * const string, File_t * const file)
24 StephanB 1926
{
41 ingob 1927
        u8 i=0;
1928
        s16 c = 0;
88 killagreg 1929
 
211 killagreg 1930
        if((!Partition.IsValid) || (file == NULL) || (string == NULL)) return(EOF);
1931
        if(file->Mode == 'r') return(EOF);
368 holgerb 1932
        while((string[i] != 0)&& (c != EOF))
24 StephanB 1933
        {
41 ingob 1934
                c = fputc_(string[i], file);
1935
                i++;
24 StephanB 1936
        }
41 ingob 1937
        return(c);
24 StephanB 1938
}
1939
 
41 ingob 1940
/****************************************************************************************************************************************/
1941
/*      Function:               fgets_(s8 *, s16 , File_t *);                                                                                                                                                                           */
1942
/*                                                                                                                                                                                                                                                                              */
1943
/*      Description:    This function reads a string from the file to the specifies string.                                                                                             */
1944
/*                                                                                                                                                                                                                                                                              */
1945
/*      Returnvalue:    A pointer to the string read from the file or 0 on error.                                                                                                                       */
1946
/****************************************************************************************************************************************/
89 killagreg 1947
s8 * fgets_(s8 * const string, s16 const length, File_t * const file)
24 StephanB 1948
{
89 killagreg 1949
        s8 *pbuff;
1950
        s16 c = 0, bytecount;
88 killagreg 1951
 
89 killagreg 1952
        if((!Partition.IsValid) || (file == NULL) || (string == NULL) || (length < 1)) return (0);
1953
        bytecount = length;
1954
        pbuff = string;                                                         // set write pointer to start of string
368 holgerb 1955
        while(bytecount > 1)                                            // read the length-1 characters from the file to the string.
24 StephanB 1956
        {
41 ingob 1957
                c = fgetc_(file);                                               // read a character from the opened file.
1958
                switch(c)
1 ingob 1959
                {
89 killagreg 1960
                        case 0x0A:                                                      // new line
1961
                                *pbuff = 0;                                             // set string terminator
1962
                                return(string);                                 // return normal
88 killagreg 1963
 
41 ingob 1964
                        case EOF:
89 killagreg 1965
                                *pbuff = 0;                                             // set string terminator
1966
                                return(0);
1967
 
1968
                        default:
1969
                                *pbuff++ = (s8)c;                               // copy byte to string
1970
                                bytecount--;
88 killagreg 1971
                                break;
1 ingob 1972
                }
24 StephanB 1973
        }
89 killagreg 1974
        *pbuff = 0;     // set string terminator
41 ingob 1975
        return(string);
24 StephanB 1976
}
1977
 
41 ingob 1978
/****************************************************************************************************************************************/
1979
/*      Function:               fexist_(const u8*);                                                                                                                                                                                                     */
1980
/*                                                                                                                                                                                                                                                                              */
1981
/*      Description:    This function checks if a file already exist.                                                                                                                                           */
1982
/*                                                                                                                                                                                                                                                                              */
1983
/*      Returnvalue:    1 if the file exist else 0.                                                                                                                                                                                     */
1984
/****************************************************************************************************************************************/
89 killagreg 1985
u8 fexist_(s8 * const filename)
24 StephanB 1986
{
41 ingob 1987
        u8 exist = 0;
1988
        File_t *file = 0;
1989
        file = LockFilePointer();
1990
        exist = FileExist(filename, ATTR_NONE, ATTR_SUBDIRECTORY|ATTR_VOLUMELABEL, file);
1991
        UnlockFilePointer(file);
1992
        return(exist);
1 ingob 1993
}
24 StephanB 1994
 
41 ingob 1995
/****************************************************************************************************************************************/
1996
/*      Function:               feof_(File_t *File);                                                                                                                                                                                            */
1997
/*                                                                                                                                                                                                                                                                              */
1998
/*      Description:    This function checks wether the end of the file has been reached.                                                                                                                                               */
1999
/*                                                                                                                                                                                                                                                                              */
2000
/*      Returnvalue:    0 if the end of the file was not reached otherwise 1.                                                                                                                                                                           */
2001
/****************************************************************************************************************************************/
2002
u8 feof_(File_t *file)
88 killagreg 2003
{
41 ingob 2004
        if(((file->Position)+1) < (file->Size))
24 StephanB 2005
        {
2006
                return(0);
2007
        }
88 killagreg 2008
        else
24 StephanB 2009
        {
88 killagreg 2010
                return(1);
24 StephanB 2011
        }
2012
}
41 ingob 2013
 
210 killagreg 2014
/****************************************************************************************************************************************************/
2015
/* Function:    s8* FAT16_GetVolumeLabel(void)                                                                                                                                                                                                                  */
2016
/*                                                                                                                                                                                                                                                                                                      */
2017
/* Description: This function returns the volume label                                                                                                                                                                                          */
2018
/*                                                                                                                                                                                                                                                                                                      */
2019
/* Returnvalue: This function returns the pointer to the volume label or NULL if not found.                                                                                                                     */
2020
/****************************************************************************************************************************************************/
2021
s8* FAT16_GetVolumeLabel(void)
2022
{
2023
        s8              *pVolumeLabel = NULL;
2024
        u32             dir_sector, max_dir_sector, curr_sector;
2025
        u16     dir_entry = 0;
2026
        u8              i = 0;
41 ingob 2027
 
210 killagreg 2028
        DirEntry_t * dir;
2029
        File_t *file = NULL;
2030
 
2031
        // if Partition is not valud return NULL
2032
        if(!Partition.IsValid) return(pVolumeLabel);
2033
        // if Volume label was read before return it
2034
        if(Partition.VolumeLabel[0]!= '\0') return (Partition.VolumeLabel);
2035
        // try to catch a file pointer
2036
        file = LockFilePointer();
2037
        if(file == NULL) return(pVolumeLabel);
2038
        // search dir entries direct within the root directory area
2039
        file->DirectorySector = 0;
2040
        max_dir_sector = (Partition.MaxRootEntries * DIRENTRY_SIZE)/BYTES_PER_SECTOR;
2041
        file->FirstSectorOfFirstCluster = Partition.FirstRootDirSector;
2042
 
2043
        // update current file data area position to start of first cluster
2044
        file->FirstSectorOfCurrCluster  = file->FirstSectorOfFirstCluster;
2045
        file->SectorOfCurrCluster               = 0;
2046
        file->ByteOfCurrSector                  = 0;
2047
 
2048
        dir_sector = 0; // reset sector counter within a new cluster
2049
        do // loop over all sectors of the root directory
2050
        {
2051
                curr_sector = file->FirstSectorOfCurrCluster + dir_sector;      // calculate sector number
2052
                file->SectorInCache = curr_sector;                                                      // upate the sector number of file cache.
2053
                if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))// read the sector
2054
                {
2055
                        Fat16_Deinit();
379 holgerb 2056
                        return(NULL);
210 killagreg 2057
                }
2058
                dir = (DirEntry_t *)file->Cache;                                                        // set pointer to directory
2059
                // search all directory entries within that sector
2060
                for(dir_entry = 0; dir_entry < DIRENTRIES_PER_SECTOR; dir_entry++)
2061
                {   // check for existing dir entry
2062
                        switch((u8)dir[dir_entry].Name[0])
2063
                        {
2064
                                case SLOT_EMPTY:
2065
                                case SLOT_DELETED:
2066
                                        // ignore empty or deleted dir entries
2067
                                        break;
2068
                                default:
2069
                                        // check attributes for volume label
2070
                                        if ((dir[dir_entry].Attribute & ATTR_VOLUMELABEL) != ATTR_VOLUMELABEL) break; // attribute must match
2071
                                        // (first 11 characters include 8 chars of basename and 3 chars extension.)
2072
                                        for(i = 0; i<11;i++) Partition.VolumeLabel[i] = dir[dir_entry].Name[i];
2073
                                        Partition.VolumeLabel[11] = '\0'; // terminate string
2074
                                        file->Attribute = dir[dir_entry].Attribute; // store attribute of found dir entry
2075
                                        file->FirstSectorOfFirstCluster = Fat16ClusterToSector(dir[dir_entry].StartCluster); // set sector of first data cluster
2076
                                        file->FirstSectorOfCurrCluster = file->FirstSectorOfFirstCluster;
219 killagreg 2077
                                        file->SectorOfCurrCluster = 0;
2078
                                        file->ByteOfCurrSector = 0;
210 killagreg 2079
                                        file->DirectorySector = curr_sector; // current sector
2080
                                        file->DirectoryIndex  = dir_entry; // current direntry in current sector
2081
                                        file->Size = dir[dir_entry].Size;
2082
                                        dir_entry = DIRENTRIES_PER_SECTOR;      // stop for-loop
2083
                                        pVolumeLabel =  Partition.VolumeLabel;
2084
                        } // end of first byte of name check
2085
                }
2086
                dir_sector++; // search next sector
2087
        // stop if we reached the end of the cluster or the end of the root dir
368 holgerb 2088
        }while((dir_sector < max_dir_sector) && (!pVolumeLabel));
210 killagreg 2089
 
2090
        UnlockFilePointer(file);
2091
        return(pVolumeLabel);
2092
}
379 holgerb 2093
 
2094
 
2095
 
2096
#define ATTR_NONE               0x00    // normal file
2097
#define ATTR_READONLY           0x01    // file is readonly
2098
#define ATTR_HIDDEN                     0x02    // file is hidden
2099
#define ATTR_SYSTEM                     0x04    // file is a system file
2100
#define ATTR_VOLUMELABEL        0x08    // entry is a volume label
2101
#define ATTR_LONG_FILENAME      0x0F    // this is a long filename entry
2102
#define ATTR_SUBDIRECTORY       0x10    // entry is a directory name
2103
#define ATTR_ARCHIVE            0x20    // file is new or modified
2104
 
2105
 
2106
/********************************************************************************************************************************************/
2107
/*      Function:               u8 FindItem(Find_t);                                                                                                                                                                                                                    */
2108
/*                                                                                                                                                                                                                                                                                      */
2109
/*      Description:    This function looks for the item specified by global structure FindElement in the actual directory                                      */
2110
/*                                                                                                                                                                                                                                                              */
2111
/*                                                                                                                                                                                                                                                                                      */
2112
/*      Returnvalue:    TRUE if an matching element was found                                                                                                                                                                           */
2113
/********************************************************************************************************************************************/
2114
 
2115
u8 FindItem(Find_t *findelement)
2116
{
2117
        u16             index = 0;
2118
        u16             max_dir_sector = 0;
2119
        u16     end_of_directory_not_reached = 1;                                                                               // the directory has been read completely without a result.
2120
        u8              i = 0;
2121
        u8              readpointer = 0;
2122
        u8              writepointer = 0;
2123
        u8              retvalue = 0;
2124
        DirEntry_t      *DirectoryEntry;
2125
        File_t  file;
2126
 
2127
        file.FirstSectorOfCurrCluster   = findelement->fp.FirstSectorOfCurrCluster;
2128
        file.SectorOfCurrCluster        = findelement->fp.SectorOfCurrCluster;
2129
        index                                                   = findelement->fp.DirectoryIndex;
2130
 
2131
        // within the root directory area we can read sectors sequentially until the end of this area
2132
        if((Partition.FirstRootDirSector <= file.FirstSectorOfCurrCluster) && (file.FirstSectorOfCurrCluster < Partition.FirstDataSector))
2133
        {
2134
                max_dir_sector = (Partition.MaxRootEntries * DIRENTRY_SIZE)/BYTES_PER_SECTOR;
2135
        }
2136
        // within the data clusters we can read sectors sequentially only within the cluster
2137
        else if((Partition.FirstDataSector <= file.FirstSectorOfCurrCluster) && (file.FirstSectorOfCurrCluster <= Partition.LastDataSector))
2138
        {
2139
                max_dir_sector = Partition.SectorsPerCluster;                           // limit max secters before next cluster
2140
        }
2141
 
2142
        do
2143
        {                                                                                                                                                               // search the next 16 rootentries in this sector of the roordirectory.          
2144
                if(SD_SUCCESS != SDC_GetSector(((u32) file.FirstSectorOfCurrCluster + (u32)file.SectorOfCurrCluster), file.Cache));                                             // Read the Rootdirectory.
2145
                {
2146
                        Fat16_Deinit();
2147
                        return(0);
2148
                }
2149
 
2150
                DirectoryEntry = (DirEntry_t *)file.Cache;
2151
 
2152
                while((!retvalue)&&(index<16))
2153
                {
2154
                        i=0;                   
2155
                        if((u8) DirectoryEntry[index].Name[0] != 0xe5)                                                          // ignore deleted items.
2156
                        {
2157
                                while((i<=10)&&((DirectoryEntry[index].Name[i] == findelement->searchstring[i]) || (findelement->searchstring[i]=='*') || findelement->searchstring[i]=='?'))
2158
                                {
2159
                                        i++;
2160
                                }
2161
                        }
2162
                        if((DirectoryEntry[index].Attribute <= 0x30) && (DirectoryEntry[index].Attribute & findelement->attribmask) && (i==11))
2163
                        {
2164
                for(readpointer=0;readpointer<=10;readpointer++)
2165
                                {
2166
                                        if((DirectoryEntry[index].Name[readpointer] != ' ') && (readpointer!=8))
2167
                                        {
2168
                                                findelement->name[writepointer] = DirectoryEntry[index].Name[readpointer];      // copy the name of the item found to the find_structure.
2169
                                                writepointer++;
2170
                                        }
2171
                                        else  
2172
                                        {
2173
                                                if(DirectoryEntry[index].Attribute == ATTR_ARCHIVE)                                            
2174
                                                {
2175
                                        if(readpointer < 8) readpointer=8;
2176
                                        if(DirectoryEntry[index].Name[readpointer] != ' ')
2177
                                        {
2178
                                        findelement->name[writepointer] = '.';                                                  // then seperate the name and the extension by a '.' at index 8.                                                
2179
                                        writepointer++;
2180
                                        findelement->name[writepointer] = DirectoryEntry[index].Name[readpointer];      // copy the name of the item found to the find_structure.
2181
                                        writepointer++;
2182
                                        }
2183
                                            else break;
2184
                                                }
2185
                            else break;
2186
                        }
2187
                        /* terminate the namestring with 0 for debugpurposes*/
2188
                        findelement->name[12] = 0;
2189
                                }
2190
                                findelement->fp.FirstSectorOfFirstCluster = (u32) DirectoryEntry[index].StartCluster;                                                  
2191
                                findelement->fp.DirectoryIndex   = index;              
2192
                                findelement->fp.FirstSectorOfCurrCluster   = file.FirstSectorOfCurrCluster;
2193
                                findelement->fp.DirectorySector  = (file.FirstSectorOfCurrCluster + file.SectorOfCurrCluster);
2194
                                findelement->fp.SectorOfCurrCluster      = file.SectorOfCurrCluster;
2195
                findelement->fp.Size            = DirectoryEntry[index].Size;
2196
                                findelement->fp.Attribute               = DirectoryEntry[index].Attribute;
2197
                retvalue = 1;
2198
                        }                      
2199
                        /* search the next sector */
2200
                        index++;
2201
                }
2202
                /* this sector has been searched but we havn't found what we are looking for. Therefore we have to find the next sector */
2203
                if(!retvalue)                                                                                                                           // file not found in this sector so take next sector.
2204
                {
2205
                        /* in the next sector we start looking for the specified entry beginning at index 0 */
2206
                        index = 0;
2207
                        /* there are still sectors to be read within the cluster or within the linear addresspace of the rootdirectory */
2208
                        if(file.SectorOfCurrCluster < max_dir_sector-1)  file.SectorOfCurrCluster++; else end_of_directory_not_reached = 0;
2209
                        /* if we are looking for an directoryentry outside the rootdirectory and have reached the end of the cluster we have to get the next one */
2210
                        if(Partition.FirstDataSector <= file.FirstSectorOfCurrCluster)
2211
                        {
2212
                                end_of_directory_not_reached = GetNextCluster(&file);
2213
                        }
2214
                }
2215
        }
2216
        while((end_of_directory_not_reached) && (!retvalue) );
2217
 
2218
        return(retvalue);      
2219
}
2220
 
2221
 
2222
 
2223
 
2224
/********************************************************************************************************************************************/
2225
/*      Function:               findnext_(Find_t *);                                                                                                                                                                                                                    */
2226
/*                                                                                                                                                                                                                                                                                      */
2227
/*      Description:    This function looks for the next item in the specified directory with a matching filename and fileattributes specified  */
2228
/*                  by function findfirst()                                                                                                                                                                                                     */
2229
/*                                                                                                                                                                                                                                                                                      */
2230
/*      Returnvalue:                                                                                                                                                                                                                                                    */
2231
/********************************************************************************************************************************************/
2232
u8 findnext_(Find_t * findelement)
2233
{
2234
        u8 itemfound = 0;
2235
        u8 index = 0;
2236
 
2237
        findelement->fp.DirectoryIndex++;
2238
 
2239
        /* before we start searching an element we clear the complete namestring within the structure FindElement */
2240
        for(index=0;index<11;index++) findelement->name[index] = 0;
2241
 
2242
        if(FindItem(findelement))
2243
        {
2244
                itemfound = 1;         
2245
        }
2246
 
2247
        return(itemfound);
2248
}
2249
 
2250
 
2251
 
2252
/********************************************************************************************************************************************/
2253
/*      Function:               findfirst_(s8* filename, u8 attribmask, Find_t *);                                                                                                                                              */
2254
/*                                                                                                                                                                                                                                                                                      */
2255
/*      Description:    This function looks for the first item in the specified directory with a matching filename and fileattributes                   */
2256
/*                                      The filename of the element found is transformed from 8.3 to a string                                                                                                   */
2257
/*                                                                                                                                                                                                                                                                                      */
2258
/*                                                                                                                                                                                                                                                                                      */
2259
/*      Returnvalue:    (1) if Element was found. (0) if no valid element was found                                                                                                                     */
2260
/********************************************************************************************************************************************/
2261
u8 findfirst_(const s8* name, u8 attribmask, Find_t *findelement)
2262
{
2263
        u8 itemfound = 0;
2264
        u8 index = 0;  
2265
 
2266
        /* initialize the FindElement structure */
2267
        findelement->fp.FirstSectorOfFirstCluster = 0;  // First sector of the first cluster of the file.
2268
        findelement->fp.FirstSectorOfCurrCluster = Partition.CurrentWorkingDirectory;                                   // First sector of the cluster which is edited at the moment.
2269
        findelement->fp.SectorOfCurrCluster = 0;                                                        // The sector within the current cluster.
2270
        findelement->fp.ByteOfCurrSector = 0;                                                   // The byte location within the current sector.
2271
        findelement->fp.Size = 0;                                                                               // The size of the opend file in bytes.
2272
        findelement->fp.Position = 0;                                                                   // Pointer to a character within the file 0 < fileposition < filesize
2273
        findelement->fp.DirectorySector = 0;                                                            // the sectorposition where the directoryentry has been made.
2274
        findelement->fp.DirectoryIndex = 0;                                                             // The index to the directoryentry within the specified sector.
2275
        findelement->attribfilter = 0;
2276
        findelement->attribmask = attribmask;
2277
        findelement->searchstring[0]=0;
2278
 
2279
        /* seperate the name of the element to be found from the filepath and bring it to the 8.3*/
2280
        SeperateDirName(name, findelement->searchstring);
2281
        /* after the name of the element is in 8.3 we process the wildcards (*). After an * all following character are wildcards to */
2282
        for(index=0;index<8;index++)
2283
        {
2284
                /* if we find an wildcard within the name of the searchstring all remaining character after the wildcard shall be wildcards also */
2285
                if(findelement->searchstring[index] == '*')
2286
                {
2287
                        /*  */
2288
                        while(++index <8) findelement->searchstring[index] = '*';
2289
                }
2290
        }
2291
        for(index=8;index<11;index++)
2292
        {                                                                                                                                                                                                                                        
2293
                /* if we find an wildcard within the name of the searchstring all remaining character after the wildcard shall be wildcards also */
2294
                if(findelement->searchstring[index] == '*')
2295
                {
2296
                        /*  */
2297
                        while(++index <11) findelement->searchstring[index] = '*';
2298
                }
2299
        }
2300
 
2301
        /* the value of ...DirectoryIndex will be incremented in findnext_() thererfore it has to be decremented in findfirst_() */
2302
        findelement->fp.DirectoryIndex--;
2303
        /* now lets search for the item within the direcory */
2304
        itemfound = findnext_(findelement);
2305
 
2306
        return(itemfound);
2307
}
2308
 
2309
 
2310
/********************************************************************************************************************************************/
2311
/*      Function:               u8 GetDirCount(s8* filepath);                                                                                                                                                                                   */
2312
/*                                                                                                                                                                                                                                                                                      */
2313
/*      Description:    This function counts the number of subdirectories the dirpath contains                                                                                                  */
2314
/*                                                                                                                                                                                                                                                              */
2315
/*                                                                                                                                                                                                                                                                                      */
2316
/*      Returnvalue:    then number of subdirectories within the specified path                                                                                                                                 */
2317
/********************************************************************************************************************************************/
2318
u8 GetDirCount(u8 *dirpath)
2319
{
2320
   u8 i=0;
2321
   u8 cnt=0;
2322
 
2323
   while(dirpath[i] != 0 )
2324
   {
2325
      if(dirpath[i]=='/')
2326
      {  
2327
         if(dirpath[i+1]!=0) cnt++;                                            // ignore last'/'
2328
      }
2329
      i++;  
2330
   }
2331
   i=0;  
2332
   return(cnt);
2333
}
2334
 
2335
 
2336
/********************************************************************************************************************************************/
2337
/* Funtion:     char *GetSubDirectory (char *dirpath, char *directory)                                                                                                                                          */
2338
/*                                                                                                                                                                                                                                                                                      */
2339
/* Description: this function returns a pointer to the beginning of the next subdirectory or NULL                                                                                       */
2340
/*                                                                                                                                                                                                                                                                                      */
2341
/*                                                                                                                                                                                                                                                                                      */
2342
/* returnvalue:   number of subdirectories in the filepath                                                                                                                                                                      */
2343
/********************************************************************************************************************************************/
2344
u8 * GetSubDirectory(u8 *dirpath, u8 *directory)
2345
{
2346
   u8 *cptr = dirpath;
2347
   u8 *dptr = directory;
2348
   u8 *retvalue = NULL;
2349
 
2350
   /* if the first character of the path is an '/' we go to the next character */
2351
   if(*cptr == '/') cptr++;
2352
   /* search end of path or subdirectory*/
2353
   while((*cptr != 0) && (*cptr != '/'))
2354
   {
2355
      *dptr = *cptr;
2356
       dptr++;
2357
       cptr++;
2358
   }  
2359
   if(*cptr!=0) retvalue = ++cptr;
2360
   *dptr = 0;
2361
 
2362
   return(retvalue);
2363
}
2364
 
2365
/********************************************************************************************************************************************/
2366
/*      Function:               s8 *GetPath(void);                                                                                                                                                                                                              */
2367
/*                                                                                                                                                                                                                                                                                      */
2368
/*      Description:    This function function returns a pointer to the absolute path of the active partition                                                                   */
2369
/*                                                                                                                                                                                                                                      */
2370
/*                                                                                                                                                                                                                                                                                      */
2371
/*      Returnvalue:                                                                                                                                                                                                                                                    */
2372
/********************************************************************************************************************************************/
2373
 
2374
s8 *GetPath(void)
2375
{
2376
        return(Partition.PathToCwd);
2377
}
2378
 
2379
/********************************************************************************************************************************************/
2380
/*      Function:               void SetPathToRoot(void);                                                                                                                                                                                                       */
2381
/*                                                                                                                                                                                                                                                                                      */
2382
/*      Description:    This function sets the path to the rootdirectory                                                                                                                                                */
2383
/*                                                                                                                                                                                                                                      */
2384
/*                                                                                                                                                                                                                                                                                      */
2385
/*      Returnvalue:                                                                                                                                                                                                                                                    */
2386
/********************************************************************************************************************************************/
2387
 
2388
void SetPathToRoot(void)
2389
{
2390
        /* lets point to the rootdirectory */
2391
        strcpy(Partition.PathToCwd, "/");      
2392
}
2393
 
2394
/********************************************************************************************************************************************/
2395
/*      Function:               void AppendDirToPath(s8* directory);                                                                                                                                                                                    */
2396
/*                                                                                                                                                                                                                                                                                      */
2397
/*      Description:    This function function appends the name of an directory to the Path to the CWD                                                                                  */
2398
/*                                                                                                                                                                                                                                      */
2399
/*                                                                                                                                                                                                                                                                                      */
2400
/*      Returnvalue:                                                                                                                                                                                                                                                    */
2401
/********************************************************************************************************************************************/
2402
 
2403
void AppendDirToPath(s8* directory)
2404
{
2405
        /* append the name of the directory to the path */
2406
        strcat(Partition.PathToCwd, directory);
2407
        /* append a '/' after the directoryname */
2408
        strcat(Partition.PathToCwd, "/");
2409
}
2410
 
2411
/********************************************************************************************************************************************/
2412
/*      Function:               RemoveLastDirFromPath(void);                                                                                                                                                                                    */
2413
/*                                                                                                                                                                                                                                                                                      */
2414
/*      Description:    This function removes the last directory from the path to the cwd                                                                                                               */
2415
/*                                                                                                                                                                                                                                      */
2416
/*                                                                                                                                                                                                                                                                                      */
2417
/*      Returnvalue:                                                                                                                                                                                                                                                    */
2418
/********************************************************************************************************************************************/
2419
 
2420
void RemoveLastDirFromPath(void)
2421
{
2422
        /* a pointer to the beginning of the absolute path to the cwd */
2423
        s8 * cptr = Partition.PathToCwd;
2424
        /* lets find the end of the path to the cwd */
2425
        while(*cptr != 0 ) cptr++;
2426
        /* if the path is terminated with an '/' */
2427
        if((*(cptr-1)) == '/') *(cptr-1)=0;    
2428
        /* now lets find the beginning of the last directorientry */
2429
        while((*cptr != '/' ) && cptr > Partition.PathToCwd) cptr--;
2430
        /* is there one subdirectory left within the path? */
2431
        if(cptr > Partition.PathToCwd)
2432
        {
2433
                /* we delete the direntry by terminating the path with 0 */
2434
                *cptr = 0;
2435
        }
2436
        /* there is no subdirectory left within the path. Therefore we create the root instead. */
2437
        else
2438
        {
2439
                *cptr = '/';
2440
                *(cptr+1) = 0;
2441
        }
2442
}
2443
 
2444
/********************************************************************************************************************************************/
2445
/*      Function:               chdir_(s8* filepath);                                                                                                                                                                                                   */
2446
/*                                                                                                                                                                                                                                                                                      */
2447
/*      Description:    This function changed the current working directory to the directory specified by the filepath                                                  */
2448
/*                  by function findfirst()                                                                                                                                                                                                     */
2449
/*                                                                                                                                                                                                                                                                                      */
2450
/*      Returnvalue:                                                                                                                                                                                                                                                    */
2451
/********************************************************************************************************************************************/
2452
/*                                                                         
2453
#define ATTR_NONE               0x00    // normal file
2454
#define ATTR_READONLY           0x01    // file is readonly
2455
#define ATTR_HIDDEN                     0x02    // file is hidden
2456
#define ATTR_SYSTEM                     0x04    // file is a system file
2457
#define ATTR_VOLUMELABEL        0x08    // entry is a volume label
2458
#define ATTR_LONG_FILENAME      0x0F    // this is a long filename entry
2459
#define ATTR_SUBDIRECTORY       0x10    // entry is a directory name
2460
#define ATTR_ARCHIVE            0x20    // file is new or modified
2461
*/
2462
 
2463
u8 chdir_(s8 *path)
2464
{
2465
        u8              retvalue = 0;                                   // the value returned by this function
2466
        u32     ultemp = 0;                                             // temp. variable
2467
        u8     *directory = path;                               // pointer to a directoryname within the path
2468
        u8      dircount = 0;                                   // the number of subdirectoryentries within the path
2469
        u8      cache[64];                                              // a buffer containing the name of the subdirectory we are actually looking for
2470
        Find_t  fe;                                                             // The findelement needed for function findfirst to find the subdirectoryentry
2471
        s8              tp[256];                                                // temporarily we remember the actual path until the operation has finished successfully
2472
        u32     cwdt = 0;
2473
        s8     *cptr;
2474
 
2475
        /* bring the path into the correct syntax */
2476
        cptr = path;
2477
        /* search the whole string */
2478
        while(*cptr != 0 )
2479
        {
2480
                if(*cptr == '\\') *cptr = '/';
2481
                cptr++;
2482
        }
2483
        /* lets remember the actual path */
2484
        strcpy(tp, Partition.PathToCwd);
2485
        cwdt = Partition.CurrentWorkingDirectory;
2486
        /* how many subdirectories are there within the path? */
2487
        dircount = GetDirCount(path);  
2488
        /* if the path is absolute we begin at the rootdirectory */
2489
        if(path[0] == '/')
2490
        {
2491
                strcpy(Partition.PathToCwd, "/");
2492
                Partition.CurrentWorkingDirectory = Partition.FirstRootDirSector;
2493
                /* if there is no other pathinformation we only switch to the rootdirectory. So theres nothing left todo.*/
2494
                if(!dircount) return(1);
2495
        }
2496
        /* now we parse through all the subdirectories within the path */
2497
        do
2498
        {  
2499
                /* until all the subdirectories within the path have been processed */
2500
        if(dircount) dircount--;
2501
                /* this is the name of the next subdirectory we are looking for */             
2502
            directory = GetSubDirectory(directory, cache);  
2503
                /* search for the next subdirectory within the path */
2504
                if(findfirst_(cache, ATTR_SUBDIRECTORY, &fe))
2505
                {
2506
                        /* we try to change into the directory "..". Now we have to delete the last direntry from the path */
2507
                        if(strcmp(cache,"..") == 0) RemoveLastDirFromPath();
2508
                        /* we try to change into the actual directory so there's nothing todo */
2509
                        else if(cache[0] == '.') return(1);
2510
                        /* otherwise we append the name of the directory we are changing in to the path */
2511
                        else AppendDirToPath(cache);
2512
                        /* The startcluster within an directoryentry specifies the position within the fat where the file or directory starts */
2513
                        ultemp = (u32) fe.fp.FirstSectorOfFirstCluster;
2514
                        /* the first 2 entries are reserved for '.' and '..' */
2515
                        ultemp -= 2;
2516
                        /* now we have to transform the position within the fat into the corrosponding sectoraddress relative to the beginning of the datasection of the active partition*/
2517
                        ultemp *= Partition.SectorsPerCluster;
2518
                        /* at least we make the sectoraddress absolute by adding the relative address to the beginning of the datasection of the active partition */
2519
                        ultemp += Partition.FirstDataSector;
2520
                        /* the cwd now points to the specified directory */
2521
                        Partition.CurrentWorkingDirectory = ultemp;
2522
                        /* we found the folder specified by the foldername */
2523
                        retvalue = 1;
2524
                }
2525
        }
2526
        /* do this until all subdirectories have been found or a subdirectory is missing */
2527
        while(dircount && retvalue );
2528
 
2529
        /* if we could not change to the specified directory we restore the actual path */
2530
        if(!retvalue)
2531
        {
2532
                Partition.CurrentWorkingDirectory = cwdt;                                                  
2533
                strcpy(Partition.PathToCwd, tp);
2534
        }
2535
        return(retvalue);      
2536
}