#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "catread.h"
void chkdoc(FILE *fdoc,int tag,int iver);

int main()
{
  static double qln[7];
  static char dname[64];
  FILE *fdoc, *fcat;
  char *match, *molnam, *fname;
  long flen;
  int iver, totlines,  nspec, nlines, tag;

  tag = 0; nspec = 0; totlines = 0;
  while(nxtdir(&tag) > 0) {
    molnam = catdir(tag, &nlines, qln, &iver);
    ++nspec;
    totlines += nlines;
    fname = catfil(tag);
    fcat = fopen(fname, "r");
    if (fcat == NULL) {
      printf("UNABLE TO OPEN FILE: %s",fname);
      continue; 
    }
    fseek(fcat, 0, SEEK_END); 
    flen = ftell(fcat);
    if (flen != (long)nlines * 81) {
      printf("problem with length: %s %d %d\n ", fname, nlines, 
       (int)(flen / 81));
    }
    match = strstr(fname,"c0");
    if (match == NULL) match = strstr(fname,"c1");
    if (match == NULL) continue;
    *match=0;
    strcpy(dname, fname); *match = 'c'; 
    strcat(dname,"doc/d"); strcat(dname,match+1);  
    fdoc = fopen(dname,"r");
    if (fdoc == NULL){
      printf("MISSING: %s\n", dname);
    } else {
      chkdoc(fdoc, tag, iver);
    }
    fclose(fcat); fclose(fdoc);
  }
  printf("%d species, %d lines\n", nspec, totlines); 
  return 0;
} /* main */

void chkdoc(FILE *fdoc,int tag,int iver)
{
  char *match;
  static char line[82];
  fgets(line, 82, fdoc);
  match = strchr(line,'&');
  if (match){
    if (match[1] == 0) 
      match = NULL;
    else if (tag != atoi(&match[2]))
      match = NULL;
  }
  if (match == NULL){
    match = strchr(line,'\n');
    if (match == NULL) *match = 0;
    printf("%d BAD TAG LINE:%s\n",tag,line);
    return;
  }  
  fgets(line, 82, fdoc);
  match = strchr(line,'&');
  if (match){
    if (match[1] == 0) 
      match = NULL;
    else if (iver != atoi(&match[2]))
      match = NULL;
  }
  if (match == NULL){
    match = strchr(line,'\n');
    if (match == NULL) *match = 0;
    printf("%d BAD VER LINE:%s\n",tag,line);
    return;
  }  
} /* chkdoc */