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