]> icculus.org git repositories - taylor/freespace2.git/blob - src/cfile/cfile.cpp
remove support for memory-mapped files
[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 <dirent.h>
224 #include <fnmatch.h>
225 #include <sys/stat.h>
226 #include <sys/types.h>
227 #endif
228
229 #include "pstypes.h"
230 #include "cfile.h"
231 #include "encrypt.h"
232 //#include "outwnd.h"
233 //#include "vecmat.h"
234 //#include "timer.h"
235 #include "cfilesystem.h"
236 #include "cfilearchive.h"
237 #include "osapi.h"
238 #include "osregistry.h"
239
240 char Cfile_root_dir[CFILE_ROOT_DIRECTORY_LEN] = "";
241 char Cfile_user_dir[CFILE_ROOT_DIRECTORY_LEN] = "";
242
243 // During cfile_init, verify that Pathtypes[n].index == n for each item
244 // Each path must have a valid parent that can be tracable all the way back to the root 
245 // so that we can create directories when we need to.
246 //
247 cf_pathtype Pathtypes[CF_MAX_PATH_TYPES]  = {
248         // What type this is          Path                             Extensions              Parent type
249         { CF_TYPE_INVALID,                              NULL,                                                                           NULL,                                                   CF_TYPE_INVALID },
250         // Root must be index 1!!       
251         { CF_TYPE_ROOT,                                 "",                                                                             ".mve",                                                 CF_TYPE_ROOT    },
252         { CF_TYPE_DATA,                                 "Data",                                                                 ".cfg .log .txt",                       CF_TYPE_ROOT    },
253         { CF_TYPE_MAPS,                                 "Data" DIR_SEPARATOR_STR "Maps",                                                        ".pcx .ani .tga",                       CF_TYPE_DATA    },
254         { CF_TYPE_TEXT,                                 "Data" DIR_SEPARATOR_STR "Text",                                                        ".txt .net",                            CF_TYPE_DATA    },
255 #ifdef MAKE_FS1
256         { CF_TYPE_MISSIONS,                             "Data" DIR_SEPARATOR_STR "Missions",                                            ".fsm .fsc .ntl .ssv",  CF_TYPE_DATA    },
257 #else
258         { CF_TYPE_MISSIONS,                             "Data" DIR_SEPARATOR_STR "Missions",                                            ".fs2 .fc2 .ntl .ssv",  CF_TYPE_DATA    },
259 #endif
260         { CF_TYPE_MODELS,                                       "Data" DIR_SEPARATOR_STR "Models",                                              ".pof",                                         CF_TYPE_DATA    },
261         { CF_TYPE_TABLES,                                       "Data" DIR_SEPARATOR_STR "Tables",                                              ".tbl",                                         CF_TYPE_DATA    },
262         { CF_TYPE_SOUNDS,                                       "Data" DIR_SEPARATOR_STR "Sounds",                                              ".wav",                                         CF_TYPE_DATA    },
263         { CF_TYPE_SOUNDS_8B22K,                 "Data" DIR_SEPARATOR_STR "Sounds" DIR_SEPARATOR_STR "8b22k",                            ".wav",                                         CF_TYPE_SOUNDS  },
264         { CF_TYPE_SOUNDS_16B11K,                "Data" DIR_SEPARATOR_STR "Sounds" DIR_SEPARATOR_STR "16b11k",                           ".wav",                                         CF_TYPE_SOUNDS  },
265         { CF_TYPE_VOICE,                                        "Data" DIR_SEPARATOR_STR "Voice",                                                       "",                                                     CF_TYPE_DATA    },
266 #ifdef MAKE_FS1
267         { CF_TYPE_VOICE_BRIEFINGS,              "Data" DIR_SEPARATOR_STR "Voice" DIR_SEPARATOR_STR "Briefings",                 ".wav",                                         CF_TYPE_VOICE   },
268 #else
269         { CF_TYPE_VOICE_BRIEFINGS,              "Data" DIR_SEPARATOR_STR "Voice" DIR_SEPARATOR_STR "Briefing",                  ".wav",                                         CF_TYPE_VOICE   },
270 #endif
271         { CF_TYPE_VOICE_CMD_BRIEF,              "Data" DIR_SEPARATOR_STR "Voice" DIR_SEPARATOR_STR "Command_briefings",".wav",                                          CF_TYPE_VOICE   },
272 #ifdef MAKE_FS1
273         { CF_TYPE_VOICE_DEBRIEFINGS,    "Data" DIR_SEPARATOR_STR "Voice" DIR_SEPARATOR_STR "Debriefings",                       ".wav",                                         CF_TYPE_VOICE   },
274 #else
275         { CF_TYPE_VOICE_DEBRIEFINGS,    "Data" DIR_SEPARATOR_STR "Voice" DIR_SEPARATOR_STR "Debriefing",                        ".wav",                                         CF_TYPE_VOICE   },
276 #endif
277         { CF_TYPE_VOICE_PERSONAS,               "Data" DIR_SEPARATOR_STR "Voice" DIR_SEPARATOR_STR "Personas",                  ".wav",                                         CF_TYPE_VOICE   },
278         { CF_TYPE_VOICE_SPECIAL,                "Data" DIR_SEPARATOR_STR "Voice" DIR_SEPARATOR_STR "Special",                           ".wav",                                         CF_TYPE_VOICE   },
279         { CF_TYPE_VOICE_TRAINING,               "Data" DIR_SEPARATOR_STR "Voice" DIR_SEPARATOR_STR "Training",                  ".wav",                                         CF_TYPE_VOICE   },
280         { CF_TYPE_MUSIC,                                        "Data" DIR_SEPARATOR_STR "Music",                                                       ".wav",                                         CF_TYPE_VOICE   },
281         { CF_TYPE_MOVIES,                                       "Data" DIR_SEPARATOR_STR "Movies",                                              ".mve .msb",                            CF_TYPE_DATA    },
282         { CF_TYPE_INTERFACE,                            "Data" DIR_SEPARATOR_STR "Interface",                                   ".pcx .ani .tga",                       CF_TYPE_DATA    },
283         { CF_TYPE_FONT,                                 "Data" DIR_SEPARATOR_STR "Fonts",                                                       ".vf",                                          CF_TYPE_DATA    },
284         { CF_TYPE_EFFECTS,                              "Data" DIR_SEPARATOR_STR "Effects",                                             ".ani .pcx .neb .tga",  CF_TYPE_DATA    },
285         { CF_TYPE_HUD,                                          "Data" DIR_SEPARATOR_STR "Hud",                                                 ".ani .pcx .tga",                       CF_TYPE_DATA    },
286         { CF_TYPE_PLAYER_MAIN,                  "Data" DIR_SEPARATOR_STR "Players",                                             "",                                                     CF_TYPE_DATA    },
287         { CF_TYPE_PLAYER_IMAGES_MAIN,   "Data" DIR_SEPARATOR_STR "Players" DIR_SEPARATOR_STR "Images",                  ".pcx",                                         CF_TYPE_PLAYER_MAIN     },
288         { CF_TYPE_CACHE,                                        "Data" DIR_SEPARATOR_STR "Cache",                                                       ".clr .tmp",                            CF_TYPE_DATA    },      //clr=cached color
289         { CF_TYPE_PLAYERS,                              "Data" DIR_SEPARATOR_STR "Players",                                             ".hcf",                                         CF_TYPE_DATA    },
290         { CF_TYPE_SINGLE_PLAYERS,               "Data" DIR_SEPARATOR_STR "Players" DIR_SEPARATOR_STR "Single",                  ".plr .csg .css",                       CF_TYPE_PLAYERS },
291         { CF_TYPE_MULTI_PLAYERS,                "Data" DIR_SEPARATOR_STR "Players" DIR_SEPARATOR_STR "Multi",                           ".plr",                                         CF_TYPE_DATA    },
292         { CF_TYPE_MULTI_CACHE,                  "Data" DIR_SEPARATOR_STR "MultiData",                                   ".pcx .fs2",                            CF_TYPE_DATA    },
293         { CF_TYPE_CONFIG,                                       "Data" DIR_SEPARATOR_STR "Config",                                              ".cfg",                                         CF_TYPE_DATA    },
294         { CF_TYPE_SQUAD_IMAGES_MAIN,    "Data" DIR_SEPARATOR_STR "Players" DIR_SEPARATOR_STR "Squads",                  ".pcx",                                         CF_TYPE_DATA    },
295         { CF_TYPE_DEMOS,                                        "Data" DIR_SEPARATOR_STR "Demos",                                                       ".fsd",                                         CF_TYPE_DATA    },
296         { CF_TYPE_CBANIMS,                              "Data" DIR_SEPARATOR_STR "CBAnims",                                             ".ani",                                         CF_TYPE_DATA    },
297         { CF_TYPE_INTEL_ANIMS,                  "Data" DIR_SEPARATOR_STR "IntelAnims",                                  ".ani",                                         CF_TYPE_DATA    },
298 };
299
300
301 #define CFILE_STACK_MAX 8
302
303 int cfile_inited = 0;
304
305 Cfile_block Cfile_block_list[MAX_CFILE_BLOCKS];
306 CFILE Cfile_list[MAX_CFILE_BLOCKS];
307
308 //
309 // Function prototypes for internally-called functions
310 //
311 int cfget_cfile_block();
312 CFILE *cf_open_fill_cfblock(FILE * fp, int type);
313 CFILE *cf_open_packed_cfblock(FILE *fp, int type, int offset, int size);
314 void cf_chksum_long_init();
315
316 void cfile_close()
317 {
318         cf_free_secondary_filelist();
319 }
320
321 // determine if the given path is in a root directory (c:\  or  c:\freespace2.exe  or  c:\fred2.exe   etc)
322 int cfile_in_root_dir(char *exe_path)
323 {
324         int token_count = 0;
325         char path_copy[2048] = "";
326         char *tok;
327
328         // bogus
329         if(exe_path == NULL){
330                 return 1;
331         }
332
333         // copy the path
334         memset(path_copy, 0, 2048);
335         SDL_strlcpy(path_copy, exe_path, sizeof(path_copy));
336
337         // count how many slashes there are in the path
338         tok = strtok(path_copy, DIR_SEPARATOR_STR);
339         if(tok == NULL){
340                 return 1;
341         }       
342         do {
343                 token_count++;
344                 tok = strtok(NULL, DIR_SEPARATOR_STR);
345         } while(tok != NULL);
346                 
347         // root directory if we have <= 1 slash
348         if(token_count <= 2){
349                 return 1;
350         }
351
352         // not-root directory
353         return 0;
354 }
355
356 // cfile_init() initializes the cfile system.  Called once at application start.
357 //
358 //      returns:  success ==> 0
359 //           error   ==> non-zero
360 //
361 int cfile_init()
362 {
363         int i;
364
365         // initialize encryption
366         encrypt_init(); 
367
368         if ( !cfile_inited ) {
369                 // initialize root and user paths (may have been done already)
370                 if ( cfile_init_paths() ) {
371                         return 1;
372                 }
373
374                 cfile_inited = 1;
375
376                 for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
377                         Cfile_block_list[i].type = CFILE_BLOCK_UNUSED;
378                 }
379
380                 const char *extras_dir = os_config_read_string(NULL, "ExtrasPath", NULL);
381
382                 if ( extras_dir && (strlen(extras_dir) >= MAX_PATH_LEN) ) {
383                         extras_dir = NULL;
384                 }
385
386                 cf_build_secondary_filelist(extras_dir);
387
388                 // 32 bit CRC table init
389                 cf_chksum_long_init();
390
391
392
393                 atexit( cfile_close );
394         }
395
396         return 0;
397 }
398
399
400 // flush (delete all files in) the passed directory (by type), return the # of files deleted
401 // NOTE : WILL NOT DELETE READ-ONLY FILES
402 int cfile_flush_dir(int dir_type)
403 {
404         char filespec[MAX_PATH_LEN];
405         int del_count;
406
407         SDL_assert( CF_TYPE_SPECIFIED(dir_type) );
408
409         cf_create_default_path_string(filespec, dir_type);
410
411         // proceed to delete the files
412         del_count = 0;
413
414 #ifdef PLAT_UNIX
415         DIR *dirp;
416         struct dirent *dir;
417
418         dirp = opendir(filespec);
419         if (dirp) {
420                 while ( (dir = readdir(dirp)) != NULL ) {
421                         if ( !fnmatch("*", dir->d_name, 0) ) {
422                                 char fn[MAX_PATH_LEN];
423                                 SDL_snprintf(fn, MAX_PATH_LEN, "%s/%s", filespec, dir->d_name);
424
425                                 struct stat buf;
426                                 if (stat(fn, &buf) == -1) {
427                                         continue;
428                                 }
429
430                                 if (!S_ISREG(buf.st_mode)) {
431                                         continue;
432                                 }
433
434                                 // delete the file
435                                 cf_delete(dir->d_name, dir_type);
436
437                                 // increment the deleted count
438                                 del_count++;
439                         }
440                 }
441
442                 closedir(dirp);
443         }
444 #else
445         int find_handle;
446         _finddata_t find;
447
448         SDL_strlcat( filespec, "*", sizeof(filespec) );
449
450         find_handle = _findfirst( filespec, &find );
451
452         if (find_handle != -1) {
453                 do {
454                         if (!(find.attrib & _A_SUBDIR) && !(find.attrib & _A_RDONLY)) {
455                                 // delete the file
456                                 cf_delete(find.name, dir_type);
457
458                                 // increment the deleted count
459                                 del_count++;
460                         }
461                 } while (!_findnext(find_handle, &find));
462
463                 _findclose( find_handle );
464         }
465 #endif
466
467         // return the # of files deleted
468         return del_count;
469 }
470
471
472 // add the given extention to a filename (or filepath) if it doesn't already have this
473 // extension.
474 //    filename = name of filename or filepath to process
475 //    ext = extension to add.  Must start with the period
476 //    Returns: new filename or filepath with extension.
477 char *cf_add_ext(const char *filename, const char *ext)
478 {
479         int flen, elen;
480         static char path[MAX_PATH_LEN];
481
482         flen = strlen(filename);
483         elen = strlen(ext);
484         SDL_assert(flen < MAX_PATH_LEN);
485         SDL_strlcpy(path, filename, sizeof(path));
486         if ((flen < 4) || SDL_strcasecmp(path + flen - elen, ext)) {
487                 SDL_assert(flen + elen < MAX_PATH_LEN);
488                 SDL_strlcat(path, ext, sizeof(path));
489         }
490
491         return path;
492 }
493
494 // Deletes a file.
495 void cf_delete( const char *filename, int dir_type )
496 {
497         char longname[MAX_PATH_LEN];
498
499         SDL_assert( CF_TYPE_SPECIFIED(dir_type) );
500
501         cf_create_default_path_string( longname, dir_type, filename );
502
503         FILE *fp = fopen(longname, "rb");
504         if (fp) {
505                 // delete the file
506                 fclose(fp);
507                 unlink(longname);
508         }
509
510 }
511
512
513 // Same as _access function to read a file's access bits
514 int cf_access( const char *filename, int dir_type, int mode )
515 {
516         char longname[MAX_PATH_LEN];
517
518         SDL_assert( CF_TYPE_SPECIFIED(dir_type) );
519
520         cf_create_default_path_string( longname, dir_type, filename );
521
522         return access(longname,mode);
523 }
524
525
526 // Returns 1 if file exists, 0 if not.
527 int cf_exist( const char *filename, int dir_type )
528 {
529         char longname[MAX_PATH_LEN];
530
531         SDL_assert( CF_TYPE_SPECIFIED(dir_type) );
532
533         cf_create_default_path_string( longname, dir_type, filename );
534
535         FILE *fp = fopen(longname, "rb");
536         if (fp) {
537                 fclose(fp);
538                 return 1;
539         }
540
541         return 0;
542 }
543
544 int cf_rename(const char *old_name, const char *name, int dir_type)
545 {
546         SDL_assert( CF_TYPE_SPECIFIED(dir_type) );
547
548         int ret_code;
549         char old_longname[MAX_PATH_LEN];
550         char new_longname[MAX_PATH_LEN];
551         
552         cf_create_default_path_string( old_longname, dir_type, old_name );
553         cf_create_default_path_string( new_longname, dir_type, name );
554
555         ret_code = rename(old_longname, new_longname );         
556         if(ret_code != 0){
557                 switch(errno){
558                 case EACCES :
559                         return CF_RENAME_FAIL_ACCESS;
560                 case ENOENT :
561                 default:
562                         return CF_RENAME_FAIL_EXIST;
563                 }
564         }
565
566         return CF_RENAME_SUCCESS;
567         
568
569 }
570
571 // Creates the directory path if it doesn't exist. Even creates all its
572 // parent paths.
573 void cf_create_directory( int dir_type )
574 {
575         int num_dirs = 0;
576         int dir_tree[CF_MAX_PATH_TYPES];
577         char longname[MAX_PATH_LEN];
578
579         SDL_assert( CF_TYPE_SPECIFIED(dir_type) );
580
581         int current_dir = dir_type;
582
583         do {
584                 SDL_assert( num_dirs < CF_MAX_PATH_TYPES );             // Invalid Pathtypes data?
585
586                 dir_tree[num_dirs++] = current_dir;
587                 current_dir = Pathtypes[current_dir].parent_index;
588
589         } while( current_dir != CF_TYPE_ROOT );
590
591         
592         int i;
593
594         for (i=num_dirs-1; i>=0; i-- )  {
595                 cf_create_default_path_string( longname, dir_tree[i], NULL );
596
597                 if ( mkdir(longname, 0700) == 0 )       {
598                         mprintf(( "CFILE: Created new directory '%s'\n", longname ));
599                 }
600         }
601
602
603 }
604
605
606 // cfopen()
607 //
608 // parameters:  *filepath ==> name of file to open (may be path+name)
609 //              *mode     ==> specifies how file should be opened (eg "rb" for read binary)
610 //                            passing NULL to mode deletes the file if it exists and returns NULL
611 //               type     ==> CFILE_NORMAL
612 //                                        dir_type      =>      override extension check, value is one of CF_TYPE* #defines
613 //
614 //               NOTE: type parameter is an optional parameter.  The default value is CFILE_NORMAL
615 //
616 //
617 // returns:             success ==> address of CFILE structure
618 //                                      error   ==> NULL
619 //
620
621 CFILE *cfopen(const char *file_path, const char *mode, int type, int dir_type, bool localize)
622 {
623         char longname[MAX_PATH_LEN];
624
625 //      nprintf(("CFILE", "CFILE -- trying to open %s\n", file_path ));
626 // #if !defined(MULTIPLAYER_BETA_BUILD) && !defined(FS2_DEMO)
627
628         //================================================
629         // Check that all the parameters make sense
630         SDL_assert(file_path && strlen(file_path));
631         SDL_assert( mode != NULL );
632
633         //===========================================================
634         // If in write mode, just try to open the file straight off
635         // the harddisk.  No fancy packfile stuff here!
636         
637         if ( SDL_strchr(mode,'w') )     {
638 #ifdef PLAT_UNIX
639                 const char *toks = "/";
640 #else
641                 const char *toks = "/\\:";
642 #endif
643
644                 // For write-only files, require a full path or a path type
645                 if ( strpbrk(file_path, toks) ) {
646                         // Full path given?
647                         SDL_strlcpy(longname, file_path, sizeof(longname));
648                 } else {
649                         // Path type given?
650                         SDL_assert( dir_type != CF_TYPE_ANY );
651
652                         // Create the directory if necessary
653                         cf_create_directory( dir_type );
654
655                         cf_create_default_path_string( longname, dir_type, file_path );
656                 }
657
658                 // JOHN: TODO, you should create the path if it doesn't exist.
659                                 
660                 FILE *fp = fopen(longname, mode);
661                 if (fp) {
662                         return cf_open_fill_cfblock(fp, dir_type);
663                 }
664                 return NULL;
665         } 
666
667
668         //================================================
669         // Search for file on disk, on cdrom, or in a packfile
670
671         int offset, size;
672         char copy_file_path[MAX_PATH_LEN];  // FIX change in memory from cf_find_file_location
673         SDL_strlcpy(copy_file_path, file_path, sizeof(copy_file_path));
674
675
676         if ( cf_find_file_location( copy_file_path, dir_type, longname, &size, &offset, localize ) )    {
677                 // Fount it, now create a cfile out of it
678                 FILE *fp = fopen( longname, "rb" );
679
680                 if ( fp )       {
681                         if ( offset )   {
682                                 // Found it in a pack file
683                                 return cf_open_packed_cfblock(fp, dir_type, offset, size );
684                         } else {
685                                 // Found it in a normal file
686                                 return cf_open_fill_cfblock(fp, dir_type);
687                         }
688                 }
689         }
690
691         return NULL;
692 }
693
694
695 // ------------------------------------------------------------------------
696 // ctmpfile() 
697 //
698 // Open up a temporary file.  A unique name is automatically generated.  The
699 // file will be automatically deleted when file is closed.
700 //
701 // return:              NULL                                    =>              tmp file could not be opened
702 //                                      pointer to CFILE        =>              tmp file successfully opened
703 //
704 CFILE *ctmpfile()
705 {
706         FILE    *fp;
707         fp = tmpfile();
708         if ( fp )
709                 return cf_open_fill_cfblock(fp, 0);
710         else
711                 return NULL;
712 }
713
714
715
716 // cfget_cfile_block() will try to find an empty Cfile_block structure in the
717 //      Cfile_block_list[] array and return the index.
718 //
719 // returns:   success ==> index in Cfile_block_list[] array
720 //            failure ==> -1
721 //
722 int cfget_cfile_block()
723 {       
724         int i;
725         Cfile_block *cb;
726
727         for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
728                 cb = &Cfile_block_list[i];
729                 if ( cb->type == CFILE_BLOCK_UNUSED ) {
730                         cb->fp = NULL;
731                         cb->type = CFILE_BLOCK_USED;
732                         return i;
733                 }
734         }
735
736         // If we've reached this point, a free Cfile_block could not be found
737         nprintf(("Warning","A free Cfile_block could not be found.\n"));
738         SDL_assert(0);  // out of free cfile blocks
739         return -1;                      
740 }
741
742
743 // cfclose() closes the file
744 //
745 // returns:   success ==> 0
746 //                                failure ==> EOF
747 //
748 int cfclose( CFILE * cfile )
749 {
750         int result;
751
752         SDL_assert(cfile != NULL);
753         Cfile_block *cb;
754         SDL_assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
755         cb = &Cfile_block_list[cfile->id];      
756
757         result = 0;
758
759         if (cb->fp != NULL) {
760                 SDL_assert(cb->fp != NULL);
761                 result = fclose(cb->fp);
762         } else {
763                 // VP  do nothing
764         }
765
766         cb->type = CFILE_BLOCK_UNUSED;
767         return result;
768 }
769
770
771
772
773 // cf_open_fill_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
774 // for the case of a file being opened by cf_open();
775 //
776 // returns:   success ==> ptr to CFILE structure.  
777 //            error   ==> NULL
778 //
779 CFILE *cf_open_fill_cfblock(FILE *fp, int type)
780 {
781         int cfile_block_index;
782
783         cfile_block_index = cfget_cfile_block();
784         if ( cfile_block_index == -1 ) {
785                 return NULL;
786         } else {
787                 CFILE *cfp;
788                 Cfile_block *cfbp;
789                 cfbp = &Cfile_block_list[cfile_block_index];
790                 cfp = &Cfile_list[cfile_block_index];;
791                 cfp->id = cfile_block_index;
792                 cfp->version = 0;
793                 cfbp->fp = fp;
794                 cfbp->dir_type = type;
795                 
796                 cf_init_lowlevel_read_code(cfp,0,filelength(fileno(fp)) );
797
798                 return cfp;
799         }
800 }
801
802
803 // cf_open_packed_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
804 // for the case of a file being opened by cf_open();
805 //
806 // returns:   success ==> ptr to CFILE structure.  
807 //            error   ==> NULL
808 //
809 CFILE *cf_open_packed_cfblock(FILE *fp, int type, int offset, int size)
810 {
811         // Found it in a pack file
812         int cfile_block_index;
813         
814         cfile_block_index = cfget_cfile_block();
815         if ( cfile_block_index == -1 ) {
816                 return NULL;
817         } else {
818                 CFILE *cfp;
819                 Cfile_block *cfbp;
820                 cfbp = &Cfile_block_list[cfile_block_index];
821         
822                 cfp = &Cfile_list[cfile_block_index];
823                 cfp->id = cfile_block_index;
824                 cfp->version = 0;
825                 cfbp->fp = fp;
826                 cfbp->dir_type = type;
827
828                 cf_init_lowlevel_read_code(cfp,offset, size );
829
830                 return cfp;
831         }
832
833 }
834
835
836 int cf_get_dir_type(CFILE *cfile)
837 {
838         return Cfile_block_list[cfile->id].dir_type;
839 }
840
841
842 // version number of opened file.  Will be 0 unless you put something else here after you
843 // open a file.  Once set, you can use minimum version numbers with the read functions.
844 void cf_set_version( CFILE * cfile, int version )
845 {
846         SDL_assert(cfile != NULL);
847
848         cfile->version = version;
849 }
850
851 // routines to read basic data types from CFILE's.  Put here to
852 // simplify mac/pc reading from cfiles.
853 #ifdef __APPLE__
854 #include <stddef.h>
855 #endif
856
857 float cfread_float(CFILE *file, int ver, float deflt)
858 {
859         float f;
860
861         if (file->version < ver)
862                 return deflt;
863
864         if (cfread( &f, sizeof(f), 1, file) != 1)
865                 return deflt;
866
867     f = INTEL_FLOAT(f);
868         return f;
869 }
870
871 int cfread_int(CFILE *file, int ver, int deflt)
872 {
873         int i;
874
875         if (file->version < ver)
876                 return deflt;
877
878         if (cfread( &i, sizeof(i), 1, file) != 1)
879                 return deflt;
880
881         i = INTEL_INT(i);
882         return i;
883 }
884
885 uint cfread_uint(CFILE *file, int ver, uint deflt)
886 {
887         uint i;
888
889         if (file->version < ver)
890                 return deflt;
891
892         if (cfread( &i, sizeof(i), 1, file) != 1)
893                 return deflt;
894
895         i = INTEL_INT(i);
896         return i;
897 }
898
899 short cfread_short(CFILE *file, int ver, short deflt)
900 {
901         short s;
902
903         if (file->version < ver)
904                 return deflt;
905
906         if (cfread( &s, sizeof(s), 1, file) != 1)
907                 return deflt;
908
909         s = INTEL_SHORT(s);
910         return s;
911 }
912
913 ushort cfread_ushort(CFILE *file, int ver, ushort deflt)
914 {
915         ushort s;
916
917         if (file->version < ver)
918                 return deflt;
919
920         if (cfread( &s, sizeof(s), 1, file) != 1)
921                 return deflt;
922
923         s = INTEL_SHORT(s);
924         return s;
925 }
926
927 ubyte cfread_ubyte(CFILE *file, int ver, ubyte deflt)
928 {
929         ubyte b;
930
931         if (file->version < ver)
932                 return deflt;
933
934         if (cfread( &b, sizeof(b), 1, file) != 1)
935                 return deflt;
936
937         return b;
938 }
939
940 void cfread_vector(vector *vec, CFILE *file, int ver, vector *deflt)
941 {
942         if (file->version < ver) {
943                 if (deflt)
944                         *vec = *deflt;
945                 else
946                         vec->xyz.x = vec->xyz.y = vec->xyz.z = 0.0f;
947
948                 return;
949         }
950
951         vec->xyz.x = cfread_float(file, ver, deflt ? deflt->xyz.x : 0.0f);
952         vec->xyz.y = cfread_float(file, ver, deflt ? deflt->xyz.y : 0.0f);
953         vec->xyz.z = cfread_float(file, ver, deflt ? deflt->xyz.z : 0.0f);
954 }
955         
956 void cfread_angles(angles *ang, CFILE *file, int ver, angles *deflt)
957 {
958         if (file->version < ver) {
959                 if (deflt)
960                         *ang = *deflt;
961                 else
962                         ang->p = ang->b = ang->h = 0.0f;
963
964                 return;
965         }
966
967         ang->p = cfread_float(file, ver, deflt ? deflt->p : 0.0f);
968         ang->b = cfread_float(file, ver, deflt ? deflt->b : 0.0f);
969         ang->h = cfread_float(file, ver, deflt ? deflt->h : 0.0f);
970 }
971
972 char cfread_char(CFILE *file, int ver, char deflt)
973 {
974         char b;
975
976         if (file->version < ver)
977                 return deflt;
978
979         if (cfread( &b, sizeof(b), 1, file) != 1)
980                 return deflt;
981
982         return b;
983 }
984
985 void cfread_string(char *buf, int n, CFILE *file)
986 {
987         char c;
988
989         do {
990                 c = cfread_char(file);
991                 if ( n > 0 )    {
992                         *buf++ = c;
993                         n--;
994                 }
995         } while (c != 0 );
996 }
997
998 void cfread_string_len(char *buf,int n, CFILE *file)
999 {
1000         int len;
1001         len = cfread_int(file);
1002         SDL_assert( len < n );
1003         if (len)
1004                 cfread(buf, len, 1, file);
1005
1006         buf[len] = 0;
1007 }
1008
1009 // equivalent write functions of above read functions follow
1010
1011 int cfwrite_float(float f, CFILE *file)
1012 {
1013     f = INTEL_FLOAT(f);
1014         return cfwrite(&f, sizeof(f), 1, file);
1015 }
1016
1017 int cfwrite_int(int i, CFILE *file)
1018 {
1019         i = INTEL_INT(i);
1020         return cfwrite(&i, sizeof(i), 1, file);
1021 }
1022
1023 int cfwrite_uint(uint i, CFILE *file)
1024 {
1025         i = INTEL_INT(i);
1026         return cfwrite(&i, sizeof(i), 1, file);
1027 }
1028
1029 int cfwrite_short(short s, CFILE *file)
1030 {
1031         s = INTEL_SHORT(s);
1032         return cfwrite(&s, sizeof(s), 1, file);
1033 }
1034
1035 int cfwrite_ushort(ushort s, CFILE *file)
1036 {
1037         s = INTEL_SHORT(s);
1038         return cfwrite(&s, sizeof(s), 1, file);
1039 }
1040
1041 int cfwrite_ubyte(ubyte b, CFILE *file)
1042 {
1043         return cfwrite(&b, sizeof(b), 1, file);
1044 }
1045
1046 int cfwrite_vector(vector *vec, CFILE *file)
1047 {
1048         if(!cfwrite_float(vec->xyz.x, file)){
1049                 return 0;
1050         }
1051         if(!cfwrite_float(vec->xyz.y, file)){
1052                 return 0;
1053         }
1054         return cfwrite_float(vec->xyz.z, file);
1055 }
1056
1057 int cfwrite_angles(angles *ang, CFILE *file)
1058 {
1059         if(!cfwrite_float(ang->p, file)){
1060                 return 0;
1061         }
1062         if(!cfwrite_float(ang->b, file)){
1063                 return 0;
1064         }
1065         return cfwrite_float(ang->h, file);
1066 }
1067
1068 int cfwrite_char(char b, CFILE *file)
1069 {
1070         return cfwrite( &b, sizeof(b), 1, file);
1071 }
1072
1073 int cfwrite_string(const char *buf, CFILE *file)
1074 {
1075         if ( (!buf) || (buf && !buf[0]) ) {
1076                 return cfwrite_char(0, file);
1077         } 
1078         int len = strlen(buf);
1079         if(!cfwrite(buf, len, 1, file)){
1080                 return 0;
1081         }
1082         return cfwrite_char(0, file);                   // write out NULL termination                   
1083 }
1084
1085 int cfwrite_string_len(const char *buf, CFILE *file)
1086 {
1087         int len = strlen(buf);
1088
1089         if(!cfwrite_int(len, file)){
1090                 return 0;
1091         }
1092         if (len){
1093                 return cfwrite(buf,len,1,file);
1094         } 
1095
1096         return 1;
1097 }
1098
1099 // Get the filelength
1100 int cfilelength( CFILE * cfile )
1101 {
1102         SDL_assert(cfile != NULL);
1103         Cfile_block *cb;
1104         SDL_assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1105         cb = &Cfile_block_list[cfile->id];      
1106
1107         SDL_assert(cb->fp != NULL);
1108
1109         // cb->size gets set at cfopen
1110         return cb->size;
1111 }
1112
1113 // cfwrite() writes to the file
1114 //
1115 // returns:   number of full elements actually written
1116 //            
1117 //
1118 int cfwrite(const void *buf, int elsize, int nelem, CFILE *cfile)
1119 {
1120         SDL_assert(cfile != NULL);
1121         SDL_assert(buf != NULL);
1122         SDL_assert(elsize > 0);
1123         SDL_assert(nelem > 0);
1124
1125         Cfile_block *cb;
1126         SDL_assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1127         cb = &Cfile_block_list[cfile->id];      
1128
1129         int size = elsize * nelem;
1130
1131         SDL_assert(cb->fp != NULL);
1132         SDL_assert(cb->lib_offset == 0 );
1133         int bytes_written = fwrite( buf, 1, size, cb->fp );
1134
1135         if (bytes_written > 0) {
1136                 cb->raw_position += bytes_written;
1137         }
1138
1139         #if defined(CHECK_POSITION) && !defined(NDEBUG)
1140                 int tmp_offset = ftell(cb->fp) - cb->lib_offset;
1141                 SDL_assert(tmp_offset == cb->raw_position);
1142         #endif
1143
1144         return bytes_written / elsize;
1145 }
1146
1147
1148 // cfputc() writes a character to a file
1149 //
1150 // returns:   success ==> returns character written
1151 //                                error   ==> EOF
1152 //
1153 int cfputc(int c, CFILE *cfile)
1154 {
1155         int result = 0;
1156
1157         SDL_assert(cfile != NULL);
1158         Cfile_block *cb;
1159         SDL_assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1160         cb = &Cfile_block_list[cfile->id];      
1161
1162         SDL_assert(cb->fp != NULL);
1163         result = fputc(c, cb->fp);
1164
1165         return result;  
1166 }
1167
1168
1169 // cfgetc() reads a character from a file
1170 //
1171 // returns:   success ==> returns character read
1172 //                                error   ==> EOF
1173 //
1174 int cfgetc(CFILE *cfile)
1175 {
1176         SDL_assert(cfile != NULL);
1177         
1178         char tmp;
1179
1180         int result = cfread(&tmp, 1, 1, cfile );
1181         if ( result == 1 )      {
1182                 result = char(tmp);
1183         } else {
1184                 result = CF_EOF;
1185         }
1186
1187         return result;  
1188 }
1189
1190
1191
1192
1193
1194 // cfgets() reads a string from a file
1195 //
1196 // returns:   success ==> returns pointer to string
1197 //                                error   ==> NULL
1198 //
1199 char *cfgets(char *buf, int n, CFILE *cfile)
1200 {
1201         SDL_assert(cfile != NULL);
1202         SDL_assert(buf != NULL);
1203         SDL_assert(n > 0 );
1204
1205         char * t = buf;
1206         int i, c;
1207
1208         for (i=0; i<n-1; i++ )  {
1209                 do {
1210                         char tmp_c;
1211
1212                         int ret = cfread( &tmp_c, 1, 1, cfile );
1213                         if ( ret != 1 ) {
1214                                 *buf = 0;
1215                                 if ( buf > t )  {               
1216                                         return t;
1217                                 } else {
1218                                         return NULL;
1219                                 }
1220                         }
1221                         c = int(tmp_c);
1222                 } while ( c == 13 );
1223                 *buf++ = char(c);
1224                 if ( c=='\n' ) break;
1225         }
1226         *buf++ = 0;
1227
1228         return  t;
1229 }
1230
1231 // cfputs() writes a string to a file
1232 //
1233 // returns:   success ==> non-negative value
1234 //                                error   ==> EOF
1235 //
1236 int cfputs(const char *str, CFILE *cfile)
1237 {
1238         SDL_assert(cfile != NULL);
1239         SDL_assert(str != NULL);
1240
1241         Cfile_block *cb;
1242         SDL_assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1243         cb = &Cfile_block_list[cfile->id];      
1244
1245         int result = 0;
1246
1247         // cfputs() not supported for memory-mapped files
1248         SDL_assert(cb->fp != NULL);
1249         result = fputs(str, cb->fp);
1250
1251         return result;  
1252 }
1253
1254
1255 // 16 and 32 bit checksum stuff ----------------------------------------------------------
1256
1257 // CRC code for mission validation.  given to us by Kevin Bentley on 7/20/98.   Some sort of
1258 // checksumming code that he wrote a while ago.  
1259 #define CRC32_POLYNOMIAL                                        0xEDB88320L
1260 unsigned long CRCTable[256];
1261
1262 #define CF_CHKSUM_SAMPLE_SIZE                           512
1263
1264 // update cur_chksum with the chksum of the new_data of size new_data_size
1265 ushort cf_add_chksum_short(ushort seed, const char *buffer, int size)
1266 {
1267         const ubyte * ptr = (const ubyte *)buffer;
1268         unsigned int sum1,sum2;
1269
1270         sum1 = sum2 = (int)(seed);
1271
1272         while(size--)   {
1273                 sum1 += *ptr++;
1274                 if (sum1 >= 255 ) sum1 -= 255;
1275                 sum2 += sum1;
1276         }
1277         sum2 %= 255;
1278         
1279         return (unsigned short)((sum1<<8)+ sum2);
1280 }
1281
1282 // update cur_chksum with the chksum of the new_data of size new_data_size
1283 unsigned long cf_add_chksum_long(unsigned long seed, const char *buffer, int size)
1284 {
1285         unsigned long crc;
1286         unsigned const char *p;
1287         unsigned long temp1;
1288         unsigned long temp2;
1289
1290         p = (unsigned const char*)buffer;
1291         crc = seed;     
1292
1293         while (size--!=0){
1294           temp1 = (crc>>8)&0x00FFFFFFL;
1295           temp2 = CRCTable[((int)crc^*p++)&0xff];
1296           crc = temp1^temp2;
1297         }       
1298         
1299         return crc;
1300 }
1301
1302 void cf_chksum_long_init()
1303 {
1304         int i,j;
1305         unsigned long crc;      
1306
1307         for( i=0;i<=255;i++) {
1308                 crc=i;
1309                 for(j=8;j>0;j--) {
1310                         if(crc&1)
1311                                  crc=(crc>>1)^CRC32_POLYNOMIAL;
1312                         else
1313                                  crc>>=1;
1314                 }
1315                 CRCTable[i]=crc;
1316         }       
1317 }
1318
1319 // single function convenient to use for both short and long checksums
1320 // NOTE : only one of chk_short or chk_long must be non-NULL (indicating which checksum to perform)
1321 int cf_chksum_do(CFILE *cfile, ushort *chk_short, uint *chk_long, int max_size)
1322 {
1323         char cf_buffer[CF_CHKSUM_SAMPLE_SIZE];
1324         int is_long;
1325         int cf_len = 0;
1326         int cf_total;
1327         int read_size;
1328
1329         // determine whether we're doing a short or long checksum
1330         is_long = 0;
1331         if(chk_short){
1332                 SDL_assert(!chk_long);          
1333                 *chk_short = 0;
1334         } else {
1335                 SDL_assert(chk_long);
1336                 is_long = 1;
1337                 *chk_long = 0;
1338         }
1339
1340         // if max_size is -1, set it to be the size of the file
1341         if(max_size < 0){
1342                 cfseek(cfile, 0, SEEK_SET);
1343                 max_size = cfilelength(cfile);
1344         }
1345         
1346         cf_total = 0;
1347         do {
1348                 // determine how much we want to read
1349                 if((max_size - cf_total) >= CF_CHKSUM_SAMPLE_SIZE){
1350                         read_size = CF_CHKSUM_SAMPLE_SIZE;
1351                 } else {
1352                         read_size = max_size - cf_total;
1353                 }
1354
1355                 // read in some buffer
1356                 cf_len = cfread(cf_buffer, 1, read_size, cfile);
1357
1358                 // total we've read so far
1359                 cf_total += cf_len;
1360
1361                 // add the checksum
1362                 if(cf_len > 0){
1363                         // do the proper short or long checksum
1364                         if(is_long){
1365                                 *chk_long = cf_add_chksum_long(*chk_long, cf_buffer, cf_len);
1366                         } else {
1367                                 *chk_short = cf_add_chksum_short(*chk_short, cf_buffer, cf_len);
1368                         }
1369                 }
1370         } while((cf_len > 0) && (cf_total < max_size));
1371
1372         return 1;
1373 }
1374
1375 // get the 2 byte checksum of the passed filename - return 0 if operation failed, 1 if succeeded
1376 int cf_chksum_short(const char *filename, ushort *chksum, int max_size, int cf_type)
1377 {
1378         int ret_val;
1379         CFILE *cfile = NULL;            
1380         
1381         // zero the checksum
1382         *chksum = 0;
1383
1384         // attempt to open the file
1385         cfile = cfopen(filename,"rt",CFILE_NORMAL,cf_type);
1386         if(cfile == NULL){              
1387                 return 0;
1388         }
1389         
1390         // call the overloaded cf_chksum function()
1391         ret_val = cf_chksum_do(cfile, chksum, NULL, max_size);
1392
1393         // close the file down
1394         cfclose(cfile);
1395         cfile = NULL;
1396
1397         // return the result
1398         return ret_val;
1399 }
1400
1401 // get the 2 byte checksum of the passed file - return 0 if operation failed, 1 if succeeded
1402 // NOTE : preserves current file position
1403 int cf_chksum_short(CFILE *file, ushort *chksum, int max_size)
1404 {
1405         int ret_code;
1406         int start_pos;
1407         
1408         // Returns current position of file.
1409         start_pos = cftell(file);
1410         if(start_pos == -1){
1411                 return 0;
1412         }
1413         
1414         // move to the beginning of the file
1415         if(cfseek(file, 0, CF_SEEK_SET)){
1416                 return 0;
1417         }
1418         ret_code = cf_chksum_do(file, chksum, NULL, max_size);
1419         // move back to the start position
1420         cfseek(file, start_pos, CF_SEEK_SET);
1421
1422         return ret_code;
1423 }
1424
1425 // get the 32 bit CRC checksum of the passed filename - return 0 if operation failed, 1 if succeeded
1426 int cf_chksum_long(const char *filename, uint *chksum, int max_size, int cf_type)
1427 {
1428         int ret_val;
1429         CFILE *cfile = NULL;            
1430         
1431         // zero the checksum
1432         *chksum = 0;
1433
1434         // attempt to open the file
1435         cfile = cfopen(filename,"rt",CFILE_NORMAL,cf_type);
1436         if(cfile == NULL){              
1437                 return 0;
1438         }
1439         
1440         // call the overloaded cf_chksum function()
1441         ret_val = cf_chksum_do(cfile, NULL, chksum, max_size);
1442
1443         // close the file down
1444         cfclose(cfile);
1445         cfile = NULL;
1446
1447         // return the result
1448         return ret_val; 
1449 }
1450
1451 // get the 32 bit CRC checksum of the passed file - return 0 if operation failed, 1 if succeeded
1452 // NOTE : preserves current file position
1453 int cf_chksum_long(CFILE *file, uint *chksum, int max_size)
1454 {
1455         int ret_code;
1456         int start_pos;
1457         
1458         // Returns current position of file.
1459         start_pos = cftell(file);
1460         if(start_pos == -1){
1461                 return 0;
1462         }
1463         
1464         // move to the beginning of the file
1465         if(cfseek(file, 0, CF_SEEK_SET)){
1466                 return 0;
1467         }
1468         ret_code = cf_chksum_do(file, NULL, chksum, max_size);
1469         // move back to the start position
1470         cfseek(file, start_pos, CF_SEEK_SET);
1471
1472         return ret_code;
1473 }
1474
1475
1476 // Flush the open file buffer
1477 //
1478 // exit: 0 - success
1479 //                      1 - failure
1480 int cflush(CFILE *cfile)
1481 {
1482         SDL_assert(cfile != NULL);
1483         Cfile_block *cb;
1484         SDL_assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1485         cb = &Cfile_block_list[cfile->id];      
1486
1487         SDL_assert(cb->fp != NULL);
1488         return fflush(cb->fp);
1489 }
1490
1491 // fill in Cfile_root_dir[] and Cfile_user_dir[]
1492 // this can be called at any time, even before cfile_init()
1493 //  returns: non-zero on error
1494 int cfile_init_paths()
1495 {
1496         if ( strlen(Cfile_root_dir) && strlen(Cfile_user_dir) ) {
1497                 return 0;
1498         }
1499
1500         char *t_path = SDL_GetBasePath();
1501
1502         // make sure we have something
1503         if (t_path == NULL) {
1504                 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Error trying to determine executable directory!", NULL);
1505                 return 1;
1506         }
1507
1508         // size check
1509         if ( strlen(t_path) >= CFILE_ROOT_DIRECTORY_LEN ) {
1510                 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Executable path is too long!", NULL);
1511                 return 1;
1512         }
1513
1514         // set root directory
1515         SDL_strlcpy(Cfile_root_dir, t_path, sizeof(Cfile_root_dir));
1516         // free SDL copy
1517         SDL_free(t_path);
1518         t_path = NULL;
1519
1520         // are we in a root directory?
1521         if ( cfile_in_root_dir(Cfile_root_dir) ) {
1522                 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Freespace2/Fred2 cannot be run from a drive root directory!", NULL);
1523                 return 1;
1524         }
1525
1526         // now for the user/pref directory, the writable location
1527         char *u_path = SDL_GetPrefPath(Osreg_company_name, Osreg_title);
1528
1529         // make sure we have something
1530         if (u_path == NULL) {
1531                 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Error trying to determine preferences directory!", NULL);
1532                 return 1;
1533         }
1534
1535         // size check
1536         if ( strlen(u_path) >= CFILE_ROOT_DIRECTORY_LEN ) {
1537                 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Preferences path is too long!", NULL);
1538                 return 1;
1539         }
1540
1541         // set user/pref directory
1542         SDL_strlcpy(Cfile_user_dir, u_path, sizeof(Cfile_user_dir));
1543         // free SDL copy
1544         SDL_free(u_path);
1545         u_path = NULL;
1546
1547         return 0;
1548 }