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

#define MAXWIDTH   80
#define MAXLINES  750
#define SEP         9    /* a TAB, randomly chosen separator of columns :*/
#define SEPSTR   "\t"    /* Same, now in string format */

char table[MAXLINES][MAXWIDTH+1];
int width[MAXWIDTH+1],totwidth[MAXWIDTH+1];
int lines,columns,curcol;
char sym[MAXWIDTH+1];

void InitTable() {
  int i;
  lines=columns=0;
  for (i=0;i<MAXLINES;i++) table[i][0]='\0';
  for (i=0;i<MAXWIDTH;i++) width[i]=0;
}


void NextSym() {
  char str[MAXWIDTH+1];
  if (scanf(" <%[^>]>",str)) {
    sprintf(sym,"<%s>",str);
  } else {
    scanf("%[^< \n]",sym);
  }
}

void ReadItem() {
  if (!strcmp("<TD>",sym)) {
    int itemwidth=0;
    if (curcol) strcat(table[lines],SEPSTR);
    NextSym(); /* useful string or </TD> */
    while (strcmp("</TD>",sym)) {
      if (itemwidth) {
        itemwidth++;
        strcat(table[lines]," ");
      }
      itemwidth+=strlen(sym);
      strcat(table[lines],sym);
      if (itemwidth>width[curcol]) width[curcol]=itemwidth;
      NextSym();
    }
    curcol++; 
    if (curcol>columns) columns++;
  }
}

void ReadLine() {
  int i;
  if (!strcmp("<TR>",sym)) {
    curcol=0;
    NextSym(); /* <TD> or </TR> */
    while (strcmp("</TR>",sym)) {
      ReadItem();
      NextSym();
    }
    for (i=strlen(table[lines]);i<MAXWIDTH;i++) table[lines][i]=SEP;
    lines++;
  }
}

void ReadTable() {
  NextSym(); /* assume this IS <TABLE> */
  NextSym(); /* <TR> or </TABLE> */
  while (strcmp("</TABLE>",sym)) {
    ReadLine();
    NextSym();
  }
}

void WriteRuler() {
  int i,j;
  for (i=0;i<columns;i++) {
    printf("+");
    for (j=0;j<=width[i];j++) printf("-");
    if (width[i]) printf("-");
  }
  printf("+\n");
}

void WriteTable() {
  int i,j,k; /* run through table&width */
  int pos;   /* run over screen (without delimiters) */
  totwidth[0]=width[0];
  for (k=1;k<MAXWIDTH;k++) totwidth[k]=totwidth[k-1]+width[k];
  WriteRuler();
  for (i=0;i<lines;i++) {
    k=pos=0;
    for (j=0;j<columns;j++) {
      printf("| ");
      while (table[i][k]!=SEP) {
        printf("%c",table[i][k]);
        k++; /* printed char */
        pos++;
      }
      k++; /* SEP itself */
      for (;pos<totwidth[j];pos++) printf(" ");
      if (width[j]) printf(" ");
    }
    printf("|\n");
    WriteRuler();
  }
}

int main() {
  int r,runs;
  scanf("%d",&runs);
  for (r=0;r<runs;r++) {
    InitTable();
    ReadTable();
    WriteTable();
  }
  return(0);
}

Generated by Java2Html