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