#include "attractions.h"
#include "utils.h"
#include "main.h"
int count=0;

ATTRACTION * attractions[MAXNUM];
extern char attr_ifile[128];
extern int attr_width;
extern int  attr_height;
extern int basezoom;

int load_attractions(char * file, char * zipfile, int datatype, int mapx, int mapy, int zoomlevel) {

	FILE *fp;
	char line[256];
	ATTRACTION * attr;
	Coord c;
	int rd, square;

	strcpy(attr_ifile,"");
	attr_width=16;
	attr_height=8;

	if (datatype==1) {
                unzipFile(zipfile,file,file);
                fp = fopen(file, "r");
        } else {
                sprintf(line, "%s/%s",zipfile,file);
                 fp = fopen(line, "r");
        }

	if (fp==NULL) {
		printf("couldn't open file: %s\n", file); 
		return -1;

	}

	while(fgets(line,256,fp) != NULL) {
		if (strlen(line) < 10 || line[0]=='#')
			continue;

		if (strncmp(line,"!IMAGE:",7)==0) {
			strcpy(attr_ifile,strtok(&line[7], ","));
			attr_width=atoi(strtok(NULL, ","));
			attr_height=atoi(strtok(NULL, ","));
			continue;
		}

		c=getXY(atof(strtok(line, ",")),atof(strtok(NULL, ",")),basezoom);

		if (abs((int)c.lon-mapx)<PSP_WIDTH*powerOf(zoomlevel-1) && abs((int)c.lat-mapy) < PSP_HEIGHT*powerOf(zoomlevel-1)){ 
		 	attr=(ATTRACTION*)malloc(sizeof(ATTRACTION));
		 	if (attr==NULL) {
				printf("couldn't allocate memory for rec#: %d\n", count); 
				break;
		 	}
			attr->x=(int)c.lon;
			attr->y=(int)c.lat;
			strncpy(attr->name,strtok(NULL, ","),37);
			attr->name[37]=0;
			toUpperCase(attr->name);
			strncpy(attr->details,strtok(NULL, ","),14);
			attr->details[14]=0;
			toUpperCase(attr->details);
			attractions[count++]=attr;
		//	printf ("%d %d %s %s\n", attr->x, attr->y, attr->name, attr->details);
		}

			if (count>=MAXNUM-1)
				break;

	}
	fclose(fp);
	if (datatype==1)
                remove(file);

	//printf("loaded: %d records\n", count);
	return count;

}

void free_attractions() {
	int i;
	for (i=0; i<count; i++) {
		if (attractions[i]!=NULL) {
			free(attractions[i]);
		}
	}
	count=0;
}

int attractions_count() {
	return count;
}
