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