chiark / gitweb /
Missing quit on error was leading to an assertion failure on some
[sgt-puzzles.git] / midend.c
1 /*
2  * midend.c: general middle fragment sitting between the
3  * platform-specific front end and game-specific back end.
4  * Maintains a move list, takes care of Undo and Redo commands, and
5  * processes standard keystrokes for undo/redo/new/quit.
6  */
7
8 #include <stdio.h>
9 #include <string.h>
10 #include <assert.h>
11 #include <stdlib.h>
12 #include <ctype.h>
13
14 #include "puzzles.h"
15
16 enum { DEF_PARAMS, DEF_SEED, DEF_DESC };   /* for midend_game_id_int */
17
18 enum { NEWGAME, MOVE, SOLVE, RESTART };/* for midend_state_entry.movetype */
19
20 #define special(type) ( (type) != MOVE )
21
22 struct midend_state_entry {
23     game_state *state;
24     char *movestr;
25     int movetype;
26 };
27
28 struct midend_data {
29     frontend *frontend;
30     random_state *random;
31     const game *ourgame;
32
33     game_params **presets;
34     char **preset_names;
35     int npresets, presetsize;
36
37     /*
38      * `desc' and `privdesc' deserve a comment.
39      * 
40      * `desc' is the game description as presented to the user when
41      * they ask for Game -> Specific. `privdesc', if non-NULL, is a
42      * different game description used to reconstruct the initial
43      * game_state when de-serialising. If privdesc is NULL, `desc'
44      * is used for both.
45      * 
46      * For almost all games, `privdesc' is NULL and never used. The
47      * exception (as usual) is Mines: the initial game state has no
48      * squares open at all, but after the first click `desc' is
49      * rewritten to describe a game state with an initial click and
50      * thus a bunch of squares open. If we used that desc to
51      * serialise and deserialise, then the initial game state after
52      * deserialisation would look unlike the initial game state
53      * beforehand, and worse still execute_move() might fail on the
54      * attempted first click. So `privdesc' is also used in this
55      * case, to provide a game description describing the same
56      * fixed mine layout _but_ no initial click. (These game IDs
57      * may also be typed directly into Mines if you like.)
58      */
59     char *desc, *privdesc, *seedstr;
60     char *aux_info;
61     enum { GOT_SEED, GOT_DESC, GOT_NOTHING } genmode;
62
63     int nstates, statesize, statepos;
64     struct midend_state_entry *states;
65
66     game_params *params, *curparams;
67     game_drawstate *drawstate;
68     game_ui *ui;
69
70     game_state *oldstate;
71     float anim_time, anim_pos;
72     float flash_time, flash_pos;
73     int dir;
74
75     int timing;
76     float elapsed;
77     char *laststatus;
78
79     int pressed_mouse_button;
80
81     int tilesize, winwidth, winheight;
82 };
83
84 #define ensure(me) do { \
85     if ((me)->nstates >= (me)->statesize) { \
86         (me)->statesize = (me)->nstates + 128; \
87         (me)->states = sresize((me)->states, (me)->statesize, \
88                                struct midend_state_entry); \
89     } \
90 } while (0)
91
92 midend_data *midend_new(frontend *fe, const game *ourgame)
93 {
94     midend_data *me = snew(midend_data);
95     void *randseed;
96     int randseedsize;
97
98     get_random_seed(&randseed, &randseedsize);
99
100     me->frontend = fe;
101     me->ourgame = ourgame;
102     me->random = random_init(randseed, randseedsize);
103     me->nstates = me->statesize = me->statepos = 0;
104     me->states = NULL;
105     me->params = ourgame->default_params();
106     me->curparams = NULL;
107     me->desc = me->privdesc = NULL;
108     me->seedstr = NULL;
109     me->aux_info = NULL;
110     me->genmode = GOT_NOTHING;
111     me->drawstate = NULL;
112     me->oldstate = NULL;
113     me->presets = NULL;
114     me->preset_names = NULL;
115     me->npresets = me->presetsize = 0;
116     me->anim_time = me->anim_pos = 0.0F;
117     me->flash_time = me->flash_pos = 0.0F;
118     me->dir = 0;
119     me->ui = NULL;
120     me->pressed_mouse_button = 0;
121     me->laststatus = NULL;
122     me->timing = FALSE;
123     me->elapsed = 0.0F;
124     me->tilesize = me->winwidth = me->winheight = 0;
125
126     sfree(randseed);
127
128     return me;
129 }
130
131 static void midend_free_game(midend_data *me)
132 {
133     while (me->nstates > 0) {
134         me->nstates--;
135         me->ourgame->free_game(me->states[me->nstates].state);
136         sfree(me->states[me->nstates].movestr);
137     }
138
139     if (me->drawstate)
140         me->ourgame->free_drawstate(me->drawstate);
141 }
142
143 void midend_free(midend_data *me)
144 {
145     int i;
146
147     midend_free_game(me);
148
149     random_free(me->random);
150     sfree(me->states);
151     sfree(me->desc);
152     sfree(me->privdesc);
153     sfree(me->seedstr);
154     sfree(me->aux_info);
155     me->ourgame->free_params(me->params);
156     if (me->npresets) {
157         for (i = 0; i < me->npresets; i++) {
158             sfree(me->presets[i]);
159             sfree(me->preset_names[i]);
160         }
161         sfree(me->presets);
162         sfree(me->preset_names);
163     }
164     if (me->ui)
165         me->ourgame->free_ui(me->ui);
166     if (me->curparams)
167         me->ourgame->free_params(me->curparams);
168     sfree(me->laststatus);
169     sfree(me);
170 }
171
172 static void midend_size_new_drawstate(midend_data *me)
173 {
174     /*
175      * Don't even bother, if we haven't worked out our tile size
176      * anyway yet.
177      */
178     if (me->tilesize > 0) {
179         me->ourgame->compute_size(me->params, me->tilesize,
180                                   &me->winwidth, &me->winheight);
181         me->ourgame->set_size(me->drawstate, me->params, me->tilesize);
182     }
183 }
184
185 void midend_size(midend_data *me, int *x, int *y, int expand)
186 {
187     int min, max;
188     int rx, ry;
189
190     /*
191      * Find the tile size that best fits within the given space. If
192      * `expand' is TRUE, we must actually find the _largest_ such
193      * tile size; otherwise, we bound above at the game's preferred
194      * tile size.
195      */
196     if (expand) {
197         max = 1;
198         do {
199             max *= 2;
200             me->ourgame->compute_size(me->params, max, &rx, &ry);
201         } while (rx <= *x && ry <= *y);
202     } else
203         max = me->ourgame->preferred_tilesize + 1;
204     min = 1;
205
206     /*
207      * Now binary-search between min and max. We're looking for a
208      * boundary rather than a value: the point at which tile sizes
209      * stop fitting within the given dimensions. Thus, we stop when
210      * max and min differ by exactly 1.
211      */
212     while (max - min > 1) {
213         int mid = (max + min) / 2;
214         me->ourgame->compute_size(me->params, mid, &rx, &ry);
215         if (rx <= *x && ry <= *y)
216             min = mid;
217         else
218             max = mid;
219     }
220
221     /*
222      * Now `min' is a valid size, and `max' isn't. So use `min'.
223      */
224
225     me->tilesize = min;
226     midend_size_new_drawstate(me);
227     *x = me->winwidth;
228     *y = me->winheight;
229 }
230
231 void midend_set_params(midend_data *me, game_params *params)
232 {
233     me->ourgame->free_params(me->params);
234     me->params = me->ourgame->dup_params(params);
235 }
236
237 static void midend_set_timer(midend_data *me)
238 {
239     me->timing = (me->ourgame->is_timed &&
240                   me->ourgame->timing_state(me->states[me->statepos-1].state));
241     if (me->timing || me->flash_time || me->anim_time)
242         activate_timer(me->frontend);
243     else
244         deactivate_timer(me->frontend);
245 }
246
247 void midend_force_redraw(midend_data *me)
248 {
249     if (me->drawstate)
250         me->ourgame->free_drawstate(me->drawstate);
251     me->drawstate = me->ourgame->new_drawstate(me->states[0].state);
252     midend_size_new_drawstate(me);
253     midend_redraw(me);
254 }
255
256 void midend_new_game(midend_data *me)
257 {
258     midend_free_game(me);
259
260     assert(me->nstates == 0);
261
262     if (me->genmode == GOT_DESC) {
263         me->genmode = GOT_NOTHING;
264     } else {
265         random_state *rs;
266
267         if (me->genmode == GOT_SEED) {
268             me->genmode = GOT_NOTHING;
269         } else {
270             /*
271              * Generate a new random seed. 15 digits comes to about
272              * 48 bits, which should be more than enough.
273              * 
274              * I'll avoid putting a leading zero on the number,
275              * just in case it confuses anybody who thinks it's
276              * processed as an integer rather than a string.
277              */
278             char newseed[16];
279             int i;
280             newseed[15] = '\0';
281             newseed[0] = '1' + random_upto(me->random, 9);
282             for (i = 1; i < 15; i++)
283                 newseed[i] = '0' + random_upto(me->random, 10);
284             sfree(me->seedstr);
285             me->seedstr = dupstr(newseed);
286
287             if (me->curparams)
288                 me->ourgame->free_params(me->curparams);
289             me->curparams = me->ourgame->dup_params(me->params);
290         }
291
292         sfree(me->desc);
293         sfree(me->privdesc);
294         sfree(me->aux_info);
295         me->aux_info = NULL;
296
297         rs = random_init(me->seedstr, strlen(me->seedstr));
298         me->desc = me->ourgame->new_desc(me->curparams, rs,
299                                          &me->aux_info, TRUE);
300         me->privdesc = NULL;
301         random_free(rs);
302     }
303
304     ensure(me);
305     me->states[me->nstates].state =
306         me->ourgame->new_game(me, me->params, me->desc);
307     me->states[me->nstates].movestr = NULL;
308     me->states[me->nstates].movetype = NEWGAME;
309     me->nstates++;
310     me->statepos = 1;
311     me->drawstate = me->ourgame->new_drawstate(me->states[0].state);
312     midend_size_new_drawstate(me);
313     me->elapsed = 0.0F;
314     midend_set_timer(me);
315     if (me->ui)
316         me->ourgame->free_ui(me->ui);
317     me->ui = me->ourgame->new_ui(me->states[0].state);
318     me->pressed_mouse_button = 0;
319 }
320
321 static int midend_undo(midend_data *me)
322 {
323     if (me->statepos > 1) {
324         if (me->ui)
325             me->ourgame->changed_state(me->ui,
326                                        me->states[me->statepos-1].state,
327                                        me->states[me->statepos-2].state);
328         me->statepos--;
329         me->dir = -1;
330         return 1;
331     } else
332         return 0;
333 }
334
335 static int midend_redo(midend_data *me)
336 {
337     if (me->statepos < me->nstates) {
338         if (me->ui)
339             me->ourgame->changed_state(me->ui,
340                                        me->states[me->statepos-1].state,
341                                        me->states[me->statepos].state);
342         me->statepos++;
343         me->dir = +1;
344         return 1;
345     } else
346         return 0;
347 }
348
349 static void midend_finish_move(midend_data *me)
350 {
351     float flashtime;
352
353     /*
354      * We do not flash if the later of the two states is special.
355      * This covers both forward Solve moves and backward (undone)
356      * Restart moves.
357      */
358     if ((me->oldstate || me->statepos > 1) &&
359         ((me->dir > 0 && !special(me->states[me->statepos-1].movetype)) ||
360          (me->dir < 0 && me->statepos < me->nstates &&
361           !special(me->states[me->statepos].movetype)))) {
362         flashtime = me->ourgame->flash_length(me->oldstate ? me->oldstate :
363                                               me->states[me->statepos-2].state,
364                                               me->states[me->statepos-1].state,
365                                               me->oldstate ? me->dir : +1,
366                                               me->ui);
367         if (flashtime > 0) {
368             me->flash_pos = 0.0F;
369             me->flash_time = flashtime;
370         }
371     }
372
373     if (me->oldstate)
374         me->ourgame->free_game(me->oldstate);
375     me->oldstate = NULL;
376     me->anim_pos = me->anim_time = 0;
377     me->dir = 0;
378
379     midend_set_timer(me);
380 }
381
382 void midend_stop_anim(midend_data *me)
383 {
384     if (me->oldstate || me->anim_time != 0) {
385         midend_finish_move(me);
386         midend_redraw(me);
387     }
388 }
389
390 void midend_restart_game(midend_data *me)
391 {
392     game_state *s;
393
394     midend_stop_anim(me);
395
396     assert(me->statepos >= 1);
397     if (me->statepos == 1)
398         return;                        /* no point doing anything at all! */
399
400     /*
401      * During restart, we reconstruct the game from the (public)
402      * game description rather than from states[0], because that
403      * way Mines gets slightly more sensible behaviour (restart
404      * goes to _after_ the first click so you don't have to
405      * remember where you clicked).
406      */
407     s = me->ourgame->new_game(me, me->params, me->desc);
408
409     /*
410      * Now enter the restarted state as the next move.
411      */
412     midend_stop_anim(me);
413     while (me->nstates > me->statepos)
414         me->ourgame->free_game(me->states[--me->nstates].state);
415     ensure(me);
416     me->states[me->nstates].state = s;
417     me->states[me->nstates].movestr = dupstr(me->desc);
418     me->states[me->nstates].movetype = RESTART;
419     me->statepos = ++me->nstates;
420     if (me->ui)
421         me->ourgame->changed_state(me->ui,
422                                    me->states[me->statepos-2].state,
423                                    me->states[me->statepos-1].state);
424     me->anim_time = 0.0;
425     midend_finish_move(me);
426     midend_redraw(me);
427     midend_set_timer(me);
428 }
429
430 static int midend_really_process_key(midend_data *me, int x, int y, int button)
431 {
432     game_state *oldstate =
433         me->ourgame->dup_game(me->states[me->statepos - 1].state);
434     int special = FALSE, gotspecial = FALSE, ret = 1;
435     float anim_time;
436     game_state *s;
437     char *movestr;
438         
439     movestr =
440         me->ourgame->interpret_move(me->states[me->statepos-1].state,
441                                     me->ui, me->drawstate, x, y, button);
442
443     if (!movestr) {
444         if (button == 'n' || button == 'N' || button == '\x0E') {
445             midend_stop_anim(me);
446             midend_new_game(me);
447             midend_redraw(me);
448             goto done;                 /* never animate */
449         } else if (button == 'u' || button == 'u' ||
450                    button == '\x1A' || button == '\x1F') {
451             midend_stop_anim(me);
452             special = special(me->states[me->statepos-1].movetype);
453             gotspecial = TRUE;
454             if (!midend_undo(me))
455                 goto done;
456         } else if (button == 'r' || button == 'R' ||
457                    button == '\x12' || button == '\x19') {
458             midend_stop_anim(me);
459             if (!midend_redo(me))
460                 goto done;
461         } else if (button == 'q' || button == 'Q' || button == '\x11') {
462             ret = 0;
463             goto done;
464         } else
465             goto done;
466     } else {
467         if (!*movestr)
468             s = me->states[me->statepos-1].state;
469         else {
470             s = me->ourgame->execute_move(me->states[me->statepos-1].state,
471                                           movestr);
472             assert(s != NULL);
473         }
474
475         if (s == me->states[me->statepos-1].state) {
476             /*
477              * make_move() is allowed to return its input state to
478              * indicate that although no move has been made, the UI
479              * state has been updated and a redraw is called for.
480              */
481             midend_redraw(me);
482             goto done;
483         } else if (s) {
484             midend_stop_anim(me);
485             while (me->nstates > me->statepos)
486                 me->ourgame->free_game(me->states[--me->nstates].state);
487             ensure(me);
488             assert(movestr != NULL);
489             me->states[me->nstates].state = s;
490             me->states[me->nstates].movestr = movestr;
491             me->states[me->nstates].movetype = MOVE;
492             me->statepos = ++me->nstates;
493             me->dir = +1;
494         } else {
495             goto done;
496         }
497     }
498
499     if (!gotspecial)
500         special = special(me->states[me->statepos-1].movetype);
501
502     /*
503      * See if this move requires an animation.
504      */
505     if (special) {
506         anim_time = 0;
507     } else {
508         anim_time = me->ourgame->anim_length(oldstate,
509                                              me->states[me->statepos-1].state,
510                                              me->dir, me->ui);
511     }
512
513     me->oldstate = oldstate; oldstate = NULL;
514     if (anim_time > 0) {
515         me->anim_time = anim_time;
516     } else {
517         me->anim_time = 0.0;
518         midend_finish_move(me);
519     }
520     me->anim_pos = 0.0;
521
522     midend_redraw(me);
523
524     midend_set_timer(me);
525
526     done:
527     if (oldstate) me->ourgame->free_game(oldstate);
528     return ret;
529 }
530
531 int midend_process_key(midend_data *me, int x, int y, int button)
532 {
533     int ret = 1;
534
535     /*
536      * Harmonise mouse drag and release messages.
537      * 
538      * Some front ends might accidentally switch from sending, say,
539      * RIGHT_DRAG messages to sending LEFT_DRAG, half way through a
540      * drag. (This can happen on the Mac, for example, since
541      * RIGHT_DRAG is usually done using Command+drag, and if the
542      * user accidentally releases Command half way through the drag
543      * then there will be trouble.)
544      * 
545      * It would be an O(number of front ends) annoyance to fix this
546      * in the front ends, but an O(number of back ends) annoyance
547      * to have each game capable of dealing with it. Therefore, we
548      * fix it _here_ in the common midend code so that it only has
549      * to be done once.
550      * 
551      * The possible ways in which things can go screwy in the front
552      * end are:
553      * 
554      *  - in a system containing multiple physical buttons button
555      *    presses can inadvertently overlap. We can see ABab (caps
556      *    meaning button-down and lowercase meaning button-up) when
557      *    the user had semantically intended AaBb.
558      * 
559      *  - in a system where one button is simulated by means of a
560      *    modifier key and another button, buttons can mutate
561      *    between press and release (possibly during drag). So we
562      *    can see Ab instead of Aa.
563      * 
564      * Definite requirements are:
565      * 
566      *  - button _presses_ must never be invented or destroyed. If
567      *    the user presses two buttons in succession, the button
568      *    presses must be transferred to the backend unchanged. So
569      *    if we see AaBb , that's fine; if we see ABab (the button
570      *    presses inadvertently overlapped) we must somehow
571      *    `correct' it to AaBb.
572      * 
573      *  - every mouse action must end up looking like a press, zero
574      *    or more drags, then a release. This allows back ends to
575      *    make the _assumption_ that incoming mouse data will be
576      *    sane in this regard, and not worry about the details.
577      * 
578      * So my policy will be:
579      * 
580      *  - treat any button-up as a button-up for the currently
581      *    pressed button, or ignore it if there is no currently
582      *    pressed button.
583      * 
584      *  - treat any drag as a drag for the currently pressed
585      *    button, or ignore it if there is no currently pressed
586      *    button.
587      * 
588      *  - if we see a button-down while another button is currently
589      *    pressed, invent a button-up for the first one and then
590      *    pass the button-down through as before.
591      * 
592      * 2005-05-31: An addendum to the above. Some games might want
593      * a `priority order' among buttons, such that if one button is
594      * pressed while another is down then a fixed one of the
595      * buttons takes priority no matter what order they're pressed
596      * in. Mines, in particular, wants to treat a left+right click
597      * like a left click for the benefit of users of other
598      * implementations. So the last of the above points is modified
599      * in the presence of an (optional) button priority order.
600      */
601     if (IS_MOUSE_DRAG(button) || IS_MOUSE_RELEASE(button)) {
602         if (me->pressed_mouse_button) {
603             if (IS_MOUSE_DRAG(button)) {
604                 button = me->pressed_mouse_button +
605                     (LEFT_DRAG - LEFT_BUTTON);
606             } else {
607                 button = me->pressed_mouse_button +
608                     (LEFT_RELEASE - LEFT_BUTTON);
609             }
610         } else
611             return ret;                /* ignore it */
612     } else if (IS_MOUSE_DOWN(button) && me->pressed_mouse_button) {
613         /*
614          * If the new button has lower priority than the old one,
615          * don't bother doing this.
616          */
617         if (me->ourgame->mouse_priorities &
618             BUTTON_BEATS(me->pressed_mouse_button, button))
619             return ret;                /* just ignore it */
620
621         /*
622          * Fabricate a button-up for the previously pressed button.
623          */
624         ret = ret && midend_really_process_key
625             (me, x, y, (me->pressed_mouse_button +
626                         (LEFT_RELEASE - LEFT_BUTTON)));
627     }
628
629     /*
630      * Now send on the event we originally received.
631      */
632     ret = ret && midend_really_process_key(me, x, y, button);
633
634     /*
635      * And update the currently pressed button.
636      */
637     if (IS_MOUSE_RELEASE(button))
638         me->pressed_mouse_button = 0;
639     else if (IS_MOUSE_DOWN(button))
640         me->pressed_mouse_button = button;
641
642     return ret;
643 }
644
645 void midend_redraw(midend_data *me)
646 {
647     if (me->statepos > 0 && me->drawstate) {
648         start_draw(me->frontend);
649         if (me->oldstate && me->anim_time > 0 &&
650             me->anim_pos < me->anim_time) {
651             assert(me->dir != 0);
652             me->ourgame->redraw(me->frontend, me->drawstate, me->oldstate,
653                                 me->states[me->statepos-1].state, me->dir,
654                                 me->ui, me->anim_pos, me->flash_pos);
655         } else {
656             me->ourgame->redraw(me->frontend, me->drawstate, NULL,
657                                 me->states[me->statepos-1].state, +1 /*shrug*/,
658                                 me->ui, 0.0, me->flash_pos);
659         }
660         end_draw(me->frontend);
661     }
662 }
663
664 void midend_timer(midend_data *me, float tplus)
665 {
666     me->anim_pos += tplus;
667     if (me->anim_pos >= me->anim_time ||
668         me->anim_time == 0 || !me->oldstate) {
669         if (me->anim_time > 0)
670             midend_finish_move(me);
671     }
672
673     me->flash_pos += tplus;
674     if (me->flash_pos >= me->flash_time || me->flash_time == 0) {
675         me->flash_pos = me->flash_time = 0;
676     }
677
678     midend_redraw(me);
679
680     if (me->timing) {
681         float oldelapsed = me->elapsed;
682         me->elapsed += tplus;
683         if ((int)oldelapsed != (int)me->elapsed)
684             status_bar(me->frontend, me->laststatus ? me->laststatus : "");
685     }
686
687     midend_set_timer(me);
688 }
689
690 float *midend_colours(midend_data *me, int *ncolours)
691 {
692     game_state *state = NULL;
693     float *ret;
694
695     if (me->nstates == 0) {
696         char *aux = NULL;
697         char *desc = me->ourgame->new_desc(me->params, me->random,
698                                            &aux, TRUE);
699         state = me->ourgame->new_game(me, me->params, desc);
700         sfree(desc);
701         sfree(aux);
702     } else
703         state = me->states[0].state;
704
705     ret = me->ourgame->colours(me->frontend, state, ncolours);
706
707     {
708         int i;
709
710         /*
711          * Allow environment-based overrides for the standard
712          * colours by defining variables along the lines of
713          * `NET_COLOUR_4=6000c0'.
714          */
715
716         for (i = 0; i < *ncolours; i++) {
717             char buf[80], *e;
718             unsigned int r, g, b;
719             int j;
720
721             sprintf(buf, "%s_COLOUR_%d", me->ourgame->name, i);
722             for (j = 0; buf[j]; j++)
723                 buf[j] = toupper((unsigned char)buf[j]);
724             if ((e = getenv(buf)) != NULL &&
725                 sscanf(e, "%2x%2x%2x", &r, &g, &b) == 3) {
726                 ret[i*3 + 0] = r / 255.0;
727                 ret[i*3 + 1] = g / 255.0;
728                 ret[i*3 + 2] = b / 255.0;
729             }
730         }
731     }
732
733     if (me->nstates == 0)
734         me->ourgame->free_game(state);
735
736     return ret;
737 }
738
739 int midend_num_presets(midend_data *me)
740 {
741     if (!me->npresets) {
742         char *name;
743         game_params *preset;
744
745         while (me->ourgame->fetch_preset(me->npresets, &name, &preset)) {
746             if (me->presetsize <= me->npresets) {
747                 me->presetsize = me->npresets + 10;
748                 me->presets = sresize(me->presets, me->presetsize,
749                                       game_params *);
750                 me->preset_names = sresize(me->preset_names, me->presetsize,
751                                            char *);
752             }
753
754             me->presets[me->npresets] = preset;
755             me->preset_names[me->npresets] = name;
756             me->npresets++;
757         }
758     }
759
760     {
761         /*
762          * Allow environment-based extensions to the preset list by
763          * defining a variable along the lines of `SOLO_PRESETS=2x3
764          * Advanced:2x3da'. Colon-separated list of items,
765          * alternating between textual titles in the menu and
766          * encoded parameter strings.
767          */
768         char buf[80], *e, *p;
769         int j;
770
771         sprintf(buf, "%s_PRESETS", me->ourgame->name);
772         for (j = 0; buf[j]; j++)
773             buf[j] = toupper((unsigned char)buf[j]);
774
775         if ((e = getenv(buf)) != NULL) {
776             p = e = dupstr(e);
777
778             while (*p) {
779                 char *name, *val;
780                 game_params *preset;
781
782                 name = p;
783                 while (*p && *p != ':') p++;
784                 if (*p) *p++ = '\0';
785                 val = p;
786                 while (*p && *p != ':') p++;
787                 if (*p) *p++ = '\0';
788
789                 preset = me->ourgame->default_params();
790                 me->ourgame->decode_params(preset, val);
791
792                 if (me->ourgame->validate_params(preset, TRUE)) {
793                     /* Drop this one from the list. */
794                     me->ourgame->free_params(preset);
795                     continue;
796                 }
797
798                 if (me->presetsize <= me->npresets) {
799                     me->presetsize = me->npresets + 10;
800                     me->presets = sresize(me->presets, me->presetsize,
801                                           game_params *);
802                     me->preset_names = sresize(me->preset_names,
803                                                me->presetsize, char *);
804                 }
805
806                 me->presets[me->npresets] = preset;
807                 me->preset_names[me->npresets] = dupstr(name);
808                 me->npresets++;
809             }
810         }
811     }
812
813     return me->npresets;
814 }
815
816 void midend_fetch_preset(midend_data *me, int n,
817                          char **name, game_params **params)
818 {
819     assert(n >= 0 && n < me->npresets);
820     *name = me->preset_names[n];
821     *params = me->presets[n];
822 }
823
824 int midend_wants_statusbar(midend_data *me)
825 {
826     return me->ourgame->wants_statusbar();
827 }
828
829 void midend_supersede_game_desc(midend_data *me, char *desc, char *privdesc)
830 {
831     sfree(me->desc);
832     sfree(me->privdesc);
833     me->desc = dupstr(desc);
834     me->privdesc = privdesc ? dupstr(privdesc) : NULL;
835 }
836
837 config_item *midend_get_config(midend_data *me, int which, char **wintitle)
838 {
839     char *titlebuf, *parstr, *rest;
840     config_item *ret;
841     char sep;
842
843     assert(wintitle);
844     titlebuf = snewn(40 + strlen(me->ourgame->name), char);
845
846     switch (which) {
847       case CFG_SETTINGS:
848         sprintf(titlebuf, "%s configuration", me->ourgame->name);
849         *wintitle = titlebuf;
850         return me->ourgame->configure(me->params);
851       case CFG_SEED:
852       case CFG_DESC:
853         if (!me->curparams) {
854           sfree(titlebuf);
855           return NULL;
856         }
857         sprintf(titlebuf, "%s %s selection", me->ourgame->name,
858                 which == CFG_SEED ? "random" : "game");
859         *wintitle = titlebuf;
860
861         ret = snewn(2, config_item);
862
863         ret[0].type = C_STRING;
864         if (which == CFG_SEED)
865             ret[0].name = "Game random seed";
866         else
867             ret[0].name = "Game ID";
868         ret[0].ival = 0;
869         /*
870          * For CFG_DESC the text going in here will be a string
871          * encoding of the restricted parameters, plus a colon,
872          * plus the game description. For CFG_SEED it will be the
873          * full parameters, plus a hash, plus the random seed data.
874          * Either of these is a valid full game ID (although only
875          * the former is likely to persist across many code
876          * changes).
877          */
878         parstr = me->ourgame->encode_params(me->curparams, which == CFG_SEED);
879         assert(parstr);
880         if (which == CFG_DESC) {
881             rest = me->desc ? me->desc : "";
882             sep = ':';
883         } else {
884             rest = me->seedstr ? me->seedstr : "";
885             sep = '#';
886         }
887         ret[0].sval = snewn(strlen(parstr) + strlen(rest) + 2, char);
888         sprintf(ret[0].sval, "%s%c%s", parstr, sep, rest);
889         sfree(parstr);
890
891         ret[1].type = C_END;
892         ret[1].name = ret[1].sval = NULL;
893         ret[1].ival = 0;
894
895         return ret;
896     }
897
898     assert(!"We shouldn't be here");
899     return NULL;
900 }
901
902 static char *midend_game_id_int(midend_data *me, char *id, int defmode)
903 {
904     char *error, *par, *desc, *seed;
905     game_params *newcurparams, *newparams, *oldparams1, *oldparams2;
906     int free_params;
907
908     seed = strchr(id, '#');
909     desc = strchr(id, ':');
910
911     if (desc && (!seed || desc < seed)) {
912         /*
913          * We have a colon separating parameters from game
914          * description. So `par' now points to the parameters
915          * string, and `desc' to the description string.
916          */
917         *desc++ = '\0';
918         par = id;
919         seed = NULL;
920     } else if (seed && (!desc || seed < desc)) {
921         /*
922          * We have a hash separating parameters from random seed.
923          * So `par' now points to the parameters string, and `seed'
924          * to the seed string.
925          */
926         *seed++ = '\0';
927         par = id;
928         desc = NULL;
929     } else {
930         /*
931          * We only have one string. Depending on `defmode', we take
932          * it to be either parameters, seed or description.
933          */
934         if (defmode == DEF_SEED) {
935             seed = id;
936             par = desc = NULL;
937         } else if (defmode == DEF_DESC) {
938             desc = id;
939             par = seed = NULL;
940         } else {
941             par = id;
942             seed = desc = NULL;
943         }
944     }
945
946     /*
947      * We must be reasonably careful here not to modify anything in
948      * `me' until we have finished validating things. This function
949      * must either return an error and do nothing to the midend, or
950      * return success and do everything; nothing in between is
951      * acceptable.
952      */
953     newcurparams = newparams = oldparams1 = oldparams2 = NULL;
954
955     if (par) {
956         newcurparams = me->ourgame->dup_params(me->params);
957         me->ourgame->decode_params(newcurparams, par);
958         error = me->ourgame->validate_params(newcurparams, desc == NULL);
959         if (error) {
960             me->ourgame->free_params(newcurparams);
961             return error;
962         }
963         oldparams1 = me->curparams;
964
965         /*
966          * Now filter only the persistent parts of this state into
967          * the long-term params structure, unless we've _only_
968          * received a params string in which case the whole lot is
969          * persistent.
970          */
971         oldparams2 = me->params;
972         if (seed || desc) {
973             char *tmpstr;
974
975             newparams = me->ourgame->dup_params(me->params);
976
977             tmpstr = me->ourgame->encode_params(newcurparams, FALSE);
978             me->ourgame->decode_params(newparams, tmpstr);
979
980             sfree(tmpstr);
981         } else {
982             newparams = me->ourgame->dup_params(newcurparams);
983         }
984         free_params = TRUE;
985     } else {
986         newcurparams = me->curparams;
987         newparams = me->params;
988         free_params = FALSE;
989     }
990
991     if (desc) {
992         error = me->ourgame->validate_desc(newparams, desc);
993         if (error) {
994             if (free_params) {
995                 if (newcurparams)
996                     me->ourgame->free_params(newcurparams);
997                 if (newparams)
998                     me->ourgame->free_params(newparams);
999             }
1000             return error;
1001         }
1002     }
1003
1004     /*
1005      * Now we've got past all possible error points. Update the
1006      * midend itself.
1007      */
1008     me->params = newparams;
1009     me->curparams = newcurparams;
1010     if (oldparams1)
1011         me->ourgame->free_params(oldparams1);
1012     if (oldparams2)
1013         me->ourgame->free_params(oldparams2);
1014
1015     sfree(me->desc);
1016     sfree(me->privdesc);
1017     me->desc = me->privdesc = NULL;
1018     sfree(me->seedstr);
1019     me->seedstr = NULL;
1020
1021     if (desc) {
1022         me->desc = dupstr(desc);
1023         me->genmode = GOT_DESC;
1024         sfree(me->aux_info);
1025         me->aux_info = NULL;
1026     }
1027
1028     if (seed) {
1029         me->seedstr = dupstr(seed);
1030         me->genmode = GOT_SEED;
1031     }
1032
1033     return NULL;
1034 }
1035
1036 char *midend_game_id(midend_data *me, char *id)
1037 {
1038     return midend_game_id_int(me, id, DEF_PARAMS);
1039 }
1040
1041 char *midend_set_config(midend_data *me, int which, config_item *cfg)
1042 {
1043     char *error;
1044     game_params *params;
1045
1046     switch (which) {
1047       case CFG_SETTINGS:
1048         params = me->ourgame->custom_params(cfg);
1049         error = me->ourgame->validate_params(params, TRUE);
1050
1051         if (error) {
1052             me->ourgame->free_params(params);
1053             return error;
1054         }
1055
1056         me->ourgame->free_params(me->params);
1057         me->params = params;
1058         break;
1059
1060       case CFG_SEED:
1061       case CFG_DESC:
1062         error = midend_game_id_int(me, cfg[0].sval,
1063                                    (which == CFG_SEED ? DEF_SEED : DEF_DESC));
1064         if (error)
1065             return error;
1066         break;
1067     }
1068
1069     return NULL;
1070 }
1071
1072 char *midend_text_format(midend_data *me)
1073 {
1074     if (me->ourgame->can_format_as_text && me->statepos > 0)
1075         return me->ourgame->text_format(me->states[me->statepos-1].state);
1076     else
1077         return NULL;
1078 }
1079
1080 char *midend_solve(midend_data *me)
1081 {
1082     game_state *s;
1083     char *msg, *movestr;
1084
1085     if (!me->ourgame->can_solve)
1086         return "This game does not support the Solve operation";
1087
1088     if (me->statepos < 1)
1089         return "No game set up to solve";   /* _shouldn't_ happen! */
1090
1091     msg = "Solve operation failed";    /* game _should_ overwrite on error */
1092     movestr = me->ourgame->solve(me->states[0].state,
1093                                  me->states[me->statepos-1].state,
1094                                  me->aux_info, &msg);
1095     if (!movestr)
1096         return msg;
1097     s = me->ourgame->execute_move(me->states[me->statepos-1].state, movestr);
1098     assert(s);
1099
1100     /*
1101      * Now enter the solved state as the next move.
1102      */
1103     midend_stop_anim(me);
1104     while (me->nstates > me->statepos)
1105         me->ourgame->free_game(me->states[--me->nstates].state);
1106     ensure(me);
1107     me->states[me->nstates].state = s;
1108     me->states[me->nstates].movestr = movestr;
1109     me->states[me->nstates].movetype = SOLVE;
1110     me->statepos = ++me->nstates;
1111     if (me->ui)
1112         me->ourgame->changed_state(me->ui,
1113                                    me->states[me->statepos-2].state,
1114                                    me->states[me->statepos-1].state);
1115     me->anim_time = 0.0;
1116     midend_finish_move(me);
1117     midend_redraw(me);
1118     midend_set_timer(me);
1119     return NULL;
1120 }
1121
1122 char *midend_rewrite_statusbar(midend_data *me, char *text)
1123 {
1124     /*
1125      * An important special case is that we are occasionally called
1126      * with our own laststatus, to update the timer.
1127      */
1128     if (me->laststatus != text) {
1129         sfree(me->laststatus);
1130         me->laststatus = dupstr(text);
1131     }
1132
1133     if (me->ourgame->is_timed) {
1134         char timebuf[100], *ret;
1135         int min, sec;
1136
1137         sec = me->elapsed;
1138         min = sec / 60;
1139         sec %= 60;
1140         sprintf(timebuf, "[%d:%02d] ", min, sec);
1141
1142         ret = snewn(strlen(timebuf) + strlen(text) + 1, char);
1143         strcpy(ret, timebuf);
1144         strcat(ret, text);
1145         return ret;
1146
1147     } else {
1148         return dupstr(text);
1149     }
1150 }
1151
1152 #define SERIALISE_MAGIC "Simon Tatham's Portable Puzzle Collection"
1153 #define SERIALISE_VERSION "1"
1154
1155 void midend_serialise(midend_data *me,
1156                       void (*write)(void *ctx, void *buf, int len),
1157                       void *wctx)
1158 {
1159     int i;
1160
1161     /*
1162      * Each line of the save file contains three components. First
1163      * exactly 8 characters of header word indicating what type of
1164      * data is contained on the line; then a colon followed by a
1165      * decimal integer giving the length of the main string on the
1166      * line; then a colon followed by the string itself (exactly as
1167      * many bytes as previously specified, no matter what they
1168      * contain). Then a newline (of reasonably flexible form).
1169      */
1170 #define wr(h,s) do { \
1171     char hbuf[80]; \
1172     char *str = (s); \
1173     sprintf(hbuf, "%-8.8s:%d:", (h), (int)strlen(str)); \
1174     write(wctx, hbuf, strlen(hbuf)); \
1175     write(wctx, str, strlen(str)); \
1176     write(wctx, "\n", 1); \
1177 } while (0)
1178
1179     /*
1180      * Magic string identifying the file, and version number of the
1181      * file format.
1182      */
1183     wr("SAVEFILE", SERIALISE_MAGIC);
1184     wr("VERSION", SERIALISE_VERSION);
1185
1186     /*
1187      * The game name. (Copied locally to avoid const annoyance.)
1188      */
1189     {
1190         char *s = dupstr(me->ourgame->name);
1191         wr("GAME", s);
1192         sfree(s);
1193     }
1194
1195     /*
1196      * The current long-term parameters structure, in full.
1197      */
1198     if (me->params) {
1199         char *s = me->ourgame->encode_params(me->params, TRUE);
1200         wr("PARAMS", s);
1201         sfree(s);
1202     }
1203
1204     /*
1205      * The current short-term parameters structure, in full.
1206      */
1207     if (me->curparams) {
1208         char *s = me->ourgame->encode_params(me->curparams, TRUE);
1209         wr("CPARAMS", s);
1210         sfree(s);
1211     }
1212
1213     /*
1214      * The current game description, the privdesc, and the random seed.
1215      */
1216     if (me->seedstr)
1217         wr("SEED", me->seedstr);
1218     if (me->desc)
1219         wr("DESC", me->desc);
1220     if (me->privdesc)
1221         wr("PRIVDESC", me->privdesc);
1222
1223     /*
1224      * The game's aux_info. We obfuscate this to prevent spoilers
1225      * (people are likely to run `head' or similar on a saved game
1226      * file simply to find out what it is, and don't necessarily
1227      * want to be told the answer to the puzzle!)
1228      */
1229     if (me->aux_info) {
1230         unsigned char *s1;
1231         char *s2;
1232         int len;
1233
1234         len = strlen(me->aux_info);
1235         s1 = snewn(len, unsigned char);
1236         memcpy(s1, me->aux_info, len);
1237         obfuscate_bitmap(s1, len*8, FALSE);
1238         s2 = bin2hex(s1, len);
1239
1240         wr("AUXINFO", s2);
1241
1242         sfree(s2);
1243         sfree(s1);
1244     }
1245
1246     /*
1247      * Any required serialisation of the game_ui.
1248      */
1249     if (me->ui) {
1250         char *s = me->ourgame->encode_ui(me->ui);
1251         if (s) {
1252             wr("UI", s);
1253             sfree(s);
1254         }
1255     }
1256
1257     /*
1258      * The game time, if it's a timed game.
1259      */
1260     if (me->ourgame->is_timed) {
1261         char buf[80];
1262         sprintf(buf, "%g", me->elapsed);
1263         wr("TIME", buf);
1264     }
1265
1266     /*
1267      * The length of, and position in, the states list.
1268      */
1269     {
1270         char buf[80];
1271         sprintf(buf, "%d", me->nstates);
1272         wr("NSTATES", buf);
1273         sprintf(buf, "%d", me->statepos);
1274         wr("STATEPOS", buf);
1275     }
1276
1277     /*
1278      * For each state after the initial one (which we know is
1279      * constructed from either privdesc or desc), enough
1280      * information for execute_move() to reconstruct it from the
1281      * previous one.
1282      */
1283     for (i = 1; i < me->nstates; i++) {
1284         assert(me->states[i].movetype != NEWGAME);   /* only state 0 */
1285         switch (me->states[i].movetype) {
1286           case MOVE:
1287             wr("MOVE", me->states[i].movestr);
1288             break;
1289           case SOLVE:
1290             wr("SOLVE", me->states[i].movestr);
1291             break;
1292           case RESTART:
1293             wr("RESTART", me->states[i].movestr);
1294             break;
1295         }
1296     }
1297
1298 #undef wr
1299 }
1300
1301 /*
1302  * This function returns NULL on success, or an error message.
1303  */
1304 char *midend_deserialise(midend_data *me,
1305                          int (*read)(void *ctx, void *buf, int len),
1306                          void *rctx)
1307 {
1308     int nstates = 0, statepos = -1, gotstates = 0;
1309     int started = FALSE;
1310     int i;
1311
1312     char *val = NULL;
1313     /* Initially all errors give the same report */
1314     char *ret = "Data does not appear to be a saved game file";
1315
1316     /*
1317      * We construct all the new state in local variables while we
1318      * check its sanity. Only once we have finished reading the
1319      * serialised data and detected no errors at all do we start
1320      * modifying stuff in the midend_data passed in.
1321      */
1322     char *seed = NULL, *parstr = NULL, *desc = NULL, *privdesc = NULL;
1323     char *auxinfo = NULL, *uistr = NULL, *cparstr = NULL;
1324     float elapsed = 0.0F;
1325     game_params *params = NULL, *cparams = NULL;
1326     game_ui *ui = NULL;
1327     struct midend_state_entry *states = NULL;
1328
1329     /*
1330      * Loop round and round reading one key/value pair at a time
1331      * from the serialised stream, until we have enough game states
1332      * to finish.
1333      */
1334     while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
1335         char key[9], c;
1336         int len;
1337
1338         do {
1339             if (!read(rctx, key, 1)) {
1340                 /* unexpected EOF */
1341                 goto cleanup;
1342             }
1343         } while (key[0] == '\r' || key[0] == '\n');
1344
1345         if (!read(rctx, key+1, 8)) {
1346             /* unexpected EOF */
1347             goto cleanup;
1348         }
1349
1350         if (key[8] != ':') {
1351             if (started)
1352                 ret = "Data was incorrectly formatted for a saved game file";
1353             goto cleanup;
1354         }
1355         len = strcspn(key, ": ");
1356         assert(len <= 8);
1357         key[len] = '\0';
1358
1359         len = 0;
1360         while (1) {
1361             if (!read(rctx, &c, 1)) {
1362                 /* unexpected EOF */
1363                 goto cleanup;
1364             }
1365
1366             if (c == ':') {
1367                 break;
1368             } else if (c >= '0' && c <= '9') {
1369                 len = (len * 10) + (c - '0');
1370             } else {
1371                 if (started)
1372                     ret = "Data was incorrectly formatted for a"
1373                     " saved game file";
1374                 goto cleanup;
1375             }
1376         }
1377
1378         val = snewn(len+1, char);
1379         if (!read(rctx, val, len)) {
1380             if (started)
1381             goto cleanup;
1382         }
1383         val[len] = '\0';
1384
1385         if (!started) {
1386             if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
1387                 /* ret already has the right message in it */
1388                 goto cleanup;
1389             }
1390             /* Now most errors are this one, unless otherwise specified */
1391             ret = "Saved data ended unexpectedly";
1392             started = TRUE;
1393         } else {
1394             if (!strcmp(key, "VERSION")) {
1395                 if (strcmp(val, SERIALISE_VERSION)) {
1396                     ret = "Cannot handle this version of the saved game"
1397                         " file format";
1398                     goto cleanup;
1399                 }
1400             } else if (!strcmp(key, "GAME")) {
1401                 if (strcmp(val, me->ourgame->name)) {
1402                     ret = "Save file is from a different game";
1403                     goto cleanup;
1404                 }
1405             } else if (!strcmp(key, "PARAMS")) {
1406                 sfree(parstr);
1407                 parstr = val;
1408                 val = NULL;
1409             } else if (!strcmp(key, "CPARAMS")) {
1410                 sfree(cparstr);
1411                 cparstr = val;
1412                 val = NULL;
1413             } else if (!strcmp(key, "SEED")) {
1414                 sfree(seed);
1415                 seed = val;
1416                 val = NULL;
1417             } else if (!strcmp(key, "DESC")) {
1418                 sfree(desc);
1419                 desc = val;
1420                 val = NULL;
1421             } else if (!strcmp(key, "PRIVDESC")) {
1422                 sfree(privdesc);
1423                 privdesc = val;
1424                 val = NULL;
1425             } else if (!strcmp(key, "AUXINFO")) {
1426                 unsigned char *tmp;
1427                 int len = strlen(val) / 2;   /* length in bytes */
1428                 tmp = hex2bin(val, len);
1429                 obfuscate_bitmap(tmp, len*8, TRUE);
1430
1431                 sfree(auxinfo);
1432                 auxinfo = snewn(len + 1, char);
1433                 memcpy(auxinfo, tmp, len);
1434                 auxinfo[len] = '\0';
1435                 sfree(tmp);
1436             } else if (!strcmp(key, "UI")) {
1437                 sfree(uistr);
1438                 uistr = val;
1439                 val = NULL;
1440             } else if (!strcmp(key, "TIME")) {
1441                 elapsed = atof(val);
1442             } else if (!strcmp(key, "NSTATES")) {
1443                 nstates = atoi(val);
1444                 if (nstates <= 0) {
1445                     ret = "Number of states in save file was negative";
1446                     goto cleanup;
1447                 }
1448                 if (states) {
1449                     ret = "Two state counts provided in save file";
1450                     goto cleanup;
1451                 }
1452                 states = snewn(nstates, struct midend_state_entry);
1453                 for (i = 0; i < nstates; i++) {
1454                     states[i].state = NULL;
1455                     states[i].movestr = NULL;
1456                     states[i].movetype = NEWGAME;
1457                 }
1458             } else if (!strcmp(key, "STATEPOS")) {
1459                 statepos = atoi(val);
1460             } else if (!strcmp(key, "MOVE")) {
1461                 gotstates++;
1462                 states[gotstates].movetype = MOVE;
1463                 states[gotstates].movestr = val;
1464                 val = NULL;
1465             } else if (!strcmp(key, "SOLVE")) {
1466                 gotstates++;
1467                 states[gotstates].movetype = SOLVE;
1468                 states[gotstates].movestr = val;
1469                 val = NULL;
1470             } else if (!strcmp(key, "RESTART")) {
1471                 gotstates++;
1472                 states[gotstates].movetype = RESTART;
1473                 states[gotstates].movestr = val;
1474                 val = NULL;
1475             }
1476         }
1477
1478         sfree(val);
1479         val = NULL;
1480     }
1481
1482     params = me->ourgame->default_params();
1483     me->ourgame->decode_params(params, parstr);
1484     if (me->ourgame->validate_params(params, TRUE)) {
1485         ret = "Long-term parameters in save file are invalid";
1486         goto cleanup;
1487     }
1488     cparams = me->ourgame->default_params();
1489     me->ourgame->decode_params(cparams, cparstr);
1490     if (me->ourgame->validate_params(cparams, FALSE)) {
1491         ret = "Short-term parameters in save file are invalid";
1492         goto cleanup;
1493     }
1494     if (seed && me->ourgame->validate_params(cparams, TRUE)) {
1495         /*
1496          * The seed's no use with this version, but we can perfectly
1497          * well use the rest of the data.
1498          */
1499         sfree(seed);
1500         seed = NULL;
1501     }
1502     if (!desc) {
1503         ret = "Game description in save file is missing";
1504         goto cleanup;
1505     } else if (me->ourgame->validate_desc(params, desc)) {
1506         ret = "Game description in save file is invalid";
1507         goto cleanup;
1508     }
1509     if (privdesc && me->ourgame->validate_desc(params, privdesc)) {
1510         ret = "Game private description in save file is invalid";
1511         goto cleanup;
1512     }
1513     if (statepos < 0 || statepos >= nstates) {
1514         ret = "Game position in save file is out of range";
1515     }
1516
1517     states[0].state = me->ourgame->new_game(me, params,
1518                                             privdesc ? privdesc : desc);
1519     for (i = 1; i < nstates; i++) {
1520         assert(states[i].movetype != NEWGAME);
1521         switch (states[i].movetype) {
1522           case MOVE:
1523           case SOLVE:
1524             states[i].state = me->ourgame->execute_move(states[i-1].state,
1525                                                         states[i].movestr);
1526             if (states[i].state == NULL) {
1527                 ret = "Save file contained an invalid move";
1528                 goto cleanup;
1529             }
1530             break;
1531           case RESTART:
1532             if (me->ourgame->validate_desc(params, states[i].movestr)) {
1533                 ret = "Save file contained an invalid restart move";
1534                 goto cleanup;
1535             }
1536             states[i].state = me->ourgame->new_game(me, params,
1537                                                     states[i].movestr);
1538             break;
1539         }
1540     }
1541
1542     ui = me->ourgame->new_ui(states[0].state);
1543     me->ourgame->decode_ui(ui, uistr);
1544
1545     /*
1546      * Now we've run out of possible error conditions, so we're
1547      * ready to start overwriting the real data in the current
1548      * midend. We'll do this by swapping things with the local
1549      * variables, so that the same cleanup code will free the old
1550      * stuff.
1551      */
1552     {
1553         char *tmp;
1554
1555         tmp = me->desc;
1556         me->desc = desc;
1557         desc = tmp;
1558
1559         tmp = me->privdesc;
1560         me->privdesc = privdesc;
1561         privdesc = tmp;
1562
1563         tmp = me->seedstr;
1564         me->seedstr = seed;
1565         seed = tmp;
1566
1567         tmp = me->aux_info;
1568         me->aux_info = auxinfo;
1569         auxinfo = tmp;
1570     }
1571
1572     me->genmode = GOT_NOTHING;
1573
1574     me->statesize = nstates;
1575     nstates = me->nstates;
1576     me->nstates = me->statesize;
1577     {
1578         struct midend_state_entry *tmp;
1579         tmp = me->states;
1580         me->states = states;
1581         states = tmp;
1582     }
1583     me->statepos = statepos;
1584
1585     {
1586         game_params *tmp;
1587
1588         tmp = me->params;
1589         me->params = params;
1590         params = tmp;
1591
1592         tmp = me->curparams;
1593         me->curparams = cparams;
1594         cparams = tmp;
1595     }
1596
1597     me->oldstate = NULL;
1598     me->anim_time = me->anim_pos = me->flash_time = me->flash_pos = 0.0F;
1599     me->dir = 0;
1600
1601     {
1602         game_ui *tmp;
1603
1604         tmp = me->ui;
1605         me->ui = ui;
1606         ui = tmp;
1607     }
1608
1609     me->elapsed = elapsed;
1610     me->pressed_mouse_button = 0;
1611
1612     midend_set_timer(me);
1613
1614     if (me->drawstate)
1615         me->ourgame->free_drawstate(me->drawstate);
1616     me->drawstate =
1617         me->ourgame->new_drawstate(me->states[me->statepos-1].state);
1618     midend_size_new_drawstate(me);
1619
1620     ret = NULL;                        /* success! */
1621
1622     cleanup:
1623     sfree(val);
1624     sfree(seed);
1625     sfree(parstr);
1626     sfree(cparstr);
1627     sfree(desc);
1628     sfree(privdesc);
1629     sfree(auxinfo);
1630     sfree(uistr);
1631     if (params)
1632         me->ourgame->free_params(params);
1633     if (cparams)
1634         me->ourgame->free_params(cparams);
1635     if (ui)
1636         me->ourgame->free_ui(ui);
1637     if (states) {
1638         int i;
1639
1640         for (i = 0; i < nstates; i++) {
1641             if (states[i].state)
1642                 me->ourgame->free_game(states[i].state);
1643             sfree(states[i].movestr);
1644         }
1645         sfree(states);
1646     }
1647
1648     return ret;
1649 }