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

#include "parser.h"

#define BUFLEN 16384

int parse_placement(char *file, vector<net> &vn, vector<pin> &vp,
		    int &width, int &height)
{
	FILE *fp;
	char buf[BUFLEN];
	char *cret,*cptr;
	int iret;
	int lcount=0;
	int num_nets;
	int i,tx,ty;

	fp=fopen(file,"r");
	if (fp==NULL) {
		fprintf(stderr,"parse_placement: couldn't open file:%s\n",file);
		return -1;
	}

	// we assume that the first line is "<width> <height>"
	cret=fgets(buf,BUFLEN,fp);
	if (cret==NULL || strlen(cret)>(BUFLEN-2)) {
		fprintf(stderr,"parse_placement: invalid height/width line: %s\n",buf);
		return -1;
	}

	width=strtol(buf,&cptr,10);
	if (buf==cptr) {
		fprintf(stderr,"parse_placement: invalid height/width line: %s\n",buf);
		return -1;
	}

    	height=strtol(cptr,&cret,10);
	if (cret==cptr) {
		fprintf(stderr,"parse_placement: invalid height/width line: %s\n",buf);
		return -1;
	}

       	// now we read in the ned lines one at a time
	for  (lcount=2,fgets(buf,BUFLEN,fp);!feof(fp);fgets(buf,BUFLEN,fp),lcount++) {
		if (buf[0]=='#') continue;
		if (strlen(buf)>(BUFLEN-2)) {
			fprintf(stderr,"%s:%i line too long!\n",file,lcount);
			vn.clear(); vp.clear();
			return -1;
		}
		net n;
		n.id=strtol(buf,&cret,10);
		if (buf==cret) {
			fprintf(stderr,"%s:%i invalid net ID\n",file,lcount);
			vn.clear(); vp.clear();
			return -1;
		}
		cptr=cret;
		num_nets=strtol(cptr,&cret,10);
		if (cret==cptr) {
			fprintf(stderr,"%s:%i invalid net ID\n",file,lcount);
			vn.clear(); vp.clear();
			return -1;
		}
		cptr=cret;
		
		for (i=0;i<num_nets;i++) {
			pin p;
			p.x=strtol(cptr,&cret,10);
			if (cptr==cret) {
				fprintf(stderr,"%s:%i invalid pin xpos\n",file,lcount);
				vn.clear(); vp.clear();
				return -1;
			}
			cptr=cret;
			p.y=strtol(cptr,&cret,10);
			if (cptr==cret) {
				fprintf(stderr,"%s:%i invalid pin ypos\n",file,lcount);
				vn.clear(); vp.clear();
				return -1;
			}
			cptr=cret;
			if (p.x==0 || p.x==(width-1) || p.y==0 || p.y==(height-1)) p.pad=true;
			else p.pad=false;
			p.net=n.id;

			if (p.x<0 || p.x>=width || p.y<0 || p.y>=height) {
				fprintf(stderr,"%s:%i (%i,%i) pin outside grid area\n",
					file,lcount,p.x,p.y);
				vn.clear();
				vp.clear();
				return -1;
			}
			
			n.pins.push_back(p);
			vp.push_back(p);
		}
		vn.push_back(n);
	}
	return 0;
}