Localize scope for restore file pointer in main.
[open-adventure.git] / cheat.c
1 /*
2  * 'cheat' is a tool for generating save game files to test states that ought
3  * not happen. It leverages chunks of advent, mostly initialize() and
4  * savefile(), so we know we're always outputing save files that advent
5  * can import.
6  */
7 #include <getopt.h>
8 #include <stdlib.h>
9 #include <stdio.h>
10 #include <stdbool.h>
11 #include "advent.h"
12
13 FILE *logfp = NULL;
14 bool oldstyle = false;
15 bool prompt = true;
16
17 int main(int argc, char *argv[])
18 {
19     int ch;
20     char *savefilename = NULL;
21     long numdie = 0;
22     long saved = 1;
23     long version = 0;
24     FILE *fp = NULL;
25
26     /*  Options. */
27     const char* opts = "d:s:v:o:";
28     const char* usage = "Usage: %s [-d numdie] [-s numsaves] [-v version] -o savefilename \n"
29                         "        -d number of deaths. Signed integer value.\n"
30                         "        -s number of saves. Signed integer value.\n"
31                         "        -v version number of save format.\n"
32                         "        -o required. File name of save game to write.\n";
33
34     while ((ch = getopt(argc, argv, opts)) != EOF) {
35         switch (ch) {
36         case 'd':
37             numdie = (long)atoi(optarg);
38             break;
39         case 's':
40             saved = (long)atoi(optarg);
41             break;
42         case 'v':
43             version = (long)atoi(optarg);;
44             break;
45         case 'o':
46             savefilename = optarg;
47             break;
48         default:
49             fprintf(stderr,
50                     usage, argv[0]);
51             exit(EXIT_FAILURE);
52             break;
53         }
54     }
55
56     // Save filename required; the point of cheat is to generate save file
57     if (savefilename == NULL) {
58         fprintf(stderr,
59                 usage, argv[0]);
60         fprintf(stderr,
61                 "ERROR: filename required\n");
62         exit(EXIT_FAILURE);
63     }
64
65     // Initialize game variables
66     initialise();
67
68     // apply cheats
69     game.numdie = numdie;
70     game.saved = saved;
71
72     fp = fopen(savefilename, WRITE_MODE);
73     if (fp == NULL) {
74         fprintf(stderr,
75                 "Can't open file %s. Exiting.\n", savefilename);
76         exit(EXIT_FAILURE);
77     }
78
79     savefile(fp, version);
80
81     printf("cheat: %s created.\n", savefilename);
82
83     return EXIT_SUCCESS;
84 }