#include<stdio.h>
#include "config.h"

#define exefolder "program/"
#define paramfile "param/"
#define maxstrlen 2000

#define fileid idfile

int getid(){
    FILE *f;
    int id;
    
    f=fopen("id","r");
    fscanf(f,"%i",&id);
    fclose(f);
    
    id++;
    
    f=fopen("id","w");
    fprintf(f,"%i\n",id);
    fclose(f);  
    
    return id;
}

// copy file src to des
void movefile(char *src,char *des){
    char a[maxstrlen];
    strcpy(a,"cp ");
    strcat(a,des);
    system(a);
}

int main(int argc,char *argv[]){
    if (argc!=3){
        printf("Usage: exptadd [experiment file] [experiment description]\n");
        printf("Please try again\n");
        return;
    }

    FILE *f;
    FILE *f2;
        
    f=fopen(argv[1],"r");
    if (f==NULL){
        printf("File not found\n");
        return;
    }
    
    f2=fopen(dbfile,"a");
    
    char author[maxstrlen];

    if (readDatabase(argv[2])==1){
        printf("The name is duplicate\n");
        return;
    }

    //get a new id
    int id=getid();
    
    //print exp name
    fprintf(f2,"%s\n",argv[2]);
    //print exp id  
    fprintf(f2,"%i\n",id);
    
    char s[maxstr];
    //read line by line and output to the database file
        
    while(fgets(s,maxstr,f)){
        char *st=strtok(s," :");
  
        if (st==NULL) continue;      
        int ok=0;
        if (strcmp(st,"PARAM")==0) ok=1;
        st=strtok(NULL," :");
        
        while(st!=NULL){
            fprintf(f2,"%s ",st);
//            if (ok) movefile(st,paramfile);
            st=strtok(NULL," :");            
        }
    }

    fprintf(f2,"0\n");
    fprintf(f2,"0\n");
         
    close(f);
    close(f2);
    
    printf("Experiment sucessfully added to the system.\n");
    printf("Identification of the experiment: %i\n",id);
}
