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

typedef struct node_parent {
	int data;
	struct node_child *child;
	struct node_parent *next;
} NodeP;

typedef struct node_child {
	int data;
	struct node_child *next;
} NodeC;

int main()
{
	FILE* pFile;
	char string[100],c[10];
	char* token;
	NodeC *curC, *headC, *curC2, *headC2;
	NodeP *NetArray, *CellArray, *curP;
	int i,max_c=0;

	//printf("%d\n", sizeof(Node));
	pFile = fopen("p2-3.in", "r");
	if( pFile == NULL) {
		perror ("Error opening file!");
		return 0;
	}

	NetArray=NULL;

	while(!feof(pFile)) {	//處理整個檔案
		fgets(string, 100, pFile);
		//printf("line=%s\n", string);
		token = strtok(string, " ");
		while( token != NULL ) {	//處理某一行
			//printf("token-0=%c\n", token[0]);
			if( token[0] == 'n' ) {
				//printf("n=%s\n", token);
				curP=(NodeP*)malloc(sizeof(NodeP));
				strcpy(c, token+1);
				curP->data=atoi(c); //取得n後面的號碼
				headC=NULL;
			}
			if( token[0] == 'c' ) {
				strcpy(c, token+1);
				curC=(NodeC*)malloc(sizeof(NodeC));
				curC->data=atoi(c);
				if( atoi(c) > max_c )
					max_c = atoi(c);
				curC->next=headC;
				headC=curC;
				//printf(" %s,", c);
			}
			if( token[0] == '}' ) {
				curP->child = headC;
				curP->next=NetArray;
				NetArray=curP;
				//printf("\n");
			}
			//printf(" token=%s", token);

			token = strtok(NULL, " ");
		}
		//printf("%s\n", string);
	}
	fclose(pFile);

	printf("max_c=%d\n", max_c);
	CellArray = (NodeP*)malloc(sizeof(NodeP)*max_c);
	//讀出
	curP=NetArray;
	while(curP) {
		printf("n=%d\n", curP->data);
		curC=curP->child;
		while(curC) {
			printf(" %d,", curC->data);

			//新建立子節點
			CellArray[curC->data - 1].data=curC->data;
			curC2 = (NodeC*)malloc(sizeof(NodeC));
			curC2->data=curP->data;
			curC2->next=CellArray[curC->data-1].child;
			CellArray[curC->data-1].child=curC2;

			curC=curC->next;
		}
		printf("\n");
		curP=curP->next;
	}

	for(i=0;i<max_c;i++) {
		curC=CellArray[i].child;
		printf("c=%d\n", CellArray[i].data);
		while(curC) {
			printf(" %d,", curC->data);
			curC = curC->next;
		}
		printf("\n");
	}

	return 0;
}

