#include <stdio.h>

#include <concorde.h>
#include "ysmaze2.h"
#include "mzedit.h"
#include "ysgui.h"


extern int errno;

int LoadMazeData(MAZEMAP *mz,char *fname)
{
	FILE *fp;
	int l,bl,bh,lx,ly;

	fp=fopen(fname,"rb");
	if(fp==NULL)
	{
		return -1;
	}

	errno=0;

	l=FileSize(fp);
	fread(&bl,4,1,fp);
	fread(&bh,4,1,fp);
	fread(&lx,4,1,fp);
	fread(&ly,4,1,fp);
	if(lx>=MAZE_SIZE_X_MAX || ly>=MAZE_SIZE_Y_MAX)
	{
		fclose(fp);
		return -1;
	}
	mz->bl=bl;
	mz->bh=bh;
	mz->lx=lx;
	mz->ly=ly;
	fread(mz->map,1,l-16,fp);

	fclose(fp);

	if(errno==0)
	{
		return 0;
	}
	else
	{
		return -1;
	}
}

int SaveMazeData(MAZEMAP *mz,char *fname)
{
	int l;
	FILE *fp;

	fp=fopen(fname,"wb");
	if(fp==NULL)
	{
		return -1;
	}

	errno=0;

	l=(mz->lx)*(mz->ly);
	fwrite(&(mz->bl),4,1,fp);
	fwrite(&(mz->bh),4,1,fp);
	fwrite(&(mz->lx),4,1,fp);
	fwrite(&(mz->ly),4,1,fp);
	fwrite(mz->map,2,l,fp);

	fclose(fp);

	if(errno==0)
	{
		return 0;
	}
	else
	{
		return -1;
	}
}

void PutExt(char *fname,char *ext)
{
	int i;

	for(i=0; fname[i]!=0; i++)
	{
		if(fname[i]=='.')
		{
			return;
		}
	}

	sprintf(fname,"%s%s",fname,ext);
}

unsigned FileSize(FILE *fp)
{
    int fptr,edptr;

    fptr = ftell(fp);
    fseek(fp,0,SEEK_END);
    edptr = ftell(fp);
    fseek(fp,fptr,SEEK_SET);
    return edptr;
}

