#include "mcdp.h"

static short wmdb_testdisk(char *fn, struct mcdp *cd);

/* test the disk lenght */
static short wmdb_testdisk(char *fn, struct mcdp *cd) {
register int pos=0,i=0;
 while(fn[i++]!='\0')
  if(fn[i]==' ') pos=i; /* jump spaces */
 if(atoi(fn+pos)==cd->t[0].cddb) return 1;
 return 0;
}

int wmdb_getentries(struct mcdp *cd) {
 char *fn=malloc(sizeof(char)*PATH_MAX);
 int p=0,tr=0,len,fd; /* p=parse;tr=track */
 char ch;
/* i know that there must have a global file, but i don't remember where */
 len=_snprintf(fn,PATH_MAX-1,"%s/%s",getenv("HOME"),".workmandb");
 fn[len]='\0';
 if ((fd=open(fn,O_RDONLY))<0) {
  free(fn); return CDDB_NOENT;
 }
 len=0;
 while (len+=read(fd,&ch,1)>0) {
  fn[len-1]=ch;
  if (ch=='\n'||ch=='\r') {
   p=1;fn[len-1]='\0';len=0;
  }
  if (p) {
   if (!strncmp(fn, "tracks ", 7))
    if(wmdb_testdisk(fn,&cd[0]))
     while (len+=read(fd,&ch,1)>0) { /* this is one possible match */
      fn[len-1]=ch;
      if (ch=='\n'||ch=='\r') {
       p=1;fn[len-1]='\0';len=0;
      }
      if (p) {
       if (!strncmp(fn,"cdname ",7)) {
        str_ncpy(cd->t[0].name, fn+7, str_len(fn));
       } else if (!strncmp(fn,"artist ",7)) {
        strncat(cd->t[0].name," >> ",4);
        strncat(cd->t[0].name, fn+7, str_len(fn));
       } else if (!strncmp(fn,"track ", 6)) {
        str_ncpy(cd->t[++tr].name, fn+6, str_len(fn));
       } else if (!strncmp(fn,"tracks ", 7)) { break; }
       p=0;
      }
     }
   p=0;
  }
 } /* while() */
 free(fn);
 if (tr) return CDDB_WORKMAN;
 return CDDB_NOENT;
}
