#include <stdlib.h>
#include <string.h>
#include "parts.h"

/*
part known[] = {
                {"XC18V01","f5034093","0ffeffff","alg_18V",0x3FC0},
                {"XC2S100","f0614093","0fffffff","alg_VIRTEX",0l},
                {NULL,NULL,NULL,NULL,0l}
               };
*/
#define TOKDELIM " \t/,;.\n"

part *
text_to_part(char *text)
{
 part temp, *ret;
 char *token;

 token=strtok(text,TOKDELIM);
 if (token==NULL) return NULL;
 temp.name=strdup(token);

 token=strtok(NULL,TOKDELIM);
 if (token==NULL) return NULL;
 temp.id=strdup(token);

 token=strtok(NULL,TOKDELIM);
 if (token==NULL) return NULL;
 temp.idmask=strdup(token);

 token=strtok(NULL, TOKDELIM);
 if (token==NULL) return NULL;
 temp.alg_tpl=strdup(token);

 token=strtok(NULL, TOKDELIM);
 if (token==NULL) return NULL;
 temp.bsize=strdup(token);

 token=strtok(NULL,TOKDELIM);
 if (token==NULL) return NULL;
 temp.msize=strtol(token,NULL,0);


 if((ret=(part *)malloc(sizeof(part)))==NULL)
   {
    fprintf(stderr,"Cannot asign memory needed for a part\n");
    return NULL;
   }
 *ret=temp;
 return ret;
}


int
select_part_from_file(char *name, char *file, part **ret)
{
 char buff[1000];
 FILE *fp;

 if((fp=fopen(file,"rt"))==NULL)
   {
    fprintf(stderr,"Unable to open devices file %s.\n",file);
    return 1;
   }

 fgets(buff,1000,fp);

 while(!feof(fp))
   {
    if (strncasecmp(buff,"//",2) && (buff[0]!='\n')) /*If its not a comment*/
        {                                            /* or a blank line ...*/
         *ret=text_to_part(buff);
         if (*ret==NULL)
           fprintf(stderr,"Invalid line inside device file: %s\n",buff);
         else if (!strcasecmp(name,(*ret)->name))
                { /* FOUND! */
                 fclose(fp);
                 return 0;
                }
        }
    fgets(buff,1000,fp);
   }

 *ret=NULL;
 fprintf(stderr,"Device not found inside device file: %s\n",name);
 fclose(fp);
 return 1;
}

/*
int
select_part_by_name(char *name, part **ret)
{
 int found=0;
 part *r;

 r=known;

 while (r->name && !found)
   {
    if (!strcasecmp(r->name,name))
      found=1;
    else
      r++;
   }

 if (!found)
   {
     fprintf(stderr,"Device not found %s\n",name);
     return 1;
   }

 *ret=r;

 return 0;
}

*/
