#include <stdio.h>
#include <stdlib.h>

#include <sys/errno.h>

struct point 
{
	int x, y;
	char c;
};

size_t scrWidth, scrHeight;

int compare(struct point *a, struct point *b)
{
	if(a->x < b->x) {
		return -1;
	} else if(a->x > b->x) {
		return 1;
	}

	if(a->y < b->y) {
		return -1;
	} else if(a->y > b->y) {
		return 1;
	}

	return 0;
}

void fill_point(struct point *p, int x, int y, char c)
{
	p->x = x;
	p->y = y;
	p->c = c;
}

void draw(struct point *graph)
{
	int x,y,i=-1;
	struct point p;
	for(y=0;y<scrHeight;y++) {
		for(x=0;i<scrWidth;x++) {
			fill_point(&p,x,y,NULL);
			if(compare(&p,&graph[++i])==0) {
				printf("%c",graph[i].c);
			} else {
				printf(" ");
			}
		}
	}
}

void read(struct point **graph, FILE *fp, size_t *len)
{
	int x,y,i;
	char c, buf[20];
	printf("fgets.\n");
	fgets(buf,20,fp);
	printf("sscanf.\n");
	sscanf(buf,"%i",len);
	printf("malloc.\n");
	(*graph) = malloc((*len) * (sizeof(**graph)));
	printf("size of array should be %i which is %i\n",
	       *len,(*len) * (sizeof(**graph)));
	for(i=0;i<(*len);i++) {
		printf("\tin for. i==%i and *len==%i\n",i,*len);
		printf("\tfgets\n");
		if(!fgets(buf,20,fp)) {
			perror("fgets");
			return;
		}
		printf("\tsscanf\n");
		sscanf(buf,"%i %i %c",&x,&y,&c);
		printf("\tfill_point\n");
		fill_point(graph[i],x,y,c);
		printf("%i %i %c\n",graph[i]->x,graph[i]->y,graph[i]->c);
	}
}

int main(int argc, char *argv[])
{
	size_t len;
	FILE *fp;
	struct point *graph;
	if(argc<2) {
		printf("usage: %s <file>\n",argv[0]);
		return 0;
	}
	if(!(fp = fopen(argv[1],"r"))) {
		printf("%s: %s: %s\n",argv[0],argv[1],strerror(errno));
		return 0;
	}
	read(&graph,fp,&len);
	draw(graph);
	free(graph);
	return 0;
}

