/* map-save.m,
 *
 * Map saving order.  Also does magic and version stuff.
 */

#include <allegro.h>
#include <assert.h>
#include <objc/Object.h>
#include "common.h"
#include "map-save.h"
#include "map.h"
#include "seborrhea/seborrhea.h"
#include "unit-save.h"


#define MAGIC_STR		"Raid Map "
#define MAP_VERSION		"0.2"
#define MAGIC_LENGTH		(9+1)


void save_map(const char *filename)
{
    PACKFILE *fp;

    assert(filename && current_map);

    fp = pack_fopen(filename, "wp");
    if (not fp)
	return;

    /* Magic and version number. */
    pack_fputs(MAGIC_STR, fp);
    pack_fputs(MAP_VERSION, fp);
    pack_putc('\n', fp);

    /* The music file. */
    pack_fputs([current_map musicDirname], fp);
    pack_putc('\n', fp);

    /* The map. */
    [current_map saveTo:fp];

    /* The units. */
    save_unit_lists(fp);

    pack_fclose(fp);
}


BOOL load_map(const char *filename, BOOL for_map_editor)
{
    PACKFILE *fp = NULL;
    char magic[MAGIC_LENGTH], version[16], music_fn[PATH_MAX];
    int i;

    assert(filename);

    fp = pack_fopen(filename, "rp");

    /* Didn't find the map.  Try looking in seborrhea data directories. */
    for (i = 0; not fp && seborrhea_data_root_directories[i]; i++) {
	char work[PATH_MAX];

	snprintf(work, sizeof work, "%s/%s", seborrhea_data_root_directories[i], filename);
	fp = pack_fopen(work, "rp");
    }

    if (not fp)
	return NO;

    /* Magic and version number. */
    pack_fgets(magic, MAGIC_LENGTH, fp);
    pack_fgets(version, sizeof version, fp);

    if (strneq(magic, MAGIC_STR)) {
	fprintf(stderr, "Magic mismatch in %s!\nGot '%s', expecting '%s'.\n", filename, magic, MAGIC_STR);
	goto error;
    }
    else if (strcmp(version, MAP_VERSION) > 0) {
	fprintf(stderr, "Warning: The map is in a newer format (%s) and may contain errors.\n", version);
    }
    else if (strcmp(version, MAP_VERSION) < 0) {
	fprintf(stderr, "Warning: The map is in an older format (%s) and may contain errors.\n", version);
    }

    /* Music. */
    pack_fgets(music_fn, sizeof music_fn, fp);
    [current_map setMusicDirname:music_fn];

    /* The map. */
    [current_map loadFrom:fp version:version];

    /* The units. */
    if (not load_unit_lists(fp, for_map_editor)) {
	fprintf(stderr, "Error loading units in %s!\n", filename);
	goto error;
    }

    pack_fclose(fp);
    return YES;

 error:
    if (fp)
	pack_fclose(fp);
    return NO;
}
