]> icculus.org git repositories - taylor/freespace2.git/blob - src/cfile/cfile.cpp
filesystem cleanup and consolidation:
[taylor/freespace2.git] / src / cfile / cfile.cpp
1 /*
2  * Copyright (C) Volition, Inc. 1999.  All rights reserved.
3  *
4  * All source code herein is the property of Volition, Inc. You may not sell 
5  * or otherwise commercially exploit the source or things you created based on
6  * the source.
7  */
8
9 /*
10  * $Logfile: /Freespace2/code/CFile/cfile.cpp $
11  * $Revision$
12  * $Date$
13  * $Author$
14  *
15  * Utilities for operating on files
16  *
17  * $Log$
18  * Revision 1.14  2006/04/26 19:36:57  taylor
19  * address an error handling bug in cfwrite()
20  *
21  * Revision 1.13  2005/10/01 22:04:58  taylor
22  * fix FS1 (de)briefing voices, the directory names are different in FS1
23  * hard code the table values so that the fs1.vp file isn't needed
24  * hard code a mission fix for sm2-08a since a have no idea how to fix it otherwise
25  * generally cleanup some FS1 code
26  * fix volume sliders in the options screen that never went all the way up
27  *
28  * Revision 1.12  2005/08/12 08:50:09  taylor
29  * recursively create directories (hurt more on OSX) and update all _mkdir() calls accordingly
30  *
31  * Revision 1.11  2004/07/04 11:27:29  taylor
32  * cleanup CFILE code a little, warning fixes, remove redundant dir checks, amd64 support
33  *
34  * Revision 1.10  2004/06/11 00:28:39  tigital
35  * byte-swapping changes for bigendian systems
36  *
37  * Revision 1.9  2003/05/25 02:30:42  taylor
38  * Freespace 1 support
39  *
40  * Revision 1.8  2003/02/20 17:41:07  theoddone33
41  * Userdir patch from Taylor Richards
42  *
43  * Revision 1.7  2002/12/30 03:23:29  relnev
44  * disable root dir check
45  *
46  * Revision 1.6  2002/06/17 06:33:08  relnev
47  * ryan's struct patch for gcc 2.95
48  *
49  * Revision 1.5  2002/06/09 04:41:15  relnev
50  * added copyright header
51  *
52  * Revision 1.4  2002/06/05 08:05:28  relnev
53  * stub/warning removal.
54  *
55  * reworked the sound code.
56  *
57  * Revision 1.3  2002/05/28 08:52:03  relnev
58  * implemented two assembly stubs.
59  *
60  * cleaned up a few warnings.
61  *
62  * added a little demo hackery to make it progress a little farther.
63  *
64  * Revision 1.2  2002/05/28 06:28:20  theoddone33
65  * Filesystem mods, actually reads some data files now
66  *
67  * Revision 1.1.1.1  2002/05/03 03:28:08  root
68  * Initial import.
69  *
70  * 
71  * 20    9/08/99 10:01p Dave
72  * Make sure game won't run in a drive's root directory. Make sure
73  * standalone routes suqad war messages properly to the host.
74  * 
75  * 19    9/08/99 12:03a Dave
76  * Make squad logos render properly in D3D all the time. Added intel anim
77  * directory.
78  * 
79  * 18    9/06/99 2:35p Dave
80  * Rename briefing and debriefing voice direcrory paths properly.
81  * 
82  * 17    9/03/99 1:31a Dave
83  * CD checking by act. Added support to play 2 cutscenes in a row
84  * seamlessly. Fixed super low level cfile bug related to files in the
85  * root directory of a CD. Added cheat code to set campaign mission # in
86  * main hall.
87  * 
88  * 16    8/31/99 9:46a Dave
89  * Support for new cfile cbanims directory.
90  * 
91  * 15    8/06/99 11:20a Johns
92  * Don't call game_cd_changed() in a demo or multiplayer beta build.
93  * 
94  * 14    6/08/99 2:33p Dave
95  * Fixed release build warning. Put in hud config stuff.
96  * 
97  * 13    5/19/99 4:07p Dave
98  * Moved versioning code into a nice isolated common place. Fixed up
99  * updating code on the pxo screen. Fixed several stub problems.
100  * 
101  * 12    4/30/99 12:18p Dave
102  * Several minor bug fixes.
103  * 
104  * 11    4/07/99 5:54p Dave
105  * Fixes for encryption in updatelauncher.
106  * 
107  * 10    3/28/99 5:58p Dave
108  * Added early demo code. Make objects move. Nice and framerate
109  * independant, but not much else. Don't use yet unless you're me :)
110  * 
111  * 9     2/22/99 10:31p Andsager
112  * Get rid of unneeded includes.
113  * 
114  * 8     1/12/99 3:15a Dave
115  * Barracks screen support for selecting squad logos. We need real artwork
116  * :)
117  * 
118  * 7     11/30/98 1:07p Dave
119  * 16 bit conversion, first run.
120  * 
121  * 6     10/29/98 10:41a Dave
122  * Change the way cfile initializes exe directory.
123  * 
124  * 5     10/13/98 9:19a Andsager
125  * Add localization support to cfile.  Optional parameter with cfopen that
126  * looks for localized files.
127  * 
128  * 4     10/12/98 9:54a Dave
129  * Fixed a few file organization things.
130  * 
131  * 3     10/07/98 6:27p Dave
132  * Globalized mission and campaign file extensions. Removed Silent Threat
133  * special code. Moved \cache \players and \multidata into the \data
134  * directory.
135  * 
136  * 2     10/07/98 10:52a Dave
137  * Initial checkin.
138  * 
139  * 1     10/07/98 10:48a Dave
140  * 
141  * 110   9/17/98 10:31a Hoffoss
142  * Changed code to use location of executable as root rather than relying
143  * on the cwd being set correctly.  This is most helpful in the case of
144  * Fred launching due to the user double-clicking on an .fsm file in
145  * explorer or something (where the cwd is probably the location of the
146  * .fsm file).
147  * 
148  * 109   9/11/98 4:14p Dave
149  * Fixed file checksumming of < file_size. Put in more verbose kicking and
150  * PXO stats store reporting.
151  * 
152  * 108   9/09/98 5:53p Dave
153  * Put in new tracker packets in API. Change cfile to be able to checksum
154  * portions of a file.
155  * 
156  * 107   9/04/98 3:51p Dave
157  * Put in validated mission updating and application during stats
158  * updating.
159  * 
160  * 106   8/31/98 2:06p Dave
161  * Make cfile sort the ordering or vp files. Added support/checks for
162  * recognizing "mission disk" players.
163  * 
164  * 105   8/20/98 5:30p Dave
165  * Put in handy multiplayer logfile system. Now need to put in useful
166  * applications of it all over the code.
167  * 
168  * 104   8/12/98 4:53p Dave
169  * Put in 32 bit checksumming for PXO missions. No validation on the
170  * actual tracker yet, though.
171  * 
172  * 103   6/17/98 9:30a Allender
173  * fixed red alert replay stats clearing problem
174  * 
175  * 102   6/05/98 9:46a Lawrance
176  * check for CD change on cfopen()
177  * 
178  * 101   5/19/98 1:19p Allender
179  * new low level reliable socket reading code.  Make all missions/campaign
180  * load/save to data missions folder (i.e. we are rid of the player
181  * missions folder)
182  * 
183  * 100   5/13/98 10:22p John
184  * Added cfile functions to read/write rle compressed blocks of data.
185  * Made palman use it for .clr files.  Made alphacolors calculate on the
186  * fly rather than caching to/from disk.
187  * 
188  * 99    5/11/98 10:59a John
189  * Moved the low-level file reading code into cfilearchive.cpp.
190  * 
191  * 98    5/06/98 5:30p John
192  * Removed unused cfilearchiver.  Removed/replaced some unused/little used
193  * graphics functions, namely gradient_h and _v and pixel_sp.   Put in new
194  * DirectX header files and libs that fixed the Direct3D alpha blending
195  * problems.
196  * 
197  * 97    5/03/98 11:53a John
198  * Fixed filename case mangling.
199  * 
200  * 96    5/03/98 8:33a John
201  * Made sure there weren't any more broken function lurking around like
202  * the one Allender fixed.  
203  * 
204  * 95    5/02/98 11:05p Allender
205  * fix cfilelength for pack files
206  * 
207  *
208  * $NoKeywords: $
209  */
210 #define _CFILE_INTERNAL 
211
212 #include <stdlib.h>
213 #include <string.h>
214 #include <stdio.h>
215 #include <errno.h>
216 #ifndef PLAT_UNIX
217 #include <io.h>
218 #include <direct.h>
219 #include <windows.h>
220 #include <winbase.h>            /* needed for memory mapping of file functions */
221 #else
222 #include <unistd.h>
223 #include <sys/stat.h>
224 #include <sys/types.h>
225 #endif
226
227 #include "pstypes.h"
228 #include "cfile.h"
229 #include "encrypt.h"
230 //#include "outwnd.h"
231 //#include "vecmat.h"
232 //#include "timer.h"
233 #include "cfilesystem.h"
234 #include "cfilearchive.h"
235 #include "osapi.h"
236 #include "osregistry.h"
237
238 char Cfile_root_dir[CFILE_ROOT_DIRECTORY_LEN] = "";
239 char Cfile_user_dir[CFILE_ROOT_DIRECTORY_LEN] = "";
240
241 // During cfile_init, verify that Pathtypes[n].index == n for each item
242 // Each path must have a valid parent that can be tracable all the way back to the root 
243 // so that we can create directories when we need to.
244 //
245 cf_pathtype Pathtypes[CF_MAX_PATH_TYPES]  = {
246         // What type this is          Path                             Extensions              Parent type
247         { CF_TYPE_INVALID,                              NULL,                                                                           NULL,                                                   CF_TYPE_INVALID },
248         // Root must be index 1!!       
249         { CF_TYPE_ROOT,                                 "",                                                                             ".mve",                                                 CF_TYPE_ROOT    },
250         { CF_TYPE_DATA,                                 "Data",                                                                 ".cfg .log .txt",                       CF_TYPE_ROOT    },
251 #ifdef PLAT_UNIX
252         { CF_TYPE_MAPS,                                 "Data/Maps",                                                    ".pcx .ani .tga",                       CF_TYPE_DATA    },
253         { CF_TYPE_TEXT,                                 "Data/Text",                                                    ".txt .net",                            CF_TYPE_DATA    },
254 #ifdef MAKE_FS1
255         { CF_TYPE_MISSIONS,                             "Data/Missions",                                                ".fsm .fsc .ntl .ssv",  CF_TYPE_DATA    },
256 #else
257         { CF_TYPE_MISSIONS,                             "Data/Missions",                                                ".fs2 .fc2 .ntl .ssv",  CF_TYPE_DATA    },
258 #endif
259         { CF_TYPE_MODELS,                                       "Data/Models",                                          ".pof",                                         CF_TYPE_DATA    },
260         { CF_TYPE_TABLES,                                       "Data/Tables",                                          ".tbl",                                         CF_TYPE_DATA    },
261         { CF_TYPE_SOUNDS,                                       "Data/Sounds",                                          ".wav",                                         CF_TYPE_DATA    },
262         { CF_TYPE_SOUNDS_8B22K,                 "Data/Sounds/8b22k",                            ".wav",                                         CF_TYPE_SOUNDS  },
263         { CF_TYPE_SOUNDS_16B11K,                "Data/Sounds/16b11k",                           ".wav",                                         CF_TYPE_SOUNDS  },
264         { CF_TYPE_VOICE,                                        "Data/Voice",                                                   "",                                                     CF_TYPE_DATA    },
265 #ifdef MAKE_FS1
266         { CF_TYPE_VOICE_BRIEFINGS,              "Data/Voice/Briefings",                 ".wav",                                         CF_TYPE_VOICE   },
267 #else
268         { CF_TYPE_VOICE_BRIEFINGS,              "Data/Voice/Briefing",                  ".wav",                                         CF_TYPE_VOICE   },
269 #endif
270         { CF_TYPE_VOICE_CMD_BRIEF,              "Data/Voice/Command_briefings",".wav",                                          CF_TYPE_VOICE   },
271 #ifdef MAKE_FS1
272         { CF_TYPE_VOICE_DEBRIEFINGS,    "Data/Voice/Debriefings",                       ".wav",                                         CF_TYPE_VOICE   },
273 #else
274         { CF_TYPE_VOICE_DEBRIEFINGS,    "Data/Voice/Debriefing",                        ".wav",                                         CF_TYPE_VOICE   },
275 #endif
276         { CF_TYPE_VOICE_PERSONAS,               "Data/Voice/Personas",                  ".wav",                                         CF_TYPE_VOICE   },
277         { CF_TYPE_VOICE_SPECIAL,                "Data/Voice/Special",                           ".wav",                                         CF_TYPE_VOICE   },
278         { CF_TYPE_VOICE_TRAINING,               "Data/Voice/Training",                  ".wav",                                         CF_TYPE_VOICE   },
279         { CF_TYPE_MUSIC,                                        "Data/Music",                                                   ".wav",                                         CF_TYPE_VOICE   },
280         { CF_TYPE_MOVIES,                                       "Data/Movies",                                          ".mve .msb",                            CF_TYPE_DATA    },
281         { CF_TYPE_INTERFACE,                            "Data/Interface",                                       ".pcx .ani .tga",                       CF_TYPE_DATA    },
282         { CF_TYPE_FONT,                                 "Data/Fonts",                                                   ".vf",                                          CF_TYPE_DATA    },
283         { CF_TYPE_EFFECTS,                              "Data/Effects",                                         ".ani .pcx .neb .tga",  CF_TYPE_DATA    },
284         { CF_TYPE_HUD,                                          "Data/Hud",                                                     ".ani .pcx .tga",                       CF_TYPE_DATA    },
285         { CF_TYPE_PLAYER_MAIN,                  "Data/Players",                                         "",                                                     CF_TYPE_DATA    },
286         { CF_TYPE_PLAYER_IMAGES_MAIN,   "Data/Players/Images",                  ".pcx",                                         CF_TYPE_PLAYER_MAIN     },
287         { CF_TYPE_CACHE,                                        "Data/Cache",                                                   ".clr .tmp",                            CF_TYPE_DATA    },      //clr=cached color
288         { CF_TYPE_PLAYERS,                              "Data/Players",                                         ".hcf",                                         CF_TYPE_DATA    },      
289         { CF_TYPE_SINGLE_PLAYERS,               "Data/Players/Single",                  ".plr .csg .css",                       CF_TYPE_PLAYERS },
290         { CF_TYPE_MULTI_PLAYERS,                "Data/Players/Multi",                           ".plr",                                         CF_TYPE_DATA    },
291         { CF_TYPE_MULTI_CACHE,                  "Data/MultiData",                                       ".pcx .fs2",                            CF_TYPE_DATA    },
292         { CF_TYPE_CONFIG,                                       "Data/Config",                                          ".cfg",                                         CF_TYPE_DATA    },
293         { CF_TYPE_SQUAD_IMAGES_MAIN,    "Data/Players/Squads",                  ".pcx",                                         CF_TYPE_DATA    },
294         { CF_TYPE_DEMOS,                                        "Data/Demos",                                                   ".fsd",                                         CF_TYPE_DATA    },
295         { CF_TYPE_CBANIMS,                              "Data/CBAnims",                                         ".ani",                                         CF_TYPE_DATA    },
296         { CF_TYPE_INTEL_ANIMS,                  "Data/IntelAnims",                                      ".ani",                                         CF_TYPE_DATA    },
297 #else
298         { CF_TYPE_MAPS,                                 "Data\\Maps",                                                   ".pcx .ani .tga",                       CF_TYPE_DATA    },
299         { CF_TYPE_TEXT,                                 "Data\\Text",                                                   ".txt .net",                            CF_TYPE_DATA    },
300         { CF_TYPE_MISSIONS,                             "Data\\Missions",                                               ".fs2 .fc2 .ntl .ssv",  CF_TYPE_DATA    },
301         { CF_TYPE_MODELS,                                       "Data\\Models",                                         ".pof",                                         CF_TYPE_DATA    },
302         { CF_TYPE_TABLES,                                       "Data\\Tables",                                         ".tbl",                                         CF_TYPE_DATA    },
303         { CF_TYPE_SOUNDS,                                       "Data\\Sounds",                                         ".wav",                                         CF_TYPE_DATA    },
304         { CF_TYPE_SOUNDS_8B22K,                 "Data\\Sounds\\8b22k",                          ".wav",                                         CF_TYPE_SOUNDS  },
305         { CF_TYPE_SOUNDS_16B11K,                "Data\\Sounds\\16b11k",                         ".wav",                                         CF_TYPE_SOUNDS  },
306         { CF_TYPE_VOICE,                                        "Data\\Voice",                                                  "",                                                     CF_TYPE_DATA    },
307         { CF_TYPE_VOICE_BRIEFINGS,              "Data\\Voice\\Briefing",                        ".wav",                                         CF_TYPE_VOICE   },
308         { CF_TYPE_VOICE_CMD_BRIEF,              "Data\\Voice\\Command_briefings",".wav",                                                CF_TYPE_VOICE   },
309         { CF_TYPE_VOICE_DEBRIEFINGS,    "Data\\Voice\\Debriefing",                      ".wav",                                         CF_TYPE_VOICE   },
310         { CF_TYPE_VOICE_PERSONAS,               "Data\\Voice\\Personas",                        ".wav",                                         CF_TYPE_VOICE   },
311         { CF_TYPE_VOICE_SPECIAL,                "Data\\Voice\\Special",                         ".wav",                                         CF_TYPE_VOICE   },
312         { CF_TYPE_VOICE_TRAINING,               "Data\\Voice\\Training",                        ".wav",                                         CF_TYPE_VOICE   },
313         { CF_TYPE_MUSIC,                                        "Data\\Music",                                                  ".wav",                                         CF_TYPE_VOICE   },
314         { CF_TYPE_MOVIES,                                       "Data\\Movies",                                         ".mve .msb",                            CF_TYPE_DATA    },
315         { CF_TYPE_INTERFACE,                            "Data\\Interface",                                      ".pcx .ani .tga",                       CF_TYPE_DATA    },
316         { CF_TYPE_FONT,                                 "Data\\Fonts",                                                  ".vf",                                          CF_TYPE_DATA    },
317         { CF_TYPE_EFFECTS,                              "Data\\Effects",                                                ".ani .pcx .neb .tga",  CF_TYPE_DATA    },
318         { CF_TYPE_HUD,                                          "Data\\Hud",                                                    ".ani .pcx .tga",                       CF_TYPE_DATA    },
319         { CF_TYPE_PLAYER_MAIN,                  "Data\\Players",                                                "",                                                     CF_TYPE_DATA    },
320         { CF_TYPE_PLAYER_IMAGES_MAIN,   "Data\\Players\\Images",                        ".pcx",                                         CF_TYPE_PLAYER_MAIN     },
321         { CF_TYPE_CACHE,                                        "Data\\Cache",                                                  ".clr .tmp",                            CF_TYPE_DATA    },      //clr=cached color
322         { CF_TYPE_PLAYERS,                              "Data\\Players",                                                ".hcf",                                         CF_TYPE_DATA    },      
323         { CF_TYPE_SINGLE_PLAYERS,               "Data\\Players\\Single",                        ".plr .csg .css",                       CF_TYPE_PLAYERS },
324         { CF_TYPE_MULTI_PLAYERS,                "Data\\Players\\Multi",                         ".plr",                                         CF_TYPE_DATA    },
325         { CF_TYPE_MULTI_CACHE,                  "Data\\MultiData",                                      ".pcx .fs2",                            CF_TYPE_DATA    },
326         { CF_TYPE_CONFIG,                                       "Data\\Config",                                         ".cfg",                                         CF_TYPE_DATA    },
327         { CF_TYPE_SQUAD_IMAGES_MAIN,    "Data\\Players\\Squads",                        ".pcx",                                         CF_TYPE_DATA    },
328         { CF_TYPE_DEMOS,                                        "Data\\Demos",                                                  ".fsd",                                         CF_TYPE_DATA    },
329         { CF_TYPE_CBANIMS,                              "Data\\CBAnims",                                                ".ani",                                         CF_TYPE_DATA    },
330         { CF_TYPE_INTEL_ANIMS,                  "Data\\IntelAnims",                                     ".ani",                                         CF_TYPE_DATA    },
331 #endif
332 };
333
334
335 #define CFILE_STACK_MAX 8
336
337 int cfile_inited = 0;
338 int Cfile_stack_pos = 0;
339
340 char Cfile_stack[128][CFILE_STACK_MAX];
341
342 Cfile_block Cfile_block_list[MAX_CFILE_BLOCKS];
343 CFILE Cfile_list[MAX_CFILE_BLOCKS];
344
345 char *Cfile_cdrom_dir = NULL;
346
347 //
348 // Function prototypes for internally-called functions
349 //
350 int cfget_cfile_block();
351 CFILE *cf_open_fill_cfblock(FILE * fp, int type);
352 CFILE *cf_open_packed_cfblock(FILE *fp, int type, int offset, int size);
353 CFILE *cf_open_mapped_fill_cfblock(HANDLE hFile, int type);
354 void cf_chksum_long_init();
355
356 void cfile_close()
357 {
358         cf_free_secondary_filelist();
359 }
360
361 // determine if the given path is in a root directory (c:\  or  c:\freespace2.exe  or  c:\fred2.exe   etc)
362 int cfile_in_root_dir(char *exe_path)
363 {
364         int token_count = 0;
365         char path_copy[2048] = "";
366         char *tok;
367
368         // bogus
369         if(exe_path == NULL){
370                 return 1;
371         }
372
373         // copy the path
374         memset(path_copy, 0, 2048);
375         strncpy(path_copy, exe_path, 2047);
376
377         // count how many slashes there are in the path
378         tok = strtok(path_copy, DIR_SEPARATOR_STR);
379         if(tok == NULL){
380                 return 1;
381         }       
382         do {
383                 token_count++;
384                 tok = strtok(NULL, DIR_SEPARATOR_STR);
385         } while(tok != NULL);
386                 
387         // root directory if we have <= 1 slash
388         if(token_count <= 2){
389                 return 1;
390         }
391
392         // not-root directory
393         return 0;
394 }
395
396 // cfile_init() initializes the cfile system.  Called once at application start.
397 //
398 //      returns:  success ==> 0
399 //           error   ==> non-zero
400 //
401 int cfile_init(const char *cdrom_dir)
402 {
403         int i;
404
405         // initialize encryption
406         encrypt_init(); 
407
408         if ( !cfile_inited ) {
409                 // initialize root and user paths (may have been done already)
410                 if ( cfile_init_paths() ) {
411                         return 1;
412                 }
413
414                 cfile_inited = 1;
415
416                 for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
417                         Cfile_block_list[i].type = CFILE_BLOCK_UNUSED;
418                 }
419
420                 Cfile_cdrom_dir = (char *)cdrom_dir;
421
422                 cf_build_secondary_filelist(Cfile_cdrom_dir);
423
424                 // 32 bit CRC table init
425                 cf_chksum_long_init();
426
427
428
429                 atexit( cfile_close );
430         }
431
432         return 0;
433 }
434
435 // Call this if pack files got added or removed or the
436 // cdrom changed.  This will refresh the list of filenames 
437 // stored in packfiles and on the cdrom.
438 void cfile_refresh()
439 {
440         cf_build_secondary_filelist(Cfile_cdrom_dir);
441 }
442
443
444 // Changes to a drive if valid.. 1=A, 2=B, etc
445 // If flag, then changes to it.
446 // Returns 0 if not-valid, 1 if valid.
447 int cfile_chdrive( int DriveNum, int flag )
448 {
449 #ifdef PLAT_UNIX
450         STUB_FUNCTION;
451         return 0;
452 #else
453         int n, org;
454         int Valid = 0;
455
456         org = -1;
457         if (!flag)
458                 org = _getdrive();
459
460         _chdrive( DriveNum );
461         n = _getdrive();
462
463
464         if (n == DriveNum )
465                 Valid = 1;
466
467         if ( (!flag) && (n != org) )
468                 _chdrive( org );
469         return Valid;
470 #endif
471 }
472
473 // push current directory on a 'stack' (so we can restore it) and change the directory
474 int cfile_push_chdir(int type)
475 {
476         int e;
477         char dir[128];
478         char OriginalDirectory[128];
479         char *Path;
480         char NoDir[] = "\\.";
481
482         _getcwd(OriginalDirectory, 127);
483         Assert(Cfile_stack_pos < CFILE_STACK_MAX);
484         strcpy(Cfile_stack[Cfile_stack_pos++], OriginalDirectory);
485
486         cf_create_default_path_string( dir, type, NULL );
487         _strlwr(dir);
488 #ifndef PLAT_UNIX
489         char *Drive = strchr(dir, ':');
490
491         if (Drive) {
492                 if (!cfile_chdrive( *(Drive - 1) - 'a' + 1, 1))
493                         return 1;
494
495                 Path = Drive+1;
496
497         } else 
498 #endif
499         {
500                 Path = dir;
501         }
502
503         if (!(*Path)) {
504                 Path = NoDir;
505         }
506
507         // This chdir might get a critical error!
508         e = _chdir( Path );
509         if (e) {
510                 cfile_chdrive( OriginalDirectory[0] - 'a' + 1, 1 );
511                 return 2;
512         }
513
514         return 0;
515 }
516
517
518 int cfile_chdir(char *dir)
519 {
520         int e;
521         char OriginalDirectory[128];
522         char *Path;
523         char NoDir[] = "\\.";
524
525         _getcwd(OriginalDirectory, 127);
526         _strlwr(dir);
527
528 #ifndef PLAT_UNIX
529         char *Drive = strchr(dir, ':');
530         if (Drive)      {
531                 if (!cfile_chdrive( *(Drive - 1) - 'a' + 1, 1))
532                         return 1;
533
534                 Path = Drive+1;
535
536         } else 
537 #endif
538         {
539                 Path = dir;
540         }
541
542         if (!(*Path)) {
543                 Path = NoDir;
544         }
545
546         // This chdir might get a critical error!
547         e = _chdir( Path );
548         if (e) {
549                 cfile_chdrive( OriginalDirectory[0] - 'a' + 1, 1 );
550                 return 2;
551         }
552
553         return 0;
554 }
555
556 int cfile_pop_dir()
557 {
558         Assert(Cfile_stack_pos);
559         Cfile_stack_pos--;
560         return cfile_chdir(Cfile_stack[Cfile_stack_pos]);
561 }
562
563 // flush (delete all files in) the passed directory (by type), return the # of files deleted
564 // NOTE : WILL NOT DELETE READ-ONLY FILES
565 int cfile_flush_dir(int dir_type)
566 {
567 #ifdef PLAT_UNIX
568         STUB_FUNCTION;
569         return 0;
570 #else
571         int find_handle;
572         int del_count;
573         _finddata_t find;
574
575         Assert( CF_TYPE_SPECIFIED(dir_type) );
576
577         // attempt to change the directory to the passed type
578         if(cfile_push_chdir(dir_type)){
579                 return 0;
580         }
581
582         // proceed to delete the files
583         find_handle = _findfirst( "*", &find );
584         del_count = 0;
585         if (find_handle != -1) {
586                 do {                    
587                         if (!(find.attrib & _A_SUBDIR) && !(find.attrib & _A_RDONLY)) {
588                                 // delete the file
589                                 cf_delete(find.name,dir_type);                          
590
591                                 // increment the deleted count
592                                 del_count++;
593                         }
594                 } while (!_findnext(find_handle, &find));
595                 _findclose( find_handle );
596         }
597
598         // pop the directory back
599         cfile_pop_dir();
600
601         // return the # of files deleted
602         return del_count;
603 #endif
604 }
605
606
607 // add the given extention to a filename (or filepath) if it doesn't already have this
608 // extension.
609 //    filename = name of filename or filepath to process
610 //    ext = extension to add.  Must start with the period
611 //    Returns: new filename or filepath with extension.
612 char *cf_add_ext(const char *filename, const char *ext)
613 {
614         int flen, elen;
615         static char path[MAX_PATH_LEN];
616
617         flen = strlen(filename);
618         elen = strlen(ext);
619         Assert(flen < MAX_PATH_LEN);
620         strcpy(path, filename);
621         if ((flen < 4) || stricmp(path + flen - elen, ext)) {
622                 Assert(flen + elen < MAX_PATH_LEN);
623                 strcat(path, ext);
624         }
625
626         return path;
627 }
628
629 // Deletes a file.
630 void cf_delete( const char *filename, int dir_type )
631 {
632         char longname[MAX_PATH_LEN];
633
634         Assert( CF_TYPE_SPECIFIED(dir_type) );
635
636         cf_create_default_path_string( longname, dir_type, filename );
637
638         FILE *fp = fopen(longname, "rb");
639         if (fp) {
640                 // delete the file
641                 fclose(fp);
642                 _unlink(longname);
643         }
644
645 }
646
647
648 // Same as _access function to read a file's access bits
649 int cf_access( const char *filename, int dir_type, int mode )
650 {
651         char longname[MAX_PATH_LEN];
652
653         Assert( CF_TYPE_SPECIFIED(dir_type) );
654
655         cf_create_default_path_string( longname, dir_type, filename );
656
657         return access(longname,mode);
658 }
659
660
661 // Returns 1 if file exists, 0 if not.
662 int cf_exist( const char *filename, int dir_type )
663 {
664         char longname[MAX_PATH_LEN];
665
666         Assert( CF_TYPE_SPECIFIED(dir_type) );
667
668         cf_create_default_path_string( longname, dir_type, filename );
669
670         FILE *fp = fopen(longname, "rb");
671         if (fp) {
672                 return 1;
673                 fclose(fp);
674         }
675
676         return 0;
677 }
678
679 void cf_attrib(const char *filename, int set, int clear, int dir_type)
680 {
681         char longname[MAX_PATH_LEN];
682
683         Assert( CF_TYPE_SPECIFIED(dir_type) );
684
685         cf_create_default_path_string( longname, dir_type, filename );
686
687         FILE *fp = fopen(longname, "rb");
688         if (fp) {
689                 fclose(fp);
690
691 #ifdef PLAT_UNIX
692                 STUB_FUNCTION;
693 #else
694                 DWORD z = GetFileAttributes(longname);
695                 SetFileAttributes(longname, z | set & ~clear);
696 #endif
697         }
698
699 }
700
701 int cf_rename(const char *old_name, const char *name, int dir_type)
702 {
703         Assert( CF_TYPE_SPECIFIED(dir_type) );
704
705         int ret_code;
706         char old_longname[_MAX_PATH];
707         char new_longname[_MAX_PATH];
708         
709         cf_create_default_path_string( old_longname, dir_type, old_name );
710         cf_create_default_path_string( new_longname, dir_type, name );
711
712         ret_code = rename(old_longname, new_longname );         
713         if(ret_code != 0){
714                 switch(errno){
715                 case EACCES :
716                         return CF_RENAME_FAIL_ACCESS;
717                 case ENOENT :
718                 default:
719                         return CF_RENAME_FAIL_EXIST;
720                 }
721         }
722
723         return CF_RENAME_SUCCESS;
724         
725
726 }
727
728 // Creates the directory path if it doesn't exist. Even creates all its
729 // parent paths.
730 void cf_create_directory( int dir_type )
731 {
732         int num_dirs = 0;
733         int dir_tree[CF_MAX_PATH_TYPES];
734         char longname[MAX_PATH_LEN];
735
736         Assert( CF_TYPE_SPECIFIED(dir_type) );
737
738         int current_dir = dir_type;
739
740         do {
741                 Assert( num_dirs < CF_MAX_PATH_TYPES );         // Invalid Pathtypes data?
742
743                 dir_tree[num_dirs++] = current_dir;
744                 current_dir = Pathtypes[current_dir].parent_index;
745
746         } while( current_dir != CF_TYPE_ROOT );
747
748         
749         int i;
750
751         for (i=num_dirs-1; i>=0; i-- )  {
752                 cf_create_default_path_string( longname, dir_tree[i], NULL );
753
754                 if ( _mkdir(longname)==0 )      {
755                         mprintf(( "CFILE: Created new directory '%s'\n", longname ));
756                 }
757         }
758
759
760 }
761
762
763 extern int game_cd_changed();
764
765 // cfopen()
766 //
767 // parameters:  *filepath ==> name of file to open (may be path+name)
768 //              *mode     ==> specifies how file should be opened (eg "rb" for read binary)
769 //                            passing NULL to mode deletes the file if it exists and returns NULL
770 //               type     ==> one of:    CFILE_NORMAL
771 //                                       CFILE_MEMORY_MAPPED
772 //                                        dir_type      =>      override extension check, value is one of CF_TYPE* #defines
773 //
774 //               NOTE: type parameter is an optional parameter.  The default value is CFILE_NORMAL
775 //
776 //
777 // returns:             success ==> address of CFILE structure
778 //                                      error   ==> NULL
779 //
780
781 CFILE *cfopen(const char *file_path, const char *mode, int type, int dir_type, bool localize)
782 {
783         char longname[_MAX_PATH];
784
785 //      nprintf(("CFILE", "CFILE -- trying to open %s\n", file_path ));
786 // #if !defined(MULTIPLAYER_BETA_BUILD) && !defined(FS2_DEMO)
787
788 // we no longer need to do this, and on machines with crappy-ass drivers it can slow things down horribly.
789 #if 0   
790         if ( game_cd_changed() ) {
791                 cfile_refresh();
792         }
793 #endif
794
795         //================================================
796         // Check that all the parameters make sense
797         Assert(file_path && strlen(file_path));
798         Assert( mode != NULL );
799         
800         // Can only open read-only binary files in memory mapped mode.
801         if ( (type & CFILE_MEMORY_MAPPED) && strcmp(mode,"rb") ) {
802                 Int3();                         
803                 return NULL;
804         }
805
806         //===========================================================
807         // If in write mode, just try to open the file straight off
808         // the harddisk.  No fancy packfile stuff here!
809         
810         if ( strchr(mode,'w') ) {
811                 // For write-only files, require a full path or a path type
812 #ifdef PLAT_UNIX
813                 if ( strpbrk(file_path, "/") ) {
814 #else
815                 if ( strpbrk(file_path,"/\\:")  ) {  
816 #endif
817                         // Full path given?
818                         strcpy(longname, file_path );
819                 } else {
820                         // Path type given?
821                         Assert( dir_type != CF_TYPE_ANY );
822
823                         // Create the directory if necessary
824                         cf_create_directory( dir_type );
825
826                         cf_create_default_path_string( longname, dir_type, file_path );
827                 }
828                 Assert( !(type & CFILE_MEMORY_MAPPED) );
829
830                 // JOHN: TODO, you should create the path if it doesn't exist.
831                                 
832                 FILE *fp = fopen(longname, mode);
833                 if (fp) {
834                         return cf_open_fill_cfblock(fp, dir_type);
835                 }
836                 return NULL;
837         } 
838
839
840         //================================================
841         // Search for file on disk, on cdrom, or in a packfile
842
843         int offset, size;
844         char copy_file_path[MAX_PATH_LEN];  // FIX change in memory from cf_find_file_location
845         strcpy(copy_file_path, file_path);
846
847
848         if ( cf_find_file_location( copy_file_path, dir_type, longname, &size, &offset, localize ) )    {
849
850                 // Fount it, now create a cfile out of it
851                 
852                 if ( type & CFILE_MEMORY_MAPPED ) {
853                 
854                         // Can't open memory mapped files out of pack files
855                         if ( offset == 0 )      {
856 #ifdef PLAT_UNIX
857                                 STUB_FUNCTION;
858 #else
859                                 HANDLE hFile;
860
861                                 hFile = CreateFile(longname, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
862
863                                 if (hFile != INVALID_HANDLE_VALUE)      {
864                                         return cf_open_mapped_fill_cfblock(hFile, dir_type);
865                                 }
866 #endif
867                         } 
868
869                 } else {
870
871                         FILE *fp = fopen( longname, "rb" );
872
873                         if ( fp )       {
874                                 if ( offset )   {
875                                         // Found it in a pack file
876                                         return cf_open_packed_cfblock(fp, dir_type, offset, size );
877                                 } else {
878                                         // Found it in a normal file
879                                         return cf_open_fill_cfblock(fp, dir_type);
880                                 } 
881                         }
882                 }
883
884         }
885
886         return NULL;
887 }
888
889
890 // ------------------------------------------------------------------------
891 // ctmpfile() 
892 //
893 // Open up a temporary file.  A unique name is automatically generated.  The
894 // file will be automatically deleted when file is closed.
895 //
896 // return:              NULL                                    =>              tmp file could not be opened
897 //                                      pointer to CFILE        =>              tmp file successfully opened
898 //
899 CFILE *ctmpfile()
900 {
901         FILE    *fp;
902         fp = tmpfile();
903         if ( fp )
904                 return cf_open_fill_cfblock(fp, 0);
905         else
906                 return NULL;
907 }
908
909
910
911 // cfget_cfile_block() will try to find an empty Cfile_block structure in the
912 //      Cfile_block_list[] array and return the index.
913 //
914 // returns:   success ==> index in Cfile_block_list[] array
915 //            failure ==> -1
916 //
917 int cfget_cfile_block()
918 {       
919         int i;
920         Cfile_block *cb;
921
922         for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
923                 cb = &Cfile_block_list[i];
924                 if ( cb->type == CFILE_BLOCK_UNUSED ) {
925                         cb->data = NULL;
926                         cb->fp = NULL;
927                         cb->type = CFILE_BLOCK_USED;
928                         return i;
929                 }
930         }
931
932         // If we've reached this point, a free Cfile_block could not be found
933         nprintf(("Warning","A free Cfile_block could not be found.\n"));
934         Assert(0);      // out of free cfile blocks
935         return -1;                      
936 }
937
938
939 // cfclose() closes the file
940 //
941 // returns:   success ==> 0
942 //                                failure ==> EOF
943 //
944 int cfclose( CFILE * cfile )
945 {
946         int result;
947
948         Assert(cfile != NULL);
949         Cfile_block *cb;
950         Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
951         cb = &Cfile_block_list[cfile->id];      
952
953         result = 0;
954         if ( cb->data ) {
955                 // close memory mapped file
956 #ifdef PLAT_UNIX
957                 STUB_FUNCTION;
958 #else
959                 result = UnmapViewOfFile((void*)cb->data);
960                 Assert(result);
961                 result = CloseHandle(cb->hInFile);              
962                 Assert(result); // Ensure file handle is closed properly
963                 result = CloseHandle(cb->hMapFile);             
964                 Assert(result); // Ensure file handle is closed properly
965 #endif
966                 result = 0;
967
968         } else if ( cb->fp != NULL )    {
969                 Assert(cb->fp != NULL);
970                 result = fclose(cb->fp);
971         } else {
972                 // VP  do nothing
973         }
974
975         cb->type = CFILE_BLOCK_UNUSED;
976         return result;
977 }
978
979
980
981
982 // cf_open_fill_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
983 // for the case of a file being opened by cf_open();
984 //
985 // returns:   success ==> ptr to CFILE structure.  
986 //            error   ==> NULL
987 //
988 CFILE *cf_open_fill_cfblock(FILE *fp, int type)
989 {
990         int cfile_block_index;
991
992         cfile_block_index = cfget_cfile_block();
993         if ( cfile_block_index == -1 ) {
994                 return NULL;
995         } else {
996                 CFILE *cfp;
997                 Cfile_block *cfbp;
998                 cfbp = &Cfile_block_list[cfile_block_index];
999                 cfp = &Cfile_list[cfile_block_index];;
1000                 cfp->id = cfile_block_index;
1001                 cfp->version = 0;
1002                 cfbp->data = NULL;
1003                 cfbp->fp = fp;
1004                 cfbp->dir_type = type;
1005                 
1006                 cf_init_lowlevel_read_code(cfp,0,filelength(fileno(fp)) );
1007
1008                 return cfp;
1009         }
1010 }
1011
1012
1013 // cf_open_packed_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
1014 // for the case of a file being opened by cf_open();
1015 //
1016 // returns:   success ==> ptr to CFILE structure.  
1017 //            error   ==> NULL
1018 //
1019 CFILE *cf_open_packed_cfblock(FILE *fp, int type, int offset, int size)
1020 {
1021         // Found it in a pack file
1022         int cfile_block_index;
1023         
1024         cfile_block_index = cfget_cfile_block();
1025         if ( cfile_block_index == -1 ) {
1026                 return NULL;
1027         } else {
1028                 CFILE *cfp;
1029                 Cfile_block *cfbp;
1030                 cfbp = &Cfile_block_list[cfile_block_index];
1031         
1032                 cfp = &Cfile_list[cfile_block_index];
1033                 cfp->id = cfile_block_index;
1034                 cfp->version = 0;
1035                 cfbp->data = NULL;
1036                 cfbp->fp = fp;
1037                 cfbp->dir_type = type;
1038
1039                 cf_init_lowlevel_read_code(cfp,offset, size );
1040
1041                 return cfp;
1042         }
1043
1044 }
1045
1046
1047
1048 // cf_open_mapped_fill_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
1049 // for the case of a file being opened by cf_open_mapped();
1050 //
1051 // returns:   ptr CFILE structure.  
1052 //
1053 CFILE *cf_open_mapped_fill_cfblock(HANDLE hFile, int type)
1054 {
1055         int cfile_block_index;
1056
1057         cfile_block_index = cfget_cfile_block();
1058         if ( cfile_block_index == -1 ) {
1059                 return NULL;
1060         }
1061         else {
1062                 CFILE *cfp;
1063                 Cfile_block *cfbp;
1064                 cfbp = &Cfile_block_list[cfile_block_index];
1065
1066                 cfp = &Cfile_list[cfile_block_index];
1067                 cfp->id = cfile_block_index;
1068                 cfbp->fp = NULL;
1069                 cfbp->hInFile = hFile;
1070                 cfbp->dir_type = type;
1071
1072                 cf_init_lowlevel_read_code(cfp,0 , 0 );
1073
1074 #ifdef PLAT_UNIX
1075                 STUB_FUNCTION;
1076 #else
1077                 cfbp->hMapFile = CreateFileMapping(cfbp->hInFile, NULL, PAGE_READONLY, 0, 0, NULL);
1078                 if (cfbp->hMapFile == NULL) { 
1079                         nprintf(("Error", "Could not create file-mapping object.\n")); 
1080                         return NULL;
1081                 } 
1082         
1083                 cfbp->data = (ubyte*)MapViewOfFile(cfbp->hMapFile, FILE_MAP_READ, 0, 0, 0);
1084                 Assert( cfbp->data != NULL );           
1085 #endif
1086                 return cfp;
1087         }
1088 }
1089
1090 int cf_get_dir_type(CFILE *cfile)
1091 {
1092         return Cfile_block_list[cfile->id].dir_type;
1093 }
1094
1095 // cf_returndata() returns the data pointer for a memory-mapped file that is associated
1096 // with the CFILE structure passed as a parameter
1097 //
1098 // 
1099
1100 void *cf_returndata(CFILE *cfile)
1101 {
1102         Assert(cfile != NULL);
1103         Cfile_block *cb;
1104         Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1105         cb = &Cfile_block_list[cfile->id];      
1106         Assert(cb->data != NULL);
1107         return cb->data;
1108 }
1109
1110
1111
1112 // version number of opened file.  Will be 0 unless you put something else here after you
1113 // open a file.  Once set, you can use minimum version numbers with the read functions.
1114 void cf_set_version( CFILE * cfile, int version )
1115 {
1116         Assert(cfile != NULL);
1117
1118         cfile->version = version;
1119 }
1120
1121 // routines to read basic data types from CFILE's.  Put here to
1122 // simplify mac/pc reading from cfiles.
1123 #ifdef __APPLE__
1124 #include <stddef.h>
1125 #endif
1126
1127 float cfread_float(CFILE *file, int ver, float deflt)
1128 {
1129         float f;
1130
1131         if (file->version < ver)
1132                 return deflt;
1133
1134         if (cfread( &f, sizeof(f), 1, file) != 1)
1135                 return deflt;
1136
1137     f = INTEL_FLOAT(&f);
1138         return f;
1139 }
1140
1141 int cfread_int(CFILE *file, int ver, int deflt)
1142 {
1143         int i;
1144
1145         if (file->version < ver)
1146                 return deflt;
1147
1148         if (cfread( &i, sizeof(i), 1, file) != 1)
1149                 return deflt;
1150
1151         i = INTEL_INT(i);
1152         return i;
1153 }
1154
1155 uint cfread_uint(CFILE *file, int ver, uint deflt)
1156 {
1157         uint i;
1158
1159         if (file->version < ver)
1160                 return deflt;
1161
1162         if (cfread( &i, sizeof(i), 1, file) != 1)
1163                 return deflt;
1164
1165         i = INTEL_INT(i);
1166         return i;
1167 }
1168
1169 short cfread_short(CFILE *file, int ver, short deflt)
1170 {
1171         short s;
1172
1173         if (file->version < ver)
1174                 return deflt;
1175
1176         if (cfread( &s, sizeof(s), 1, file) != 1)
1177                 return deflt;
1178
1179         s = INTEL_SHORT(s);
1180         return s;
1181 }
1182
1183 ushort cfread_ushort(CFILE *file, int ver, ushort deflt)
1184 {
1185         ushort s;
1186
1187         if (file->version < ver)
1188                 return deflt;
1189
1190         if (cfread( &s, sizeof(s), 1, file) != 1)
1191                 return deflt;
1192
1193         s = INTEL_SHORT(s);
1194         return s;
1195 }
1196
1197 ubyte cfread_ubyte(CFILE *file, int ver, ubyte deflt)
1198 {
1199         ubyte b;
1200
1201         if (file->version < ver)
1202                 return deflt;
1203
1204         if (cfread( &b, sizeof(b), 1, file) != 1)
1205                 return deflt;
1206
1207         return b;
1208 }
1209
1210 void cfread_vector(vector *vec, CFILE *file, int ver, vector *deflt)
1211 {
1212         if (file->version < ver) {
1213                 if (deflt)
1214                         *vec = *deflt;
1215                 else
1216                         vec->xyz.x = vec->xyz.y = vec->xyz.z = 0.0f;
1217
1218                 return;
1219         }
1220
1221         vec->xyz.x = cfread_float(file, ver, deflt ? deflt->xyz.x : 0.0f);
1222         vec->xyz.y = cfread_float(file, ver, deflt ? deflt->xyz.y : 0.0f);
1223         vec->xyz.z = cfread_float(file, ver, deflt ? deflt->xyz.z : 0.0f);
1224 }
1225         
1226 void cfread_angles(angles *ang, CFILE *file, int ver, angles *deflt)
1227 {
1228         if (file->version < ver) {
1229                 if (deflt)
1230                         *ang = *deflt;
1231                 else
1232                         ang->p = ang->b = ang->h = 0.0f;
1233
1234                 return;
1235         }
1236
1237         ang->p = cfread_float(file, ver, deflt ? deflt->p : 0.0f);
1238         ang->b = cfread_float(file, ver, deflt ? deflt->b : 0.0f);
1239         ang->h = cfread_float(file, ver, deflt ? deflt->h : 0.0f);
1240 }
1241
1242 char cfread_char(CFILE *file, int ver, char deflt)
1243 {
1244         char b;
1245
1246         if (file->version < ver)
1247                 return deflt;
1248
1249         if (cfread( &b, sizeof(b), 1, file) != 1)
1250                 return deflt;
1251
1252         return b;
1253 }
1254
1255 void cfread_string(char *buf, int n, CFILE *file)
1256 {
1257         char c;
1258
1259         do {
1260                 c = cfread_char(file);
1261                 if ( n > 0 )    {
1262                         *buf++ = c;
1263                         n--;
1264                 }
1265         } while (c != 0 );
1266 }
1267
1268 void cfread_string_len(char *buf,int n, CFILE *file)
1269 {
1270         int len;
1271         len = cfread_int(file);
1272         Assert( len < n );
1273         if (len)
1274                 cfread(buf, len, 1, file);
1275
1276         buf[len] = 0;
1277 }
1278
1279 // equivalent write functions of above read functions follow
1280
1281 int cfwrite_float(float f, CFILE *file)
1282 {
1283     f = INTEL_FLOAT(&f);
1284         return cfwrite(&f, sizeof(f), 1, file);
1285 }
1286
1287 int cfwrite_int(int i, CFILE *file)
1288 {
1289         i = INTEL_INT(i);
1290         return cfwrite(&i, sizeof(i), 1, file);
1291 }
1292
1293 int cfwrite_uint(uint i, CFILE *file)
1294 {
1295         i = INTEL_INT(i);
1296         return cfwrite(&i, sizeof(i), 1, file);
1297 }
1298
1299 int cfwrite_short(short s, CFILE *file)
1300 {
1301         s = INTEL_SHORT(s);
1302         return cfwrite(&s, sizeof(s), 1, file);
1303 }
1304
1305 int cfwrite_ushort(ushort s, CFILE *file)
1306 {
1307         s = INTEL_SHORT(s);
1308         return cfwrite(&s, sizeof(s), 1, file);
1309 }
1310
1311 int cfwrite_ubyte(ubyte b, CFILE *file)
1312 {
1313         return cfwrite(&b, sizeof(b), 1, file);
1314 }
1315
1316 int cfwrite_vector(vector *vec, CFILE *file)
1317 {
1318         if(!cfwrite_float(vec->xyz.x, file)){
1319                 return 0;
1320         }
1321         if(!cfwrite_float(vec->xyz.y, file)){
1322                 return 0;
1323         }
1324         return cfwrite_float(vec->xyz.z, file);
1325 }
1326
1327 int cfwrite_angles(angles *ang, CFILE *file)
1328 {
1329         if(!cfwrite_float(ang->p, file)){
1330                 return 0;
1331         }
1332         if(!cfwrite_float(ang->b, file)){
1333                 return 0;
1334         }
1335         return cfwrite_float(ang->h, file);
1336 }
1337
1338 int cfwrite_char(char b, CFILE *file)
1339 {
1340         return cfwrite( &b, sizeof(b), 1, file);
1341 }
1342
1343 int cfwrite_string(const char *buf, CFILE *file)
1344 {
1345         if ( (!buf) || (buf && !buf[0]) ) {
1346                 return cfwrite_char(0, file);
1347         } 
1348         int len = strlen(buf);
1349         if(!cfwrite(buf, len, 1, file)){
1350                 return 0;
1351         }
1352         return cfwrite_char(0, file);                   // write out NULL termination                   
1353 }
1354
1355 int cfwrite_string_len(const char *buf, CFILE *file)
1356 {
1357         int len = strlen(buf);
1358
1359         if(!cfwrite_int(len, file)){
1360                 return 0;
1361         }
1362         if (len){
1363                 return cfwrite(buf,len,1,file);
1364         } 
1365
1366         return 1;
1367 }
1368
1369 // Get the filelength
1370 int cfilelength( CFILE * cfile )
1371 {
1372         Assert(cfile != NULL);
1373         Cfile_block *cb;
1374         Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1375         cb = &Cfile_block_list[cfile->id];      
1376
1377         // TODO: return length of memory mapped file
1378         Assert( !cb->data );
1379
1380         Assert(cb->fp != NULL);
1381
1382         // cb->size gets set at cfopen
1383         return cb->size;
1384 }
1385
1386 // cfwrite() writes to the file
1387 //
1388 // returns:   number of full elements actually written
1389 //            
1390 //
1391 int cfwrite(const void *buf, int elsize, int nelem, CFILE *cfile)
1392 {
1393         Assert(cfile != NULL);
1394         Assert(buf != NULL);
1395         Assert(elsize > 0);
1396         Assert(nelem > 0);
1397
1398         Cfile_block *cb;
1399         Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1400         cb = &Cfile_block_list[cfile->id];      
1401
1402         int size = elsize * nelem;
1403
1404         // cfwrite() not supported for memory-mapped files
1405         Assert( !cb->data );
1406
1407         Assert(cb->fp != NULL);
1408         Assert(cb->lib_offset == 0 );
1409         int bytes_written = fwrite( buf, 1, size, cb->fp );
1410
1411         if (bytes_written > 0) {
1412                 cb->raw_position += bytes_written;
1413         }
1414
1415         #if defined(CHECK_POSITION) && !defined(NDEBUG)
1416                 int tmp_offset = ftell(cb->fp) - cb->lib_offset;
1417                 Assert(tmp_offset == cb->raw_position);
1418         #endif
1419
1420         return bytes_written / elsize;
1421 }
1422
1423
1424 // cfputc() writes a character to a file
1425 //
1426 // returns:   success ==> returns character written
1427 //                                error   ==> EOF
1428 //
1429 int cfputc(int c, CFILE *cfile)
1430 {
1431         int result;
1432
1433         Assert(cfile != NULL);
1434         Cfile_block *cb;
1435         Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1436         cb = &Cfile_block_list[cfile->id];      
1437
1438         result = 0;
1439         // cfputc() not supported for memory-mapped files
1440         Assert( !cb->data );
1441
1442         Assert(cb->fp != NULL);
1443         result = fputc(c, cb->fp);
1444
1445         return result;  
1446 }
1447
1448
1449 // cfgetc() reads a character from a file
1450 //
1451 // returns:   success ==> returns character read
1452 //                                error   ==> EOF
1453 //
1454 int cfgetc(CFILE *cfile)
1455 {
1456         Assert(cfile != NULL);
1457         
1458         char tmp;
1459
1460         int result = cfread(&tmp, 1, 1, cfile );
1461         if ( result == 1 )      {
1462                 result = char(tmp);
1463         } else {
1464                 result = CF_EOF;
1465         }
1466
1467         return result;  
1468 }
1469
1470
1471
1472
1473
1474 // cfgets() reads a string from a file
1475 //
1476 // returns:   success ==> returns pointer to string
1477 //                                error   ==> NULL
1478 //
1479 char *cfgets(char *buf, int n, CFILE *cfile)
1480 {
1481         Assert(cfile != NULL);
1482         Assert(buf != NULL);
1483         Assert(n > 0 );
1484
1485         char * t = buf;
1486         int i, c;
1487
1488         for (i=0; i<n-1; i++ )  {
1489                 do {
1490                         char tmp_c;
1491
1492                         int ret = cfread( &tmp_c, 1, 1, cfile );
1493                         if ( ret != 1 ) {
1494                                 *buf = 0;
1495                                 if ( buf > t )  {               
1496                                         return t;
1497                                 } else {
1498                                         return NULL;
1499                                 }
1500                         }
1501                         c = int(tmp_c);
1502                 } while ( c == 13 );
1503                 *buf++ = char(c);
1504                 if ( c=='\n' ) break;
1505         }
1506         *buf++ = 0;
1507
1508         return  t;
1509 }
1510
1511 // cfputs() writes a string to a file
1512 //
1513 // returns:   success ==> non-negative value
1514 //                                error   ==> EOF
1515 //
1516 int cfputs(const char *str, CFILE *cfile)
1517 {
1518         Assert(cfile != NULL);
1519         Assert(str != NULL);
1520
1521         Cfile_block *cb;
1522         Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1523         cb = &Cfile_block_list[cfile->id];      
1524
1525         int result;
1526
1527         result = 0;
1528         // cfputs() not supported for memory-mapped files
1529         Assert( !cb->data );
1530         Assert(cb->fp != NULL);
1531         result = fputs(str, cb->fp);
1532
1533         return result;  
1534 }
1535
1536
1537 // 16 and 32 bit checksum stuff ----------------------------------------------------------
1538
1539 // CRC code for mission validation.  given to us by Kevin Bentley on 7/20/98.   Some sort of
1540 // checksumming code that he wrote a while ago.  
1541 #define CRC32_POLYNOMIAL                                        0xEDB88320L
1542 unsigned long CRCTable[256];
1543
1544 #define CF_CHKSUM_SAMPLE_SIZE                           512
1545
1546 // update cur_chksum with the chksum of the new_data of size new_data_size
1547 ushort cf_add_chksum_short(ushort seed, const char *buffer, int size)
1548 {
1549         const ubyte * ptr = (const ubyte *)buffer;
1550         unsigned int sum1,sum2;
1551
1552         sum1 = sum2 = (int)(seed);
1553
1554         while(size--)   {
1555                 sum1 += *ptr++;
1556                 if (sum1 >= 255 ) sum1 -= 255;
1557                 sum2 += sum1;
1558         }
1559         sum2 %= 255;
1560         
1561         return (unsigned short)((sum1<<8)+ sum2);
1562 }
1563
1564 // update cur_chksum with the chksum of the new_data of size new_data_size
1565 unsigned long cf_add_chksum_long(unsigned long seed, const char *buffer, int size)
1566 {
1567         unsigned long crc;
1568         unsigned const char *p;
1569         unsigned long temp1;
1570         unsigned long temp2;
1571
1572         p = (unsigned const char*)buffer;
1573         crc = seed;     
1574
1575         while (size--!=0){
1576           temp1 = (crc>>8)&0x00FFFFFFL;
1577           temp2 = CRCTable[((int)crc^*p++)&0xff];
1578           crc = temp1^temp2;
1579         }       
1580         
1581         return crc;
1582 }
1583
1584 void cf_chksum_long_init()
1585 {
1586         int i,j;
1587         unsigned long crc;      
1588
1589         for( i=0;i<=255;i++) {
1590                 crc=i;
1591                 for(j=8;j>0;j--) {
1592                         if(crc&1)
1593                                  crc=(crc>>1)^CRC32_POLYNOMIAL;
1594                         else
1595                                  crc>>=1;
1596                 }
1597                 CRCTable[i]=crc;
1598         }       
1599 }
1600
1601 // single function convenient to use for both short and long checksums
1602 // NOTE : only one of chk_short or chk_long must be non-NULL (indicating which checksum to perform)
1603 int cf_chksum_do(CFILE *cfile, ushort *chk_short, uint *chk_long, int max_size)
1604 {
1605         char cf_buffer[CF_CHKSUM_SAMPLE_SIZE];
1606         int is_long;
1607         int cf_len = 0;
1608         int cf_total;
1609         int read_size;
1610
1611         // determine whether we're doing a short or long checksum
1612         is_long = 0;
1613         if(chk_short){
1614                 Assert(!chk_long);              
1615                 *chk_short = 0;
1616         } else {
1617                 Assert(chk_long);
1618                 is_long = 1;
1619                 *chk_long = 0;
1620         }
1621
1622         // if max_size is -1, set it to be the size of the file
1623         if(max_size < 0){
1624                 cfseek(cfile, 0, SEEK_SET);
1625                 max_size = cfilelength(cfile);
1626         }
1627         
1628         cf_total = 0;
1629         do {
1630                 // determine how much we want to read
1631                 if((max_size - cf_total) >= CF_CHKSUM_SAMPLE_SIZE){
1632                         read_size = CF_CHKSUM_SAMPLE_SIZE;
1633                 } else {
1634                         read_size = max_size - cf_total;
1635                 }
1636
1637                 // read in some buffer
1638                 cf_len = cfread(cf_buffer, 1, read_size, cfile);
1639
1640                 // total we've read so far
1641                 cf_total += cf_len;
1642
1643                 // add the checksum
1644                 if(cf_len > 0){
1645                         // do the proper short or long checksum
1646                         if(is_long){
1647                                 *chk_long = cf_add_chksum_long(*chk_long, cf_buffer, cf_len);
1648                         } else {
1649                                 *chk_short = cf_add_chksum_short(*chk_short, cf_buffer, cf_len);
1650                         }
1651                 }
1652         } while((cf_len > 0) && (cf_total < max_size));
1653
1654         return 1;
1655 }
1656
1657 // get the 2 byte checksum of the passed filename - return 0 if operation failed, 1 if succeeded
1658 int cf_chksum_short(const char *filename, ushort *chksum, int max_size, int cf_type)
1659 {
1660         int ret_val;
1661         CFILE *cfile = NULL;            
1662         
1663         // zero the checksum
1664         *chksum = 0;
1665
1666         // attempt to open the file
1667         cfile = cfopen(filename,"rt",CFILE_NORMAL,cf_type);
1668         if(cfile == NULL){              
1669                 return 0;
1670         }
1671         
1672         // call the overloaded cf_chksum function()
1673         ret_val = cf_chksum_do(cfile, chksum, NULL, max_size);
1674
1675         // close the file down
1676         cfclose(cfile);
1677         cfile = NULL;
1678
1679         // return the result
1680         return ret_val;
1681 }
1682
1683 // get the 2 byte checksum of the passed file - return 0 if operation failed, 1 if succeeded
1684 // NOTE : preserves current file position
1685 int cf_chksum_short(CFILE *file, ushort *chksum, int max_size)
1686 {
1687         int ret_code;
1688         int start_pos;
1689         
1690         // Returns current position of file.
1691         start_pos = cftell(file);
1692         if(start_pos == -1){
1693                 return 0;
1694         }
1695         
1696         // move to the beginning of the file
1697         if(cfseek(file, 0, CF_SEEK_SET)){
1698                 return 0;
1699         }
1700         ret_code = cf_chksum_do(file, chksum, NULL, max_size);
1701         // move back to the start position
1702         cfseek(file, start_pos, CF_SEEK_SET);
1703
1704         return ret_code;
1705 }
1706
1707 // get the 32 bit CRC checksum of the passed filename - return 0 if operation failed, 1 if succeeded
1708 int cf_chksum_long(const char *filename, uint *chksum, int max_size, int cf_type)
1709 {
1710         int ret_val;
1711         CFILE *cfile = NULL;            
1712         
1713         // zero the checksum
1714         *chksum = 0;
1715
1716         // attempt to open the file
1717         cfile = cfopen(filename,"rt",CFILE_NORMAL,cf_type);
1718         if(cfile == NULL){              
1719                 return 0;
1720         }
1721         
1722         // call the overloaded cf_chksum function()
1723         ret_val = cf_chksum_do(cfile, NULL, chksum, max_size);
1724
1725         // close the file down
1726         cfclose(cfile);
1727         cfile = NULL;
1728
1729         // return the result
1730         return ret_val; 
1731 }
1732
1733 // get the 32 bit CRC checksum of the passed file - return 0 if operation failed, 1 if succeeded
1734 // NOTE : preserves current file position
1735 int cf_chksum_long(CFILE *file, uint *chksum, int max_size)
1736 {
1737         int ret_code;
1738         int start_pos;
1739         
1740         // Returns current position of file.
1741         start_pos = cftell(file);
1742         if(start_pos == -1){
1743                 return 0;
1744         }
1745         
1746         // move to the beginning of the file
1747         if(cfseek(file, 0, CF_SEEK_SET)){
1748                 return 0;
1749         }
1750         ret_code = cf_chksum_do(file, NULL, chksum, max_size);
1751         // move back to the start position
1752         cfseek(file, start_pos, CF_SEEK_SET);
1753
1754         return ret_code;
1755 }
1756
1757
1758 // Flush the open file buffer
1759 //
1760 // exit: 0 - success
1761 //                      1 - failure
1762 int cflush(CFILE *cfile)
1763 {
1764         Assert(cfile != NULL);
1765         Cfile_block *cb;
1766         Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1767         cb = &Cfile_block_list[cfile->id];      
1768
1769         // not supported for memory mapped files
1770         Assert( !cb->data );
1771
1772         Assert(cb->fp != NULL);
1773         return fflush(cb->fp);
1774 }
1775
1776 // fill in Cfile_root_dir[] and Cfile_user_dir[]
1777 // this can be called at any time, even before cfile_init()
1778 //  returns: non-zero on error
1779 int cfile_init_paths()
1780 {
1781         if ( strlen(Cfile_root_dir) && strlen(Cfile_user_dir) ) {
1782                 return 0;
1783         }
1784
1785         char *t_path = SDL_GetBasePath();
1786
1787         // make sure we have something
1788         if (t_path == NULL) {
1789                 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Error trying to determine executable directory!", NULL);
1790                 return 1;
1791         }
1792
1793         // size check
1794         if ( strlen(t_path) >= CFILE_ROOT_DIRECTORY_LEN ) {
1795                 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Executable path is too long!", NULL);
1796                 return 1;
1797         }
1798
1799         // set root directory
1800         strcpy(Cfile_root_dir, t_path);
1801         // free SDL copy
1802         SDL_free(t_path);
1803         t_path = NULL;
1804
1805         // are we in a root directory?
1806         if ( cfile_in_root_dir(Cfile_root_dir) ) {
1807                 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Freespace2/Fred2 cannot be run from a drive root directory!", NULL);
1808                 return 1;
1809         }
1810
1811         // now for the user/pref directory, the writable location
1812         char *u_path = SDL_GetPrefPath(Osreg_company_name, Osreg_title);
1813
1814         // make sure we have something
1815         if (u_path == NULL) {
1816                 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Error trying to determine preferences directory!", NULL);
1817                 return 1;
1818         }
1819
1820         // size check
1821         if ( strlen(u_path) >= CFILE_ROOT_DIRECTORY_LEN ) {
1822                 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Preferences path is too long!", NULL);
1823                 return 1;
1824         }
1825
1826         // set user/pref directory
1827         strcpy(Cfile_user_dir, u_path);
1828         // free SDL copy
1829         SDL_free(u_path);
1830         u_path = NULL;
1831
1832         return 0;
1833 }