#include "sprite.h"

VG_SPRITE_DATA * vg_sprite_load_fp(PACKFILE * fp)
{
	int i;
	int states;
	int temp;
	VG_SPRITE_DATA * sp;

	sp = vg_sprite_create();
	if(!sp)
	{
		return NULL;
	}

	states = pack_igetl(fp);
	for(i = 0; i < states; i++)
	{
		temp = pack_igetl(fp);
		if(temp)
		{
			sp->ap[i] = load_ani_fp(fp, NULL);
		}
		else
		{
			sp->ap[i] = NULL;
		}
		sp->cx[i] = pack_igetl(fp);
		sp->cy[i] = pack_igetl(fp);
		sp->cw[i] = pack_igetl(fp);
		sp->ch[i] = pack_igetl(fp);
	}
	return sp;
}

VG_SPRITE_DATA * vg_sprite_load(char * fn)
{
	PACKFILE * fp;
	int type;
	char ffn[1024];
	VG_SPRITE_DATA * sp;
	
	fp = pack_fopen(fn, "r");
	if(!fp)
	{
		return 0;
	}
	sp = vg_sprite_load_fp(fp);
	pack_fclose(fp);
	return sp;
}

int vg_sprite_save_fp(VG_SPRITE_DATA * sp, PACKFILE * fp)
{
	int i;

	pack_iputl(VG_SPRITE_MAX_STATES, fp);
	for(i = 0; i < VG_SPRITE_MAX_STATES; i++)
	{
		if(sp->ap[i])
		{
			pack_iputl(1, fp);
			save_ani_fp(sp->ap[i], fp, NULL);
		}
		else
		{
			pack_iputl(0, fp);
		}
		pack_iputl(sp->cx[i], fp);
		pack_iputl(sp->cy[i], fp);
		pack_iputl(sp->cw[i], fp);
		pack_iputl(sp->ch[i], fp);
	}
}

int vg_sprite_save(VG_SPRITE_DATA * sp, char * fn)
{
	PACKFILE * fp;

	fp = pack_fopen(fn, "w");
	if(!fp)
	{
		return 0;
	}
	vg_sprite_save_fp(sp, fp);
	pack_fclose(fp);
	return 1;
}

void vg_sprite_destroy(VG_SPRITE_DATA * sp)
{
	if(sp)
	{
		free(sp);
	}
}

VG_SPRITE_DATA * vg_sprite_create(void)
{
	int i;
	VG_SPRITE_DATA * sp;
	
	sp = malloc(sizeof(VG_SPRITE_DATA));
	if(!sp)
	{
		return NULL;
	}
	
	for(i = 0; i < VG_SPRITE_MAX_STATES; i++)
	{
		sp->ap[i] = NULL;
		sp->cx[i] = 0;
		sp->cy[i] = 0;
		sp->cw[i] = 0;
		sp->ch[i] = 0;
	}
	return sp;
}
