/******************************COPYRIGHT NOTICE*******************************/ /* (c) Centro de Regulacio Genomica */ /* and */ /* Cedric Notredame */ /* 12 Aug 2014 - 22:07. */ /*All rights reserved. */ /*This file is part of T-COFFEE. */ /* */ /* T-COFFEE is free software; you can redistribute it and/or modify */ /* it under the terms of the GNU General Public License as published by */ /* the Free Software Foundation; either version 2 of the License, or */ /* (at your option) any later version. */ /* */ /* T-COFFEE is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* GNU General Public License for more details. */ /* */ /* You should have received a copy of the GNU General Public License */ /* along with Foobar; if not, write to the Free Software */ /* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /*............................................... */ /* If you need some more information */ /* cedric.notredame@europe.com */ /*............................................... */ /******************************COPYRIGHT NOTICE*******************************/ // DIR_4_TCOFFEE [def: ~/.t_coffee]: UNIQUE_DIR_4_TCOFFEE -> DIR_4_TCOFFEE ->HOME/.t_coffee //TMP_4_TCOFFEE [def: ~/.t_coffee/tmp]:: UNIQUE_DIR_4_TCOFFEE -> TMP_4_TCOFFEE ->DIR_4_TCOFFEE/tmp #define FILE_CHECK 1 #include #include #include #include #include #include #include #include #include #include #include #include #include // required to find out the numOfCores on MACOSX // see function 'getNumCores' below #ifdef MACOS #include #include #endif #include "io_lib_header.h" #include "util_lib_header.h" #include "define_header.h" #include "perl_header_lib.h" #include "dp_lib_header.h" //defined this way because all compilers cannot pas ap //safe printf: it declares buf to the proper size #define cvsprintf(buf,string)\ if(1)\ { \ va_list ap; \ int n; \ char buf2[2]; \ va_start (ap,string); \ n=vsnprintf (buf2,1, string, ap)+3; \ va_end (ap); \ va_start (ap, string); \ buf=(char*)vcalloc (n, sizeof (char)); \ vsnprintf (buf, n,string, ap); \ va_end(ap);} int my_vsscanf(char *buf, char *fmt, va_list parms); static int get_vtmpnam2_root(); /** * \file util.c * Collection of basic C functions. */ static int global_exit_signal; static int no_error_report; static int clean_exit_started; static int debug_lock; static char *in_cl; static char *logfile; /*********************************************************************/ /* */ /* SANDBOX /* */ /* */ /*********************************************************************/ void sb() { double *in; double *out; int a; float tot=0; in=(double *)vcalloc (26, sizeof (double)); in[dirichlet_code('y')]=0.5; in[dirichlet_code('k')]=0.5; out=compute_dirichlet_p (in); for ( a=0; a<26; a++) { if (is_aa(a+'a')) { int i=dirichlet_code (a+'a'); HERE ("%c %.2f", a+'a', (float)exp((float)out[i])); tot+=(float)exp((float)out[i]); } } HERE ("TOT=%.2f", tot); exit(0); } /*********************************************************************/ /* */ /* DICHOTOMY */ /* */ /* */ /*********************************************************************/ double dichotomy (double value, double target_value, double middle, double *bottom,double *top) { if ( value> target_value)top[0]=middle; else if ( value= 0; sp--) { char *lb, *ub, *m; char *P, *i, *j; lb = lbStack[sp]; ub = ubStack[sp]; while (lb < ub) { /* select pivot and exchange with 1st element */ offset = (ub - lb) >> 1; P = lb + offset - offset % size; exchange (lb, P, size); /* partition into two segments */ i = lb + size; j = ub; while (1) { while (i < j && compar(lb, i) > 0) i += size; while (j >= i && compar(j, lb) > 0) j -= size; if (i >= j) break; exchange (i, j, size); j -= size; i += size; } /* pivot belongs in A[j] */ exchange (lb, j, size); m = j; /* keep processing smallest segment, and stack largest */ if (m - lb <= ub - m) { if (m + size < ub) { lbStack[sp] = m + size; ubStack[sp++] = ub; } ub = m - size; } else { if (m - size > lb) { lbStack[sp] = lb; ubStack[sp++] = m - size; } lb = m + size; } } } } #endif int pstrcmp(char *p1, char *p2); /*********************************************************************/ /* */ /* HEAPSORT */ /* */ /* */ /*********************************************************************/ FILE * hsort_file ( FILE *fp,int n,int len, size_t size,int first_comp_field, int n_comp_fields,int (*compare)(const void *, const void*,int, int, size_t),void * (*copy)(void *,void*, size_t)) { unsigned long i, ir, j, l; void *rra, *rrb, *ra_j, *ra_j_1; void *tp; long start; int FE=1; start=ftell(fp); rra =vcalloc ( len, size); rrb =vcalloc ( len, size); ra_j =vcalloc ( len, size); ra_j_1=vcalloc ( len, size); if ( n<2)return fp; l=(n >>1)+1; ir=n; for (;;) { if ( l>FE) { l--; fseek( fp, start+(((l-1)*len)*size), SEEK_SET); fread( rra, size, len,fp); /*rra=ra[--l]*/ } else { fseek( fp, start+((ir-1)*len*size), SEEK_SET); fread( rra, size, len,fp); /*rra=ra[ir]*/ fseek( fp, start, SEEK_SET); fread( rrb, size, len,fp); /*rrb=ra[0]*/ fseek( fp, start+((ir-1)*len*size), SEEK_SET); fwrite(rrb,size, len, fp); /*ra[ir]=rrb=ra[0]*/ if (--ir ==FE) { fseek ( fp,start, SEEK_SET); fwrite(rra,size, len, fp); /*ra[0]=rra*/ break; } } i=l; j=l+l; while ( j<=ir) { fseek ( fp, start+((j-1)*len*size), SEEK_SET); fread (ra_j, size, len, fp); if ( j>1)+1; ir=n; for (;;) { if ( l>FE) { copy ( rra, ra[--l],len); } else { copy ( rra, ra[ir],len); copy ( ra[ir], ra[FE], len); if (--ir ==FE) { copy ( ra[FE],rra,len); break; } } i=l; j=l+l; while ( j<=ir) { if ( j1) { i=(lower+upper) >> 1; fseek ( fp,start+(i*el_size*entry_len), SEEK_SET); fread ( key2, el_size, entry_len,fp); c=compare(key2,key, comp_first, comp_len,el_size); if ( c==0){p[0]=i;return key2;} else if ( c< 0)upper=i; else if ( c> 0)lower=i; } return NULL; } void * bsearch_array ( const void *key,int *p,int comp_first, int comp_len,void**list,int len, int entry_len,size_t el_size, int (*compare)(const void *, const void*,int, int, size_t)) { int upper, lower, c, i; void *key2; upper=-1; lower=len; while ((lower-upper)>1) { i=(lower+upper) >>1; key2=list[i]; c=compare(key2,key, comp_first,comp_len,el_size); if ( c==0){p[0]=i;return key2;} else if ( c< 0)upper=i; else if ( c> 0)lower=i; } return NULL; } /**********************************************************************/ /* */ /* HSORT/BSEARCH WRAPPERS */ /* */ /* */ /**********************************************************************/ void **search_in_list_file ( void *key, int *p,int comp_len,FILE *fp, int len, size_t size, int entry_len) { static void **l; if ( l==NULL)l=(void**)vcalloc ( 1, sizeof (int*)); l[0]=bsearch_file (key,p,0,comp_len,fp,len,entry_len,size,hsort_cmp); if (l[0]==NULL)return NULL; else return l; } void **search_in_list_array ( void *key,int *p, int comp_len,void **L, int len, size_t size, int entry_len) { static void **l; if ( l==NULL)l=(void**)vcalloc ( 1, sizeof (int*)); l[0]=bsearch_array (key,p,0,comp_len,L,len,entry_len,size,hsort_cmp); if (l[0]==NULL)return NULL; else return l; } void **hsort_list_array ( void **L, int len, size_t size, int entry_len, int first_comp_field, int n_comp_fields) { return hsort_array (L, len,entry_len, size,first_comp_field, n_comp_fields,hsort_cmp , hsort_cpy); } FILE *hsort_list_file ( FILE*fp , int len, size_t size, int entry_len, int first_comp_field, int n_comp_fields) { return hsort_file (fp, len,entry_len, size,first_comp_field, n_comp_fields,hsort_cmp , hsort_cpy); } int hsort_cmp ( const void *a, const void *b, int first, int clen, size_t size) { int*ax; int*bx; int p; ax=(int*)a; bx=(int*)b; for ( p=first; pbest){R=V[a];best=V[a][F];} } return R; } int *flash_sort_int ( int **V,int N_F, int F, int left, int right) { int *R=NULL; int best; int a; for (a=0; a<=right; a++) { if (a==0 ||V[a][F]b[0][c])return 1; else if ( a[0][c]b[0][c])return 1; else if ( a[0][c]=0; --a) { if ( name_list[a]==NULL) {} else if ( len!=-1) { if (strncmp ( name, name_list[a], len)==0) return a; } else if ( strm ( name, name_list[a])) return a; } return pos; } char * check_list_for_dup ( char **list, int ne) { int a, b; for ( a=0; a< ne-1; a++) for ( b=a+1; b< ne; b++)if (strm ( list[a], list[b]))return list[a]; return NULL; } FILE *get_number_list_in_file ( FILE *fp, int *list, int *n, int *max_len) { int c; while ( isspace((c=fgetc (fp)))); ungetc(c, fp); while ( c!='\n') { while ( isspace((c=fgetc (fp))) && c!='\n'); if ( c!='\n') { ungetc(c, fp); if ( n[0]>=max_len[0]) list=(int*)vrealloc ( list, (n[0]+100)*sizeof (int)); max_len[0]=(n[0]+100); fscanf ( fp, "%d",&list[n[0]++]); } } return fp; } /*********************************************************************/ /* */ /* QUANTILE */ /* */ /* */ /*********************************************************************/ int quantile (int argc, char *argv[]) { FILE *fp; int a,n,c, t; int **list; char *** string_list; char *name, s1[1000], s2[1000]; if ( argc<2) { fprintf (stderr, "\nquantile []"); fprintf (stderr, "\nSplits your data in two according to the quantile"); fprintf (stderr, "\nReturns the top quantile or the bottom quantile"); fprintf (stderr, "\nData must be in with two fields/line: Field1=index, Field2=value\n"); fprintf (stderr, "\n1 27\n2 46\n3 5\n...\n"); fprintf (stderr, "\nValue can either be integer or float"); myexit (EXIT_FAILURE); } if (strm (argv[1], "stdin")) { name=vtmpnam(NULL); fp=vfopen (name, "w"); while ( (c=fgetc(stdin))!=EOF) { fprintf ( fp, "%c", c); } vfclose (fp); } else name=argv[1]; n=count_n_line_in_file (name); list=declare_int (n, 2); string_list=(char***)declare_arrayN(3,sizeof (char), n, 2, 10); fp=vfopen (name, "r"); n=0; while ( (c=fgetc (fp))!=EOF) { ungetc(c,fp); fscanf ( fp, "%s %s\n", s1, s2); list[n][0]=(int)(atof(s1)*1000); list[n][1]=(int)(atof(s2)*1000); list[n][2]=n; sprintf (string_list[n][0],"%s",s1); sprintf (string_list[n][1],"%s",s2); n++; } sort_int_inv ( list,3, 1, 0, n-1); t=quantile_rank ( list,1,n, atof (argv[2])); if ( argc!=4 || (argc==4 && strm (argv[3], "bottom"))) { for (a=t; a=q)nr++; vfree(l); } return nr; } /*********************************************************************/ /* */ /* DUPLICATION */ /* */ /* */ /*********************************************************************/ short* ga_memcpy_short ( short *array1, short *array2, int n) { int a; for ( a=0; a< n; a++) array2[a]=array1[a]; return array2; } int * ga_memcpy_int ( int *array1, int *array2, int n) { int a; for ( a=0; a< n; a++) array2[a]=array1[a]; return array2; } float* ga_memcpy_float ( float *array1, float *array2, int n) { int a; for ( a=0; a< n; a++) array2[a]=array1[a]; return array2; } double* ga_memcpy_double (double *array1, double*array2, int n) { int a; for ( a=0; a< n; a++) array2[a]=array1[a]; return array2; } /*recycle: get the bottom pointer on the top of the heap*/ void ** recycle (void **A, int l, int cycle) { void **B; int a,b,c; B=(void**)vcalloc (l, sizeof (void*)); for ( c=0; c< cycle; c++) { for ( a=1, b=0; anseq; rec_list=realloc_aln_array ( rec_list, end-first); for ( a=first, b=rec_list_start; a, UNDEFINED_SHORT) RETURN_MAX_COOR(char,write_size_char,read_size_char,return_max_coor_char,>, UNDEFINED_CHAR) RETURN_MAX_COOR(int,write_size_int,read_size_int,return_max_coor_int,>, UNDEFINED_INT) RETURN_MAX_COOR(float,write_size_float,read_size_float,return_max_coor_float,>, UNDEFINED_FLOAT) RETURN_MAX_COOR(double,write_size_double,read_size_double,return_max_coor_double,>, UNDEFINED_DOUBLE) RETURN_MAX_COOR(short,write_size_short,read_size_short,return_min_coor_short,<, UNDEFINED_SHORT) RETURN_MAX_COOR(char,write_size_char,read_size_char,return_min_coor_char,<, UNDEFINED_CHAR) RETURN_MAX_COOR(int,write_size_int,read_size_int,return_min_coor_int,<, UNDEFINED_INT) RETURN_MAX_COOR(float,write_size_float,read_size_float,return_min_coor_float,<, UNDEFINED_FLOAT) RETURN_MAX_COOR(double,write_size_double,read_size_double,return_min_coor_double,<, UNDEFINED_DOUBLE) #define RETURN_MAX(type,wf,rf,function,comparison,undef)\ type function ( type ** array, int len_array, int field)\ {\ type max;\ int a;\ \ if (array==NULL || len_array==0)return 0;\ else\ {\ if (len_array==-1)len_array=rf(array,sizeof (type*));\ max=array[0][field];\ for ( a=1; a< len_array; a++)\ if ( max==undef)max=array[a][field];\ else if ( array[a][field]!=undef)max=( array[a][field] comparison max)?array[a][field]:max;\ }\ return (max==undef)?0:max;\ } RETURN_MAX(short,write_size_short,read_size_short,return_max_short,>,UNDEFINED_SHORT) RETURN_MAX(char,write_size_char,read_size_char,return_max_char,>,UNDEFINED_CHAR) RETURN_MAX(int,write_size_int,read_size_int,return_max_int,>,UNDEFINED_INT) RETURN_MAX(float,write_size_float,read_size_float,return_max_float,>,UNDEFINED_FLOAT) RETURN_MAX(double,write_size_double,read_size_double,return_max_double,>,UNDEFINED_DOUBLE) RETURN_MAX(short,write_size_short,read_size_short,return_min_short,<,UNDEFINED_SHORT) RETURN_MAX(char,write_size_char,read_size_char,return_min_char,<,UNDEFINED_CHAR) RETURN_MAX(int,write_size_int,read_size_int,return_min_int,<,UNDEFINED_INT) RETURN_MAX(float,write_size_float,read_size_float,return_min_float,<,UNDEFINED_FLOAT) RETURN_MAX(double,write_size_double,read_size_double,return_min_double,<,UNDEFINED_DOUBLE) #define RETURN_2DMAX(type,wf,rf,function,comparison,undef)\ type function ( type ** array, int start, int len_array, int first_field, int number_field)\ {\ type max;\ int a,b;\ if (array==NULL || len_array==0 || first_field<0 || number_field==0)return 0;\ else\ {max=array[start][first_field];\ for ( a=start; a< start+len_array; a++)\ for (b=first_field; b< first_field+number_field; b++)\ if (array[a][b]!=undef)max=( array[a][b] comparison max)?array[a][b]:max;\ }\ return max;\ } RETURN_2DMAX(short,write_size_short,read_size_short,return_2Dmax_short,>, UNDEFINED_SHORT) RETURN_2DMAX(char,write_size_char,read_size_char,return_2Dmax_char,>,UNDEFINED_CHAR) RETURN_2DMAX(int,write_size_int,read_size_int,return_2Dmax_int,>,UNDEFINED_INT) RETURN_2DMAX(float,write_size_float,read_size_float,return_2Dmax_float,>,UNDEFINED_FLOAT) RETURN_2DMAX(double,write_size_double,read_size_double,return_2Dmax_double,>,UNDEFINED_DOUBLE) RETURN_2DMAX(short,write_size_short,read_size_short,return_2Dmin_short,<,UNDEFINED_SHORT) RETURN_2DMAX(char,write_size_char,read_size_char,return_2Dmin_char,<,UNDEFINED_CHAR) RETURN_2DMAX(int,write_size_int,read_size_int,return_2Dmin_int,<,UNDEFINED_INT) RETURN_2DMAX(float,write_size_float,read_size_float,return_2Dmin_float,<,UNDEFINED_FLOAT) RETURN_2DMAX(double,write_size_double,read_size_double,return_2Dmin_double,<,UNDEFINED_DOUBLE) #define RETURN_2DMAX_COOR(type,wf,rf,function,compare,undef)\ type function ( type **array, int start1 , int end1, int start2, int end2,int *i, int *j)\ {\ int a, b;\ double max=undef;\ if ( start1==-1)start1=0;\ if ( start2==-1)start2=0;\ if ( end1==-1)end1=rf(array,sizeof (type*));\ if ( end2==-1)end2=rf(array[0],sizeof (type));\ if ( array==NULL || (end1-start1)==0 || (end1-start1)>rf ( array,sizeof (type*)) || (end2-start2)==0)\ {\ return 0;\ i[0]=0;\ j[0]=0;\ }\ i[0]=0;\ j[0]=0;\ for ( a=start1; a,UNDEFINED_SHORT) RETURN_2DMAX_COOR(char,write_size_char,read_size_char,return_2Dmax_coor_char,>,UNDEFINED_CHAR) RETURN_2DMAX_COOR(int,write_size_int,read_size_int,return_2Dmax_coor_int,>,UNDEFINED_INT) RETURN_2DMAX_COOR(float,write_size_float,read_size_float,return_2Dmax_coor_float,>,UNDEFINED_FLOAT) RETURN_2DMAX_COOR(double,write_size_double,read_size_double,return_2Dmax_coor_double,>,UNDEFINED_DOUBLE) RETURN_2DMAX_COOR(short,write_size_short,read_size_short,return_2Dmin_coor_short,<,UNDEFINED_SHORT) RETURN_2DMAX_COOR(char,write_size_char,read_size_char,return_2Dmin_coor_char,<,UNDEFINED_CHAR) RETURN_2DMAX_COOR(int,write_size_int,read_size_int,return_2Dmin_coor_int,<,UNDEFINED_INT) RETURN_2DMAX_COOR(float,write_size_float,read_size_float,return_2Dmin_coor_float,<,UNDEFINED_FLOAT) RETURN_2DMAX_COOR(double,write_size_double,read_size_double,return_2Dmin_coor_double,<,UNDEFINED_DOUBLE) #define RETURN_WMEAN(type,wf,rf,function,sum_function,undef)\ double function ( type **array, int len, int wfield,int sfield)\ {\ double b;\ int a, c;\ if ( len==0 ||array==NULL || len>rf ( array,sizeof (type*)))return 0;\ else\ {\ if ( len==-1)len=rf(array,sizeof (type*));\ for ( b=0, c=0,a=0; a< len; a++)\ {\ if (array[a][sfield]!=undef && array[a][wfield]!=undef )\ {\ b+=array[a][sfield];\ c+=array[a][wfield];\ }\ }\ }\ return (c==0)?0:(b/c);\ } RETURN_WMEAN(short,write_size_short,read_size_short,return_wmean_short, return_sum_short,UNDEFINED_SHORT) RETURN_WMEAN(char,write_size_char,read_size_char, return_wmean_char,return_sum_char,UNDEFINED_CHAR) RETURN_WMEAN(int,write_size_int,read_size_int,return_wmean_int,return_sum_int,UNDEFINED_INT) RETURN_WMEAN(float,write_size_float,read_size_float,return_wmean_float,return_sum_float,UNDEFINED_FLOAT) RETURN_WMEAN(double,write_size_double,read_size_double,return_wmean_double,return_sum_double,UNDEFINED_DOUBLE) #define RETURN_MEAN(type,wf,rf,function,sum_function,undef)\ double function ( type **array, int len, int field)\ {\ double b;\ int a, c;\ if ( len==0 ||array==NULL || len>rf ( array,sizeof(type*)))return 0;\ else\ {\ for ( b=0, c=0,a=0; a< len; a++)\ {\ if (array[a][field]!=undef)\ {\ b+=array[a][field];\ c++;\ }\ }\ }\ return (c==0)?0:(b/c);\ } RETURN_MEAN(short,write_size_short,read_size_short,return_mean_short, return_sum_short,UNDEFINED_SHORT) RETURN_MEAN(char,write_size_char,read_size_char, return_mean_char,return_sum_char,UNDEFINED_CHAR) RETURN_MEAN(int,write_size_int,read_size_int,return_mean_int,return_sum_int,UNDEFINED_INT) RETURN_MEAN(float,write_size_float,read_size_float,return_mean_float,return_sum_float,UNDEFINED_FLOAT) RETURN_MEAN(double,write_size_double,read_size_double,return_mean_double,return_sum_double,UNDEFINED_DOUBLE) #define RETURN_SUM(type,wf,rf,function,undef)\ type function(type **array, int len, int field)\ {\ int a;\ type b=0;\ if ( len==0 ||array==NULL)return 0;\ else\ {\ if ( len==-1)len=rf ( array,sizeof (type*));\ for ( a=0; a< len; a++)\ if ( array[a][field]!=undef)b+=array[a][field];\ }\ return b;\ } RETURN_SUM(short,write_size_short,read_size_short, return_sum_short,UNDEFINED_SHORT) RETURN_SUM(char,write_size_char,read_size_char,return_sum_char,UNDEFINED_CHAR) RETURN_SUM(int,write_size_int,read_size_int,return_sum_int,UNDEFINED_INT) RETURN_SUM(float,write_size_float,read_size_float,return_sum_float,UNDEFINED_FLOAT) RETURN_SUM(double,write_size_double,read_size_double,return_sum_double,UNDEFINED_DOUBLE) #define RETURN_SD(type,wf,rf,function,undef)\ type function ( type **array, int len, int field,type mean) \ {\ int a;\ double c=0;\ if ( len==0 ||array==NULL || len>rf ( array,sizeof(type*)))return 0;\ else\ {\ for ( a=0; a< len; a++)\ {\ if ((array[a][field]!=undef) && (mean-array[a][field])!=0)\ c+=((double)mean-array[a][field])*((double)mean-array[a][field]);\ }\ c=sqrt(c)/(double)len;\ return (type)MAX(c,1);\ }\ } RETURN_SD(short,write_size_short,read_size_short, return_sd_short,UNDEFINED_SHORT) RETURN_SD(char,write_size_char,read_size_char,return_sd_char,UNDEFINED_CHAR) RETURN_SD(int,write_size_int,read_size_int,return_sd_int,UNDEFINED_INT) RETURN_SD(float,write_size_float,read_size_float,return_sd_float,UNDEFINED_FLOAT) RETURN_SD(double,write_size_double,read_size_double,return_sd_double,UNDEFINED_DOUBLE) double return_z_score( double x,double sum, double sum2, double n) { double sd; double avg; double z; sd=(n==0)?0:sqrt(sum2*n -sum*sum)/n; avg=(n==0)?0:(sum/n); z=(sd==0)?0:(x-avg)/sd; return z; } double* return_r (double **list, int n) { double Sy, Sx, Sxy, Sx2, Sy2,r_up, r_low, x, y; double *r; int a; r=(double*)vcalloc ( 3, sizeof (double)); Sy=Sx=Sxy=Sx2=Sy2=0; for ( a=0; a,UNDEFINED_SHORT) RETURN_MAX_HORIZ(char,write_size_char,read_size_char,return_max_char_hor,>,UNDEFINED_CHAR) RETURN_MAX_HORIZ(int,write_size_int,read_size_int,return_max_int_hor,>,UNDEFINED_INT) RETURN_MAX_HORIZ(float,write_size_float,read_size_float,return_max_float_hor,>,UNDEFINED_FLOAT) RETURN_MAX_HORIZ(double,write_size_double,read_size_double,return_max_double_hor,>,UNDEFINED_DOUBLE) RETURN_MAX_HORIZ(short,write_size_short,read_size_short,return_min_short_hor,<,UNDEFINED_SHORT) RETURN_MAX_HORIZ(char,write_size_char,read_size_char,return_min_char_hor,<,UNDEFINED_CHAR) RETURN_MAX_HORIZ(int,write_size_int,read_size_int,return_min_int_hor,<,UNDEFINED_INT) RETURN_MAX_HORIZ(float,write_size_float,read_size_float,return_min_float_hor,<,UNDEFINED_FLOAT) RETURN_MAX_HORIZ(double,write_size_double,read_size_double,return_min_double_hor,<,UNDEFINED_DOUBLE) #define BEST_OF_MANY(type,wf,rf,function,undef)\ type function (int n, ...)\ {\ va_list ap;\ int *fop,a;\ type v, best;\ int maximise;\ /*first Arg: number of values\ 2nd Arg: maximise(1)/minimise(0)\ 3rd Arg: *int contains the indice of the best value\ ... Arg: n type values\ */\ va_start (ap, n);\ maximise=va_arg (ap, int);\ fop=va_arg (ap, int*);\ best=va_arg (ap, type);\ fop[0]=0;\ for ( a=1; abest)\ {\ fop[0]=a;\ best=v;\ }\ else if ( maximise==0 && vmax)?strlen ( array[a]):max; return max; } int return_minlen ( char ** array, int number) { int a; int min; min=strlen( array[0]); for ( a=1; a< number; a++) min=( strlen ( array[a])>min)?strlen ( array[a]):min; return min; } float return_mean_diff_float ( float **array, int len, int field,float mean) { int a; float b=0; for ( a=0; a< len; a++) { if ( (mean-array[a][field])!=0) b+=sqrt((double)((float) ( mean-array[a][field])*(float)(mean-array[a][field]))); } return ((float)b/(float)len); } void inverse_int ( int**array, int len, int field, int max, int min) { int a; for ( a=0; a< len; a++) array[a][field]=max-array[a][field]+min; } void inverse_float ( float**array, int len, int field, int max, int min) { int a; for ( a=0; a< len; a++) array[a][field]=max-array[a][field]+min; } void inverse_2D_float ( float **array, int start, int len, int start_field, int number_field, float max,float min) { int a, b; for ( a=0; a< start+len; a++) for ( b=start_field; b< start_field+ number_field; b++) array[a][b]=max-array[a][b]+min; } int max_int (int*i, ...) { va_list ap; \ int index, best_value=0, value; int a=0; // expects n values : n, &index, i1, v1, i2, v2...., -1 va_start(ap, i); while ((index=va_arg(ap,int))!=-1) { value=va_arg(ap, int); if ( a==0 || value>best_value) { i[0]=index; best_value=value; a=1; } } va_end (ap); return best_value; } /*********************************************************************/ /* */ /* SHELL INTERFACES */ /* */ /* */ /*********************************************************************/ char* getenv4debug (const char * val) { /*efficient mean of getting an environment variable: checks only if one DEBUG is on*/ static int check; if ( !check) { if (getenv ("DEBUG_BLAST"))check=1; else if ( getenv ("DEBUG_TREE_COMPARE"))check=1; else if ( getenv ("DEBUG_MALN"))check=1; else if ( getenv ("DEBUG_EXTRACT_FROM_PDB"))check=1; else if ( getenv ("DEBUG_LIBRARY"))check=1; else if ( getenv ("DEBUG_FUGUE"))check=1; else if ( getenv ("DEBUG_REFORMAT"))check=1; else if ( getenv ("DEBUG_RECONCILIATION"))check=1; else if ( getenv ("DEBUG_TMP_FILE"))check=1; else if ( getenv ("DEBUG_TREE"))check=1; else if ( getenv ("DEBUG_SEQ_REFORMAT") && strm (PROGRAM, "SEQ_REFORMAT"))check=2; else if ( getenv ("DEBUG_TCOFFEE") && strm (PROGRAM, "T-COFFEE"))check=2; else check=-1; } if ( check>0 && strm ( val, "DEBUG_TMP_FILE")) { return "1"; } else if ( check==1) { return getenv (val); } else if ( check==2) { return "1"; } else return NULL; } float atofgetenv (const char*var) { char *v; if (!var) return 0; else if (!(v=getenv(var)))return 0; else if ( is_number(v))return atof(v); else return 1; } int atoigetenv (const char*var) { char *v; if (!var) return 0; else if (!(v=getenv(var)))return 0; else if ( is_number(v))return atoi(v); else return 0; } char* get_env_variable ( const char *var, int mode) { /*mode 0: return NULL if variable not set*/ /*mode 1: crash if variable not set*/ if ( !getenv (var)) { if (mode==NO_REPORT)return NULL; else if ( mode ==IS_NOT_FATAL) { myexit(fprintf_error ( stderr, "\nYou must set the variable %s [FATAL]\n", var)); return NULL; } else { myexit(fprintf_error ( stderr, "\nYou must set the variable %s [FATAL]\n", var)); myexit (EXIT_FAILURE); return NULL; } } else return getenv (var); } char *get_pwd ( char *name) { char cwd[1024]; if (!name)name=(char*)vcalloc (1025, sizeof (int)); if (getcwd(cwd, sizeof(cwd)) != NULL) sprintf(name, "%s", cwd); else perror("getcwd() error"); } int pg_is_installed ( char *pg) { char *fname; FILE *fp; int r=0; return 1; fname= vtmpnam(NULL); printf_system_direct("which %s > %s", pg, fname); if ((fp=find_token_in_file ( fname, NULL, "Command"))){r=1;vfclose(fp);} return r; } /*********************************************************************/ /* */ /* MISC */ /* */ /*********************************************************************/ char *num2plot (int value, int max, int line_len) { int len; int value_len; char *buf; static char *string; if ( string==NULL)string=(char*)vcalloc (1000, sizeof(char)); if ( line_len==-1)len=30; else len=line_len; value_len=((float)value/(float)max)*(float)len; if ( value==0) sprintf ( string, "|"); else { buf=generate_string(value_len, '*'); sprintf ( string,"%s", buf); vfree(buf); } return string; } int perl_strstr ( char *string, char *pattern) { char *tmp; FILE *fp; int r; char *string2; if (!string) return 0; if (!pattern) return 0; string2=(char*)vcalloc ( strlen (string)+1, sizeof (char)); sprintf ( string2,"%s", string); string2=substitute (string2, "(", " "); string2=substitute (string2, ")", " "); string2=substitute (string2, "'", " "); tmp=vtmpnam(NULL); printf_system_direct("perl -e '$s=\"%s\";$x=($s=~/%s/);$x=($x==1)?1:0;print $x;'>%s", string2, pattern,tmp); if (check_file_exists(tmp)) { fp=vfopen (tmp, "r"); fscanf (fp, "%d", &r); vfclose (fp); } else { fprintf ( stderr, "COM: %s\n", string); r=0; } vfree (string2); return r; } void crash_if ( int val, char *s) { if ( val==0)crash(s); } void crash ( char *s) { int *a; fprintf ( stderr, "%s",s); a=(int*)vcalloc ( 10, sizeof (int)); a[20]=1; error_exit(EXIT_FAILURE); } static int *local_table; int ** make_recursive_combination_table ( int tot_n_param, int *n_param, int *nc, int**table, int field) { int a, b, c; /* makes a table of all possible combinations*/ if ( tot_n_param==0) { nc[0]=1; fprintf ( stderr, "\nNULL RETURNED"); return NULL; } if (table==NULL) { if ( local_table!=NULL)vfree (local_table); local_table=(int*)vcalloc ( tot_n_param, sizeof (int)); field=0; for ( a=0; a< tot_n_param; a++)local_table[a]=-1; for ( a=0; a< tot_n_param; a++)nc[0]=nc[0]*n_param[a]; table=declare_int ( nc[0],tot_n_param); nc[0]=0; } for ( b=0; bsuffix)sprintf ( name, "%s.%s", F->name, F->suffix); else sprintf (name, "%s", F->name); free_fname (F); return name; } Fname* parse_fname ( char *array) { int l; Fname *F; F=declare_fname( sizeof(array) ); sprintf ( F->full, "%s", array); sprintf ( F->path, "%s", array); l=strlen (array); while (l!=-1 && (F->path)[l]!='/')(F->path)[l--]='\0'; sprintf ( F->name, "%s", array+l+1); l=strlen (F->name); while (l!=-1) { if((F->name)[l]=='.') { F->name[l]='\0'; sprintf ( F->suffix, "%s", F->name+l+1); break; } else l--; } return F; } char *filename2path (char *name) { char *nname; int x; if (isdir (name))return name; x=strlen (name)-1; nname=(char*)vcalloc (x+2, sizeof (char)); sprintf ( nname, "%s", name); while ( x >=0 && nname[x]!='/')nname[x--]='\0'; if ( !isdir (nname) || !nname[0]){vfree (nname); return NULL;} return nname; } char *extract_suffixe ( char *array) { int l; char *new_string; char *x; l=strlen (array); new_string=(char*)vcalloc ( l+1, sizeof (char)); sprintf (new_string, "%s",array); x=new_string+l; while (x!=new_string && x[0]!='.' && x[0]!='/' )x--; if ( x[0]=='.')x[0]='\0'; else if (x[0]=='/')return x+1; while ( x!=new_string && x[0]!='/')x--; return (x[0]=='/')?x+1:x; } void string_array_upper ( char **string, int n) { int a; for ( a=0; a< n; a++)upper_string (string[a]); } void string_array_lower ( char **string, int n) { int a; for ( a=0; a< n; a++)lower_string (string[a]); } char *upper_string ( char *string) { int len, a; len=strlen ( string); for ( a=0; a< len; a++)string[a]=toupper ( string[a]); return string; } char *lower_string ( char *string) { int len, a; len=strlen ( string); for ( a=0; a< len; a++)string[a]=tolower ( string[a]); return string; } void string_array_convert ( char **array, int n_strings, int ns, char **sl) { int a; for ( a=0; a< n_strings; a++)string_convert ( array[a], ns, sl); } void string_convert( char *string, int ns, char **sl) { int a, l; l=strlen ( string); for ( a=0; a< l; a++) string[a]=convert(string[a], ns, sl); } int convert ( char c, int ns, char **sl) { int a; int return_char; for ( a=0; a< ns; a++) { if ((return_char=convert2 ( c, sl[a]))!=-1) return return_char; } return c; } int convert2 ( char c, char *list) { int a; int l1; int return_char; l1=strlen ( list); return_char=(list[l1-1]=='#')?c:list[l1-1]; for ( a=0; a< l1; a++) if (list[a]=='#')return return_char; else if ( list[a]==c)return return_char; return -1; } char* substitute_old ( char *string_in, char *t, char *r) { char *string_out; char *p, *heap_in; int delta, l; /*REplaces every occurence of token t with token r in string_in*/ if ( string_in==NULL || t==NULL || r==NULL) return string_in; heap_in=string_in; l=read_array_size_new ((void*)string_in)+1; string_out=(char*)vcalloc (l, sizeof (char)); delta=strlen(r)-strlen (t); delta=(delta<0)?0:delta; while ( (p=strstr ( string_in, t))!=NULL) { p[0]='\0'; if ( delta) { l+=delta; string_out=(char*)vrealloc(string_out, sizeof (char)*l); } strcat ( string_out, string_in); strcat ( string_out, r); string_in=p+strlen (t); } strcat ( string_out, string_in); if (l0)?(lr-lt):0; nt=0; while ( (p=strstr (string_in, t))!=NULL) { string_in=p+lt; nt++; } string_in=heap_in; lso=nt*delta+lsi; string_out=(char*)vcalloc (lso+1, sizeof (char)); while ((N==0 ||n end1)string1[a]=x; for ( a=0; a< l2; a++)if ( a end2)string2[a]=x; free_int ( array, l1); return max_val; } } int get_string_line ( int start, int n_lines, char *in, char *out) { int nl=0; int a=0; int c=0; while ( nlA\nthecat\n>B\nthecat\n"); vfclose (fp); result=safe_system (command); printf_system ( "rm %s.*", name); vfree (name); if (result) {myexit (EXIT_FAILURE);return 0;} else return 1; } } char** merge_list ( char **argv, int *argc) { int a, b; int n_in; char **out; char current [STRING]; out=declare_char (argc[0], STRING); n_in=argc[0]; argc[0]=0; a=0; while (a< n_in && !is_parameter ( argv[a])) { sprintf (out[argc[0]++], "%s", argv[a]); argv[a][0]='\0'; a++; } for ( a=0; a< n_in; a++) { if ( is_parameter (argv[a])) { sprintf ( out[argc[0]++], "%s", argv[a]); sprintf ( current, "%s", argv[a]); for ( b=0; b< n_in;) { if ( is_parameter (argv[b]) && strm (current, argv[b])) { argv[b][0]='\0'; b++; while ( b=MAX_N_PARAM) { myexit(fprintf_error ( stderr, "\nERROR: too many parameters, recompile with MAX_N_PARAM set at a higher velue [FATAL:%s]\n", PROGRAM));\ myexit (EXIT_FAILURE); } for ( a=0; a< n_in; a++) { if (cont)ar=get_list_of_tokens( argv[a], separators,&n_ar); else ar=get_list_of_tokens( argv[a],"",&n_ar); for ( b=0; b< n_ar; b++) { out[argc[0]]=(char*)vcalloc( strlen (ar[b])+1, sizeof (char)); sprintf (out[argc[0]++], "%s", ar[b]); } free_char (ar, -1); ar=NULL; if ( strstr (argv[a], "-other_pg"))cont=0; } free_char (ar, -1); return out; } char *invert_string2 (char *string) { char *buf; int a, b, l; l=strlen (string); buf=(char*)vcalloc ( l+1, sizeof (char)); for ( a=l-1, b=0; a>=0; a--, b++) buf[b]=string[a]; sprintf (string, "%s", buf); vfree (buf); return string; } char *invert_string (char *string) { return string2inverted_string(string); } char* string2inverted_string(char *string) { char *buf; int a, b, l; l=strlen (string); buf=(char*)vcalloc ( l+1, sizeof (char)); for ( a=l-1, b=0; a>=0; a--, b++) buf[b]=string[a]; return buf; } char ** get_list_of_tokens ( char *in_string, char *separators, int *n_tokens) { char **list=NULL; char *p=NULL; char *string; n_tokens[0]=0; if ( in_string==NULL || strm(in_string, "")); else if ( in_string[0]=='[') { list=declare_char (1, strlen ( in_string)+1); sprintf ( list[n_tokens[0]], "%s",in_string); n_tokens[0]++; } else { list=declare_char (strlen ( in_string)+1, 1); string=(char*)vcalloc ( strlen(in_string)+1, sizeof (char)); sprintf ( string, "%s", in_string); while ( (p=strtok ((p==NULL)?string:NULL, ((separators==NULL)?SEPARATORS:separators)))!=NULL) { list[n_tokens[0]]=(char*)vrealloc ( list[n_tokens[0]], sizeof (char) *strlen (p)+1); sprintf ( list[n_tokens[0]], "%s", p); n_tokens[0]++; } vfree (string); } return list; } char **ungap_array ( char **array, int n) { int a; for ( a=0; a< n; a++)ungap(array[a]); return array; } void ungap ( char *seq) { remove_charset ( seq, "ungap"); } int seq2len (char *seq, char *pset,char *nset) { int a, l, t=0; //count all the residues in pset and NOT in nset if ( !seq) return 0; l=strlen (seq); //returns the len of the string for (a=0; a< l; a++) { char c=seq[a]; if ( pset && nset && strchr (pset, c) && !strchr (nset, c))t++; else if ( pset && strchr (pset, c))t++; else if ( nset && !strchr (nset, c))t++; } return t; } int seq2res_len (char *seq) { return seq2len (seq, NULL, GAP_LIST); } char* remove_charset_from_file (char *fname, char *set) { char *tmp; char c; FILE *fp1; FILE *fp2; fp1=vfopen (fname, "r"); fp2=vfopen (tmp=vtmpnam (NULL), "w"); while ( (c=fgetc(fp1))!=EOF) { if (!strchr ( set,c))fprintf ( fp2, "%c", c); } vfclose (fp1); vfclose (fp2); return tmp; } void remove_charset ( char *seq, char *set) { int a, b, l; char *set2; set2=(char*)vcalloc (256, sizeof (char)); if ( strm (set, "!alnum")) { for ( b=0,a=1;a< 256; a++)if ( !isalnum (a))set2[b++]=a; } else if ( strm ( set, "ungap")) { sprintf ( set2, "%s", GAP_LIST); } else { sprintf ( set2, "%s", set); } l=strlen ( seq); for (b=0, a=0; a=0; a--) { gap=is_gap(seq[a]); if ( !gap && !in_seq)break; if (gap && !in_seq)seq[a]=cache_seq[a]; } vfree(cache_seq); return seq; } void splice_out ( char *seq, char x) { int a, b, l; l=strlen ( seq); for (b=0, a=0; a<=l; a++) if ( seq[a]==x); else seq[b++]=seq[a]; seq[b]='\0'; } char *splice_out_seg ( char *seq, int pos, int len) { int l, a; if (seq==NULL || pos<0) return seq; l=strlen (seq); if ( l<(pos+len)) printf_exit ( EXIT_FAILURE, stderr, "Splice_out_seg out of bound: Length %d seg: [%d %d] [splice_out_seg::util.c][FATAL:%s]\n", l, pos, pos+len, PROGRAM); l-=len; for (a=pos; a< l; a++) seq[a]=seq[a+len]; seq[a]='\0'; return seq; } int isblanc ( char *buf) { int a, l; if ( buf==NULL)return 0; l=strlen (buf); for ( a=0; a< l; a++) if (isalnum (buf[a]))return 0; return 1; } int is_number ( char *num) { int a, l; l=strlen (num); for (a=0;amax_len) { max_len=l; max_index=a; } } if (index!=NULL)index[0]=max_index; if (len!=NULL)len[0]=max_len; } return max_len; } int get_shortest_string (char **array,int n, int *len, int *index) { int a, l; int min_len; if ( n==0|| array==NULL || read_size_char ( array,sizeof (char*))tms_stime*milli_sec_conv; tms_utime=(long)time_buf->tms_utime*milli_sec_conv; if ( ref==0) { ref=(tms_stime+tms_utime); return 0; } else { time=(tms_utime+tms_stime)-ref; return (int) ((time)/ticks); } } int get_ctime () { static long time; struct tms time_buf[1]; long tms_cutime, tms_cstime; if ( ticks==0)ticks = sysconf(_SC_CLK_TCK); times ( time_buf); tms_cstime=(long)time_buf->tms_cstime*milli_sec_conv; tms_cutime=(long)time_buf->tms_cutime*milli_sec_conv; if ( ref==0) { child=1; ref=tms_cstime+tms_cutime; return 0; } else { time=(tms_cutime+tms_cstime)-ref; return (int)((time)/ticks); } } int reset_time() { ref=0; return (int)get_time(); } int increase_ref_time(int increase) { if ( ref==0)get_time(); ref-=(long)ticks*(long)increase; if (ref==0)ref++; return (int)ref; } /*********************************************************************/ /* */ /* SYSTEM CALLS */ /* */ /* */ /*********************************************************************/ int evaluate_sys_call_io ( char *out_file, char *com, char *fonc) { if ( file_exists (NULL,out_file))return 1; else { add_warning (stderr, "COMMAND FAILED: %s",com); return 0; } } void HERE2 (char *string, ...) { va_list ap; va_start (ap, string); fprintf ( stdout, "\nHERE: "); vfprintf (stdout, string, ap); fprintf ( stdout, "\n"); va_end (ap); } void HERE (char *string, ...) { va_list ap; va_start (ap, string); fprintf ( stderr, "HERE: "); vfprintf (stderr, string, ap); fprintf ( stderr, "\n"); va_end (ap); } int fprintf_fork (FILE *fp, char *string, ...) { static char *openF; static char *closeF; FILE *flag; char *buf; if (!openF) { //openF=vcalloc (100, sizeof (char)); //sprintf (openF, "cedric1"); //closeF=vcalloc (100, sizeof (char)); //sprintf (closeF, "cedric2"); openF =vtmpnam (NULL); closeF=vtmpnam (NULL); vfclose(vfopen (openF,"w")); } while ((rename (openF,closeF))==-1); cvsprintf (buf,string); fprintf ( fp, "%s", buf); fflush (fp); rename (closeF, openF); vfree (buf); return 0; } int fprintf_fork2 (FILE *fp, char *string, ...) { char* buf; cvsprintf (buf, string); fprintf ( fp, "%s", buf); vfree (buf); fflush (fp); return 0; } int printf_file (char *file,char *mode, char *string,...) { FILE *fp; va_list ap; if (!(fp=vfopen (file, mode)))return 0; if (string) { va_start (ap, string); vfprintf (fp, string, ap); va_end (ap); } vfclose (fp); return 1; } int printf_system_direct_check (char *string, ...) { char *buf; int r; cvsprintf (buf, string); r=system (buf); if (r!=EXIT_SUCCESS) { printf_exit ( EXIT_FAILURE, stderr, "ERROR: Could not run %s\n", buf); } else { vfree (buf); return r; } } int printf_system_direct (char *string, ...) { char *buf; int r; cvsprintf (buf, string); r=system (buf); vfree(buf); return r; } int printf_system (char *string, ...) { char *buf; int r; char static *tmpdir; char static *cdir; cvsprintf (buf, string); r=my_system (buf); vfree(buf); return r; } int my_system_cl (int argc, char *argv[]) { int a,l; char *command; for ( a=0, l=0; a< argc; a++)l+=(strlen(argv[a])+2); command=(char*)vcalloc (l+1, sizeof(char)); for ( a=0; a< argc; a++) { command=strcat (command, argv[a]); command=strcat (command, " "); } a=my_system ( command); vfree (command); return a; } int my_system ( char *command0) { static char ***unpacked_list; static int n_unpacked; if (!unpacked_list) { unpacked_list=(char***)declare_arrayN(3, sizeof (char), 3, 200,vtmpnam_size()); } if ( getenv ("DEBUG_PERL"))return safe_system (command0); else { char **list; int is_command; int a, c=0; char *command1; char *command2; int return_val; command1=(char*)vcalloc ( 3*strlen (command0)+1, sizeof (char)); command2=(char*)vcalloc ( 100000, sizeof (char)); sprintf ( command1, "%s", command0); command1=substitute (command1, "|", " | "); command1=substitute (command1, ";", " ; "); list=string2list (command1); if ( !list) return EXIT_SUCCESS; is_command=1; //Identify T-Coffee self threads and install threads for ( a=1; a< atoi(list[0]); a++) { if ( is_command) { if ( strstr ( list[a], "unpack_")) { unpack_all_perl_script (list[a]+strlen ("unpack_")); myexit (EXIT_SUCCESS); } else if ((c=name_is_in_list (list[a], unpacked_list[0], n_unpacked, 100))!=-1); else { n_unpacked=unpack_perl_script (list[a], unpacked_list, n_unpacked);c=n_unpacked-1; } //if non unpacked script check pg is installed: if ( strm (unpacked_list[2][c], "shell")) { check_program_is_installed (list[a], NULL, NULL, NULL, INSTALL_OR_DIE); } strcat (command2, ((c!=-1)?unpacked_list[1][c]:list[a])); strcat (command2, " "); is_command=0; } else { strcat (command2, list[a]); strcat (command2, " "); if ( strm (list[a], ",") ||strm (list[a], "|")) is_command=1; } } free_char (list,-1); vfree ( command1); command2=substitute ( command2, "//", "/"); command2=substitute ( command2, ":/", "://"); return_val=safe_system (command2); vfree ( command2); return return_val; } } int has_warning_lock() { if (lock(getpid(), LWARNING, LCHECK,NULL))return 1; else return 0; } int has_error_lock() { if (lock(getpid(), LERROR, LCHECK,NULL))return 1; else return 0; } int is_shellpid(int pid) { if ( lock(pid, LLOCK, LCHECK, NULL) && strstr (lock(pid,LLOCK, LREAD, NULL), "-SHELL-"))return 1; else return 0; } int is_rootpid() { static pid_t root_pid=0; pid_t cp; cp=getpid(); if( root_pid == 0 ) { root_pid = cp; } int result = (cp == root_pid); return result; //old is_rootpid // // if (debug_lock) // { // char *f; // fprintf ( stderr,"\n\t------ check if %d isrootpid (util): %s->%d", getpid(),f=lock2name (getppid(),LLOCK), (lock(getppid(), LLOCK, LCHECK, NULL))?1:0); // vfree (f); // } // // // if(lock (getppid(), LLOCK, LCHECK, NULL)!=NULL)return 0; // else return 1; // } int shift_lock ( int from, int to, int from_type,int to_type, int action) { //action: SET (concatenate) or RESET (replace parent with child content) char *e; if (!lock (from,from_type, LCHECK, NULL))return 0; e=lock (from,from_type, LREAD, NULL); lock (from,from_type, LRELEASE, NULL); if ( action==LSET || action==LRESET)lock (to, to_type,action, e); else { myexit(fprintf_error (stderr, "Unsupported type for shift_lock")); } vfree (e); return 1; } char*lock2name (int pid, int type) { char *fname; char host[1024]; gethostname(host, 1023); fname=(char*)vcalloc (strlen(host)+strlen (get_lockdir_4_tcoffee())+1000, sizeof (char)); if (type == LLOCK)sprintf (fname, "%s/.%d.%s.lock4tcoffee",get_lockdir_4_tcoffee(), pid,host); else if ( type == LERROR) sprintf (fname, "%s/.%d.%s.error4tcoffee", get_lockdir_4_tcoffee(),pid,host); else if ( type == LWARNING) sprintf (fname, "%s/.%d.%s.warning4tcoffee",get_lockdir_4_tcoffee(),pid,host); else myexit(fprintf_error ( stderr, "ERROR: Unknown type for lock")); return fname; } int release_all_locks (int pid) { lock (pid, LLOCK, LRELEASE, NULL); lock (pid, LERROR, LRELEASE, NULL); lock (pid, LWARNING, LRELEASE, NULL); return 1; } char* lock(int pid,int type, int action,char *string, ...) { char *fname; char *r; fname=lock2name (pid, type); if (debug_lock) { fprintf (stderr,"\n\t\t---loc4tc(util.h) %d =>%s [RD: %s]\n", action, fname, getcwd(NULL, 0)); } if (action == LREAD) { r=file2string (fname); } else if ( action == LCHECK) { r=const_cast( (file_exists (NULL,fname))?"x":NULL ); } else if (action== LRELEASE) { if (debug_lock) { printf_system_direct ("mv %s %s.released", fname, fname); } else if (file_exists (NULL, fname)) { vremove (fname); //safe_remove (fname);return NULL; } r=" "; } else if ( clean_exit_started) return NULL; //NO MORE LOCK SETTING during EXIT Phase else if (action== LSET || action == LRESET) { char *value; if (string) { cvsprintf (value,string); } else { value=(char*)vcalloc (2, sizeof(char)); sprintf (value, " "); } string2file (fname, const_cast( (action==LSET)?"a":"w"), value); vfree (value); r= " "; } else myexit(fprintf_error ( stderr, "ERROR: Unknown action for LOCK")); vfree (fname); return r; } int check_process (const char *com,int pid,int r, int failure_handling) { //If the child process has an error lock, copy that lock into the parent'lock //The error stack trace of the child gets passed to the parent if (debug_lock)fprintf (stderr, "\nEVAL_CALL ----- %d ->%s\n",pid, (r==EXIT_FAILURE)?"FAIL":"SUCCESS"); if ( failure_handling == IGNORE_FAILURE) return r; if ( lock(pid, LWARNING, LCHECK, NULL)) { shift_lock (pid, getpid(), LWARNING, LWARNING,LSET); } if ( lock(pid, LERROR, LCHECK, NULL)) { shift_lock (pid, getpid(), LERROR,LERROR, LSET); } else if (r==EXIT_FAILURE) { //Reconstruct missing errorlock lock (getpid(), LERROR,LSET,"%d -- ERROR: UNSPECIFIED UNSPECIFIED\n",pid); lock (getpid(), LERROR,LSET,"%d -- COM: %s\n",pid,com); lock (getpid(), LERROR, LSET,"%d -- STACK: %d -> %d\n",pid,getpid(), pid); } //lock is now ready. Shall we use it? if (lock(getpid(), LERROR, LCHECK, NULL)) { if (failure_handling==RETURN_ON_FAILURE) { shift_lock(getpid(),getpid(),LERROR, LWARNING,LSET); } else { myexit (EXIT_FAILURE); } } return r; } int safe_system (const char * com_in) { pid_t pid; int status; int failure_handling; char *p; char command[1000]; static char *com; if ( clean_exit_started) return system (com_in); if ( com)vfree (com); if ( strstr ( com_in, "SCRATCH_FILE")) { com=(char*)vcalloc ( strlen ( com_in)+1, sizeof (char)); sprintf ( com, "%s", com_in); while (strstr ( com, "SCRATCH_FILE")) { char *t; t=vtmpnam(NULL); com=(char*)vrealloc (com, (strlen (com)+strlen (t)+1)*sizeof (char)); com=substitute (com,"SCRATCH_FILE", t); } } else { com=(char*)vcalloc (strlen (com_in)+1, sizeof (char)); sprintf ( com, "%s", com_in); } if (com == NULL) return (1); else if ( (p=strstr (com, "::IGNORE_FAILURE::"))) { p[0]='\0'; failure_handling=IGNORE_FAILURE; } else if ( (p=strstr (com, "::RETURN_ON_FAILURE::"))) { p[0]='\0'; failure_handling=RETURN_ON_FAILURE; } else if ( (p=strstr (com, "::EXIT_ON_FAILURE::"))) { p[0]='\0'; failure_handling=EXIT_ON_FAILURE; } else { failure_handling=EXIT_ON_FAILURE; } sprintf ( command, " -SHELL- %s (tc)", com_in); if ((pid = vvfork (command)) < 0) return (-1); if (pid == 0) { char * argv [4]; argv [0] = "sh"; argv [1] = "-c"; argv [2] =(char*) com; argv [3] = 0; if ( debug_lock)fprintf (stderr,"\n--- safe_system (util.h): %s (%d)\n", com, getpid()); execvp ("/bin/sh", argv); } else { set_pid(pid); } while (1) { int r; r=vwaitpid (pid, &status, 0); if (errno ==EINTR)r=EXIT_SUCCESS; else if (r==-1 || status != EXIT_SUCCESS)r=EXIT_FAILURE; else r=EXIT_SUCCESS; if ( debug_lock) fprintf ( stderr, "\n--- safe system return (util.c): p:%d c:%d r:%d (wait for %d", getppid(), getpid(), r, pid); return check_process (com_in,pid,r, failure_handling); } } static int **pidtable; int assert_pid (pid_t p) { if ( p>= MAX_N_PID || p<0) { printf_exit (EXIT_FAILURE, stderr, "MAX_N_PID exceded -- Recompile changing the value of MAX_N_PID (current: %d Requested: %d)", MAX_N_PID, p); } return 1; } pid_t **declare_pidtable () { int a; pidtable=(int**)vcalloc (MAX_N_PID, sizeof (pid_t*)); for (a=0; a0) { vwait (NULL); sub--; } } else if ( sub>=max) { while (sub>=min) { vwait (NULL); sub--; } } else{;} return sub; } pid_t vwaitpid (pid_t p, int *status, int options) { p=waitpid (p, status, options); if (pidtable) { assert_pid (p); pidtable[(int)p][0]=pidtable[(int)p][1]=0; } return p; } pid_t vwait (pid_t *p) { pid_t p2; int rv=0; int handle_failure; if (atoigetenv("RETURN_ON_FAILURE"))handle_failure=RETURN_ON_FAILURE; else handle_failure=EXIT_ON_FAILURE; p2=wait(&rv); if (p2!=-1)rv=check_process("forked::T-Coffee", p2, rv,handle_failure); if ( p) p[0]=rv; return p2; } int get_child_list (int pid,int *clist); void kill_child_list (int *list); int kill_child_pid(int pid) { int *list; int n,a, cpid; cpid=getpid(); list=(int*)vcalloc (MAX_N_PID, sizeof (int)); while ((n=get_child_list (pid,list))) { kill_child_list (list); } for (a=0; a1) { add_information ( stderr, "WARNING Lock System not solved correctly." ); for (a=0; a %s", file); s=file2string (file); lower_string (s); if (strstr (s, "cygwin"))sprintf ( os, "windows"); else if ( strstr (s, "linux"))sprintf ( os, "linux"); else if ( strstr (s, "osx"))sprintf ( os, "macosx"); else if ( strstr (s, "darwin"))sprintf ( os, "macosx"); else sprintf (os, "linux"); vfree (s); vremove (file); } return os; } int cputenv (char *string, ...) { char *s; char *s2; int r; if (!string)return 0; cvsprintf (s, string); s2=(char*)vcalloc (strlen (s)+1, sizeof (char)); sprintf ( s2, "%s", s); r=putenv (s2); //vfree (s); //Potential leak return r; } int fcputenv (char *file, char *mode,char * string, ...) { va_list ap; FILE *fp; if (!string)return 0; if (!(fp=vfopen (file, mode)))return 0; va_start (ap, string); vfprintf (fp, string, ap); vfclose (fp); va_end (ap); return 1; } int isdir4path (char *p) { if ( !p) return 0; if ( !p || access (p, F_OK)==-1 || access (p, W_OK)==-1 || access(p, R_OK)==-1 || access (p, X_OK)==-1)return 0; return 1; } int check_dir_getenv ( char *string) { char *p; return (isdir4path(p=getenv ( string))); } int set_unique_dir_4_tcoffee (char *dir); int set_unique_dir_4_tcoffee (char *dir) { static char **string; int m, n; m=n=0; if ( !dir || !isdir(dir) || strm (dir, "no"))return 0; string=declare_char (10, 100); sprintf ( string[m++], "DIR_4_TCOFFEE=%s", dir);putenv (string[n++]); sprintf ( string[m++], "CACHE_4_TCOFFEE=%s", dir);putenv (string[n++]); sprintf ( string[m++], "TMP_4_TCOFFEE=%s", dir);putenv (string[n++]); sprintf ( string[m++], "PLUGINS_4_TCOFFEE=%s", dir);putenv (string[n++]); sprintf ( string[m++], "MCOFFEE_4_TCOFFEE=%s", dir);putenv (string[n++]); sprintf ( string[m++], "METHODS_4_TCOFFEE=%s", dir);putenv (string[n++]); return 1; } void myexit (int signal) { if (clean_exit_started==1)return; //protects processes while they are doing a clean exit global_exit_signal=signal; exit (global_exit_signal); //ONLY BARE EXIT!!!!!!!!!!!!!! } static int n_warning; static char **warning_list; FILE *fatal_exit (FILE *fp,int exit_mode, char *string, ...) { va_list ap; va_start (ap, string); vfprintf (fp, string, ap); va_end (ap); myexit (exit_mode); return fp; } static int warning_mode; int set_warning_mode ( int mode) { warning_mode=mode; return mode; } int fprintf_error( FILE *fp, char *string, ...) { char *msg; cvsprintf (msg, string); msg=substitute ( msg, "\n", ""); msg=substitute ( msg, "ERROR", " "); if (fp)fprintf ( fp, "\n--ERROR: %s\n", msg); if ( clean_exit_started) return EXIT_FAILURE; lock (getpid(), LERROR,LSET,"%d -- ERROR: %s\n",getpid(),msg); lock (getpid(), LERROR,LSET,"%d -- COM: %s\n",getpid(),in_cl); lock (getpid(), LERROR, LSET,"%d -- STACK: %d -> %d\n",getpid(), getppid(),getpid()); vfree (msg); return EXIT_FAILURE; } void printf_exit (int exit_code, FILE *fp, char *string, ...) { char *msg; cvsprintf (msg, string); myexit(fprintf_error (fp,msg)); myexit (exit_code); } FILE *add_warning (FILE *fp, char *string, ...) { char *buf; if ( warning_mode==NO || getenv("NO_WARNING_4_TCOFFEE"))return fp; else { cvsprintf (buf, string); if (fp)fprintf (fp, "\npid %d -- %s\n",getpid(), buf); if ( clean_exit_started)return fp; lock(getpid(),LWARNING, LSET, "%d -- WARNING: %s\n", getpid(),buf); vfree (buf); } return fp; } FILE *add_information (FILE *fp, char *string, ...) { char *buf; if ( warning_mode==NO || getenv("NO_INFORMATION_4_TCOFFEE"))return fp; else { cvsprintf(buf, string); if (fp)fprintf (fp, "\npid %d -- %s\n",getpid(), buf); if ( clean_exit_started)return fp; lock(getpid(),LWARNING, LSET, "%d -- INFORMATION: %s\n", getpid(),buf); vfree (buf); } return fp; } int count_n_res_in_array (char *array, int len) { return count_n_symbol_in_array(array, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", len); } int count_n_gap_in_array (char *array, int len) { int l; if ( len<=0 ||len>strlen(array) )l=strlen(array); else l=len; return l- count_n_res_in_array (array,len); } int count_n_symbol_in_array ( char *array, char *array_list, int len) { int a=0, t=0; int l; if ( len<=0 ||len>strlen(array) )l=strlen(array); else l=len; for ( a=0; a< l; a++)t+=is_in_set (array[a], array_list); return t; } char* count_strings_in_file ( char *in, char *out) { FILE *fp; int n,c; char **list, **result; if (!out) out=vtmpnam (NULL); list=declare_char (count_n_line_in_file(in)+1, measure_longest_line_in_file (in)+1); n=0; fp=vfopen (in, "r"); while ((c=fgetc (fp))!=EOF) { ungetc (c, fp); fscanf (fp, "%s\n",list[n]); n++; } vfclose (fp); result=count_strings (list, n); n=0; fp=vfopen (out, "w"); while (result[n])fprintf ( fp,"%s\n", result[n++]); vfclose (fp); free_char (list, -1); free_char (result, -1); return out; } int ** count_int_strings (int **array, int len, int s) { int **result; int a,n; sort_list_int (array,s, s,0, len-1); result=(int**)vcalloc (len, sizeof (int*)); for (n=-1,a=0; a:$PATH\n"); fprintf ( fp, "* Make this permanent by adding this line to the file\n"); fprintf ( fp, "* ~/.bashrc\n"); fprintf ( fp, "* If this package is not installed but supported you can try to install it via t_coffee:\n"); fprintf ( fp, "* t_coffee -other_pg install \n"); fprintf ( fp, "* Otherwise you must install it yourself\n"); fprintf ( fp, "*************************************************************************************************\n"); return fp; } FILE* proxy_msg(FILE*fp) { fprintf ( fp, "\n\n"); fprintf ( fp, "*************************************************************************************************\n"); fprintf ( fp, "* CONFIGURATION: Faulty Network OR Missing Proxy \n"); fprintf ( fp, "* \n"); fprintf ( fp, "* \n"); fprintf ( fp, "* It looks like you cannot access the network\n"); fprintf ( fp, "* Check that your network is up and running...\n"); fprintf ( fp, "* If you are behind a firewall, you must enter your proxy address to use webservices\n"); fprintf ( fp, "* This address is usualy something like: http://some.place.here:8080\n"); fprintf ( fp, "* Todo this via the command line:\n"); fprintf ( fp, "* \n"); fprintf ( fp, "* -proxy= \n"); fprintf ( fp, "* \n"); fprintf ( fp, "*To make it permanent:\n"); fprintf ( fp, "* export PROXY_4_TCOFFEE=\n"); fprintf ( fp, "*Add this line to either:\n"); fprintf ( fp, "* /.bashrc\n"); fprintf ( fp, "* OR %s/.t_coffee_env\n", get_dir_4_tcoffee()); fprintf ( fp, "*************************************************************************************************\n"); return fp; } FILE* email_msg(FILE*fp) { fprintf ( fp, "\n\n"); fprintf ( fp, "*************************************************************************************************\n"); fprintf ( fp, "* CONFIGURATION: Missing Email \n"); fprintf ( fp, "* \n"); fprintf ( fp, "* This mode of T-Coffee uses the EBI BLAST webservices. The EBI requires a valid E-mail \n"); fprintf ( fp, "* address for this service to be used (check: www.ebi.ac.uk/Tools/webservices/). \n"); fprintf ( fp, "* \n"); fprintf ( fp, "* To provide the email, add to the command line:*\n"); fprintf ( fp, "* \n"); fprintf ( fp, "* -email= *\n"); fprintf ( fp, "*To make it permanent:\n"); fprintf ( fp, "* export EMAIL_4_TCOFFEE=\n"); fprintf ( fp, "*Add this line to either:\n"); fprintf ( fp, "* ~/.bashrc\n"); fprintf ( fp, "* OR %s/.t_coffee_env\n", get_dir_4_tcoffee()); fprintf ( fp, "*************************************************************************************************\n"); return fp; } void update_error_dir() { ; } void dump_tcoffee(char *target, char *nature) { char **list, *s; int a=0; FILE *fp; char *f; char *out_list; if ((fp=fopen (target, "w"))) { fprintf (fp, "\n%s\n", nature); fprintf (fp, "%s\n", PROGRAM); fprintf (fp, "%s\n",VERSION); fprintf (fp, "%s\n",BUILD_INFO); if ((f=strstr (in_cl, "-dump")))f[0]='\0'; fprintf (fp, "%s\n",in_cl); fprintf (fp, "\n"); stack_msg(fp); fprintf (fp, "\n\n"); warning_msg (fp); fprintf (fp, "\n"); //dump input list=string2list (in_cl); out_list=file2string (get_string_variable ("dump_output_file_list")); for (a=1; a\ninput\n"); fprintf (fp, "%s\n",s); fprintf (fp, "\n"); while ((c=fgetc(fp2))!=EOF)fprintf ( fp, "%c", c); fclose (fp2); fprintf (fp, "\n\n"); } } //dump output if ((f=get_string_variable ("dump_output_file"))) { FILE *fp2; char c; if ((fp2=fopen (f, "r"))!=NULL) { while ((c=fgetc (fp2))!=EOF)fprintf (fp, "%c",c); fclose (fp2); } } fprintf (fp, "\n"); fclose (fp); printf_system_direct("printenv >> %s", target); fp=fopen (target, "a"); fprintf (fp, "\n"); fclose (fp); fprintf ( stderr, "\n#----- Dumped File: %s\n",target); } else fprintf ( stderr, "\n#----- Could NOT Produce Dump File: %s -- Sorry \n", target); } void dump_error_file() { char target[1000]; char **list, *s; int a=0; FILE *fp; sprintf ( target, "%s",getenv("ERRORFILE_4_TCOFFEE")); if (strstr (target, "NO")); else dump_tcoffee (target, "error"); return; if ((fp=fopen (target, "w"))) { fprintf ( fp, "\n######### RUN_REPORT START ######"); fprintf ( fp, "\n######### PROGRAM_VERSION START ######"); fprintf ( fp, "\n %s, %s (%s)", PROGRAM, VERSION, BUILD_INFO); fprintf ( fp, "\n######### PROGRAM_VERSION END ######"); fprintf ( fp, "\n######### COMMAND_LINE START ######"); fprintf ( fp, "\n%s", in_cl); fprintf ( fp, "\n######### COMMAND_LINE END ######\n"); fprintf ( fp, "\n######### MESSAGES START ######\n"); stack_msg(fp); warning_msg (fp); fprintf ( fp, "\n######### MESSAGES END ######\n"); fprintf ( fp, "\n######### FILES START ######\n"); list=string2list (in_cl); for (a=1; a> %s", target); fprintf ( stderr, "\n#----- Dumped ErrorFile: %s\n",target); } else fprintf ( stderr, "\n#----- Could NOT Dumpe ErrorFile: %s -- Sorry \n", target); } FILE* error_msg(FILE*fp ) { if ( no_error_report)return fp; char errorfile[100]; sprintf (errorfile , "%s", getenv("ERRORFILE_4_TCOFFEE")); fprintf( fp,"\n\t******************************************************************"); fprintf( fp, "\n\t* Abnormal Termination"); fprintf( fp, "\n\t* Job NOT Completed:[%s, %s]",PROGRAM, VERSION); fprintf( fp, "\n\t* Please CHECK: "); fprintf( fp, "\n\t* \t-1 The format of your Input Files "); fprintf( fp, "\n\t* \t-2 The parameters "); fprintf( fp, "\n\t* \t-3 The use of special characters in sequence names:"); fprintf( fp, "\n\t* \t\t (@, |, %%...)"); fprintf( fp, "\n\t* \t-4 The Online Doc (%s) ", URL); if ( strm (errorfile, "NO")) fprintf( fp, "\n\t* \t-5 re-run your CL (see below) with tze -debug option. This will produce a debug file you can send us."); else fprintf( fp, "\n\t* \t-5 Send the file:"); fprintf (fp, "\n\t*"); fprintf (fp, "\n\t*\t %s ", getenv("ERRORFILE_4_TCOFFEE")); fprintf (fp, "\n\t* to:"); fprintf( fp, "\n\t* \t\t%s",EMAIL); fprintf( fp, "\n\t* If you run T-Coffee over the WEB:"); fprintf( fp, "\n\t* \tWindows Cut and Paste is sometimes erratic and"); fprintf( fp, "\n\t* \tit can loose carriage returns. If you suspect this,"); fprintf( fp, "\n\t* \ttry to cut and paste through an intermediate application"); fprintf( fp, "\n\t* \t(word pad) and inspect the results\n\n"); fprintf( fp, "\n\t* CONFIDENTIALITY:"); fprintf( fp, "\n\t* \tThe File %s may contain your personal DATA", getenv("ERRORFILE_4_TCOFFEE")); fprintf( fp, "\n\t* \tRemove ALL confidential DATA from this file BEFORE sending it"); fprintf( fp, "\n\t******************************************************************\n"); print_command_line(fp); return fp; } char *get_email_from_env () { char *email=NULL; if ( (email=get_string_variable ("cl_email"))); else if ( (email=get_string_variable ("email"))); else if ( (email=getenv ("EMAIL_4_TCOFFEE"))); else if ( (email=getenv ("EMAIL"))); else email=(char*)vcalloc ( 1, sizeof (char)); return email; } int set_email (char *email) { if (!email) return 0; cputenv ("EMAIL_4_TCOFFEE=%s", email); cputenv ("EMAIL=%s",email); return 1; } char *chomp (char *name) { int a=0; while ( name[a]!='\n' && name[a]!='\0')a++; name[a]='\0'; return name; } static Tmpname *tmpname; static Tmpname *ntmpname; static int n_tmpname; static int file2remove_flag; char *set_file2remove_extension (char *extension, int mode) { static char ext[100]; if (mode==SET)sprintf (ext, "%s", extension); else if ( mode==UNSET) ext[0]='\0'; else if ( mode==GET); return ext; } int flag_file2remove_is_on () { return file2remove_flag; } void set_file2remove_on() { file2remove_flag=1; } void set_file2remove_off() { file2remove_flag=0; } char *add2file2remove_list (char *name) { if ( !tmpname || !name)ntmpname=tmpname=(Tmpname*)vcalloc ( 1, sizeof (Tmpname)); else if (!ntmpname->name); else ntmpname=ntmpname->next=(Tmpname*)vcalloc ( 1, sizeof (Tmpname)); if (!name) return NULL; ntmpname->name=(char*)vcalloc(strlen(name)+1, sizeof (char)); sprintf (ntmpname->name, "%s", name); return ntmpname->name; } //char *short_tmpnam_2(char *s);//used to generate very compact tmp names void initiate_vtmpnam (char *file) { add2file2remove_list (NULL); tmpnam_2(NULL); } char *vtmpnam ( char *s1) { char *s,*s2; n_tmpname++; standard_initialisation(NULL, NULL); s=(char*)vcalloc ( VERY_LONG_STRING, sizeof (char)); s[0]='\0'; s=tmpnam_2 (s); s2=add2file2remove_list (s); if (s!=s2)vfree (s); if (s1){sprintf (s1, "%s",s2);return s1;} else return s2; } int vtmpnam_size() { static int size; if (!size) { char *p=vtmpnam (NULL); size=(strlen (p)*2)+1; } return size; } int get_vtmpnam2_root() { int MAX_TMPNAM_ROOT=10000; static int v; if (v) ; else { vsrand(0); v=rand()%MAX_TMPNAM_ROOT; } return v; } char *tmpnam_2 (char *s) { static int root; static int file; char buf[VERY_LONG_STRING]; static char root2[VERY_LONG_STRING]; static char *tmpdir; static int name_size; if ( !root || !s) { char *vtmpnam_prefixe; name_size=MAX( 2*L_tmpnam, MAXNAMES*2)+1; root=get_vtmpnam2_root(); sprintf ( root2, "%d%d_", root, (int)getpid()); vtmpnam_prefixe=(char*)vcalloc (strlen (root2)+strlen (get_tmp_4_tcoffee())+2, sizeof (char)); sprintf (vtmpnam_prefixe, "%s/%s", get_tmp_4_tcoffee(), root2); set_string_variable ("vtmpnam_prefixe1", vtmpnam_prefixe); set_string_variable ("vtmpnam_prefixe2", root2); vfree (vtmpnam_prefixe); } if (!s)return NULL; tmpdir=get_tmp_4_tcoffee(); sprintf (buf, "%s/%s%d_TCtmp%s",tmpdir,root2, file++,set_file2remove_extension (NULL, GET)); if ( strlen(buf)>=name_size)s=(char*)vrealloc (s,(strlen(buf)+1)*sizeof (char)); sprintf (s, "%s", buf); return s; } char *short_tmpnam_2(char *s) { static int root; static int file; char buf[VERY_LONG_STRING]; static char root2[VERY_LONG_STRING]; static int name_size; if ( !root || !s) { char *vtmpnam_prefixe; name_size=MAX( 2*L_tmpnam, MAXNAMES*2)+1; root=get_vtmpnam2_root(); sprintf ( root2, "%d%d", root,getpid()); vtmpnam_prefixe=(char*)vcalloc (strlen (root2)+strlen (get_tmp_4_tcoffee())+2, sizeof (char)); sprintf (vtmpnam_prefixe, "%s", root2); set_string_variable ("vtmpnam_prefixe1", vtmpnam_prefixe); set_string_variable ("vtmpnam_prefixe2", root2); vfree (vtmpnam_prefixe); } if (!s) return NULL; sprintf (buf, "%s%d%s",root2, file++,set_file2remove_extension (NULL, GET)); if ( strlen(buf)>=name_size)s=(char*)vrealloc (s,(strlen(buf)+1)*sizeof (char)); sprintf (s, "%s", buf); return s; } char *vremove2 (char *s) { char list_file[1000]; char ***list; int a; //Remove filenames with a wildcard sprintf (list_file, "list_file_%d", (int)getpid()); printf_system_direct("ls -1 %s>%s 2>/dev/null", s, list_file); list=file2list (list_file, " "); a=0; while (list && list[a]) { if ( file_exists (NULL,list[a][1])) { vremove (list[a][1]); } a++; } vremove (list_file); return NULL; } void safe_remove (char *s)//remove even if the file is partly unaccessible { FILE *fp; if ( !s) return; else if (!(fp=fopen (s, "w")))return; else { fclose (fp); remove (s); } } char *vremove (char *s) { if ( s && strstr (s, "*"))return vremove2(s); else if ( !s || !file_exists(NULL,s) ) return NULL; else if ( isdir (s)) { rmdir (s); return NULL; } else { remove (s); return NULL; } return NULL; } int log_function ( char *fname) { if ( file_exists (NULL,error_file)) { printf_system_direct ("cp %s %s", error_file, fname); fprintf( stderr,"\n\t******************************************************************"); fprintf( stderr, "\n\t* Full Log of [%s, %s] in File [%s]",PROGRAM, VERSION, fname); fprintf( stderr, "\n\t******************************************************************\n"); } return 1; } FILE *NFP;/*Null file pointer: should only be open once*/ /*********************************************************************/ /* */ /* CACHE_FUNCTION */ /* */ /* */ /*********************************************************************/ static char *cache; char * prepare_cache ( const char *mode) { cache =(char*)vcalloc ( 10000, sizeof(char)); if (strm (mode, "use")) { sprintf (cache, "%s",get_cache_4_tcoffee()); } else if ( strm (mode, "ignore") || strm (mode, "no")) { cache=vtmpnam(cache); strcat (cache, "/"); printf_system_direct ("mkdir %s",cache); } else if ( strm (mode, "update")) { cache=vtmpnam(cache); strcat (cache, "/"); printf_system_direct ("mkdir %s",cache); } else if ( strm (mode, "local")) { cache[0]='\0'; } else { sprintf ( cache, "%s/",mode); my_mkdir ( cache); } return cache; } char * get_cache_dir() { if ( cache==NULL){cache=(char*)vcalloc (1, sizeof (char));cache[0]='\0';} return cache; } void update_cache () { char old_cache[1000]; sprintf ( old_cache, "%s", get_cache_dir()); prepare_cache( "use"); printf_system_direct ("mv %s* %s",old_cache, get_cache_dir()); printf_system_direct ("rmdir %s",old_cache); } void ignore_cache() { if (getenv4debug ("DEBUG_TMP_FILE")) { fprintf ( stderr, "\n[DEBUG_TMP_FILE:%s] TEMPORARY CACHE HAS NOT Been Removed:\n\t%s\n", PROGRAM,get_cache_dir()); } else { printf_system_direct ("rm -r %s",get_cache_dir()); } return; } FILE *fopenN ( char *fname, char *mode, int max_n_tries, int delay); FILE * vfopen ( char *name_in, char *mode) { FILE *fp; int get_new_name; int tolerate_mistake; int cache_used=0; FILE *tmp_fp; int c; static char *name; static char *name2; static char *stdin_file; if ( !name_in)return NULL; if (!name){name=(char*)vcalloc (1000, sizeof (char));} if (!name2){name2=(char*)vcalloc (1000, sizeof (char));} //intercept net files if ( strstr (name_in, "tp:/") && mode && (mode[0]=='r' || mode[0]=='R')) { char *tmpf; tmpf=check_url_exists(name_in); if (!tmpf) { myexit(fprintf_error (stderr, "\nCould not fetch nefile %s -FORCED EXIT (NON INTERACTIVE MODE pid %d)\n", name_in,getpid())); } else return vfopen (tmpf, mode); } sprintf ( name, "%s", name_in); tild_substitute (name, "~", get_home_4_tcoffee()); get_new_name=tolerate_mistake=0; if ( mode[0]=='g'){get_new_name=1; mode++;} else if ( mode[0]=='t'){tolerate_mistake=1;mode++;} /*Use the cached version from CACHE_4_TCOFFEE*/ else if ( mode[0]=='c'){cache_used=1;mode++;} if (name==NULL ||strm5 ( name, "no","NO","No","NULL","/dev/null") || strm2 (name, "no_file", "NO_FILE")) { if ( NFP==NULL)NFP=fopen (NULL_DEVICE, mode); return NFP; } else if ( strm3 (name,"stderr","STDERR","Stderr"))return stderr; else if ( strm3 (name,"stdout","STDOUT","Stdout"))return stdout; else if ( strm3 ( name, "stdin","STDIN","Stdin")) { if (!stdin_file) { stdin_file=vtmpnam (NULL); tmp_fp=vfopen ( stdin_file, "w"); while ( (c=fgetc(stdin))!=EOF)fprintf (tmp_fp, "%c", c); vfclose ( tmp_fp); } return vfopen (stdin_file, "r"); } else if ( strm (name, "") && (strm (mode, "w") ||strm (mode, "a")) )return stdout; else if ( strm (name, "") && strm (mode, "r"))return stdin; else if ( (fp= fopen ( name, mode))==NULL) { if ( strcmp (mode, "r")==0 && cache_used==0) { sprintf ( name2, "%s%s",get_cache_dir(), name); return vfopen ( name2, "cr"); } else if ( strcmp (mode, "r")==0 && cache_used==1) { fprintf (stderr, "\n--COULD NOT READ %s\n", name); if ( get_new_name){fprintf ( stderr, "\nNew name: ");return vfopen (input_name(), mode-1);} else if ( tolerate_mistake)return NULL; else { myexit(fprintf_error (stderr, "\nFORCED EXIT (NON INTERACTIVE MODE pid %d)\n", getpid())); } } else if ( strcmp (mode, "a")==0 && cache_used==0) { sprintf ( name2, "%s%s",get_cache_dir(), name); return vfopen ( name, "ca"); } else if ( strcmp (mode, "a")==0 && cache_used==1) { fprintf (stderr, "\nCOULD NOT Append anything to %s\n", name);exit (0); if ( get_new_name){fprintf ( stderr, "\nNew name: ");return vfopen (input_name(), mode-1);} else if ( tolerate_mistake)return NULL; else { myexit(fprintf_error (stderr, "\nFORCED EXIT (NON INTERACTIVE MODE pid %d)\n", getpid())); } } else if ( strcmp (mode, "w")==0) { fprintf (stderr, "\nCANNOT WRITE %s\n", name); if ( get_new_name==1){fprintf ( stderr, "\nNew name: ");return vfopen (input_name(), mode-1);} else if ( tolerate_mistake)return NULL; else { myexit(fprintf_error (stderr, "\nFORCED EXIT (NON INTERACTIVE MODE pid %d): %s %s\n", getpid(),(strcmp ( mode, "r")==0)?"READ":"WRITE", name)); } } } else return fp; return NULL; } FILE *fopenN ( char *fname, char *mode, int max_n_tries, int delay) { FILE *fp; int a; for (a=0; a< max_n_tries; a++) { if ((fp=fopen (fname, mode))) return fp; else sleep (delay); HERE ("---- failed opening: %s", fname); } return NULL; } FILE * vfclose ( FILE *fp) { if ( fp==NFP)return NULL; if ( fp==stdout)return stdout; if ( fp==stderr)return stderr; if ( fp==stdin) return stdin; if ( fp==NULL)return NULL; else if (fclose (fp)!=0)HERE ("***** ERROR****"); return NULL; } int echo ( char *string, char *fname) { int a; /* description: prints the content of string into file fname in: string= string to print fname =name of the file to create */ FILE *fp; fp=vfopen ( fname, "w"); fprintf (fp, "%s", string); a=fclose (fp); return a; } int file_cat ( char *from, char *to) { FILE *fp; //appends the content of file1 to file 2 if (!(fp=vfopen (to, "a")))return 0; if (!display_file_content (fp, from)) return 0; vfclose (fp); return 1; } FILE* display_file_content (FILE *output, char *name) { FILE *fp; int c; if ( !name || !file_exists (NULL,name) || !(fp=vfopen (name, "r")))return NULL; while ( (c=fgetc(fp))!=EOF)fprintf (output,"%c", c); vfclose (fp); return output; } char **list2expanded_flist (char **list, int *n, char *tag) { //expand files into lists //a file list is declared as tag1:: //or as a file whose first line is FILE_LIST:: //expansion keeps going recursively until all files have been expanded //keeps trap of infinite loops (i.e. file referencing itself int a=0; while (list[a]!=NULL) { char *f=NULL; if (strstr (list[a], tag)){f=list[a]+strlen (tag);} else if ( token_is_in_file_n (list[a],tag,1))f=list[a]; else f=NULL; if (f) { list=expand_flist(f,list,a,n,tag); } else { a++; } } return list; } char **expand_flist (char *file, char **list,int i,int *n, char *tag) { //expand the content of a file within a list of files; //make sure the last element is null (list[n[0]] int nl=0; char ***fl=file2list(file, "\n"); char **nlist; int nn=0; int a; while (fl[nl++]); nlist=(char**)vcalloc (n[0]+nl+1, sizeof (char*)); //put the old stuff back for (a=0; anlines; lines[1]->first_line */ char **lines; char *string; string=file2string (name); if ( !string) return NULL; else { lines=string2list2(string, "\n"); vfree ( string); return lines; } } int string2file (char *file, char *mode, char *string,...) { FILE *fp; va_list ap; if (!file) return 0; else if ( !mode) return 0; else if ( !(fp=vfopen (file, mode)))return 0; va_start (ap, string); vfprintf (fp, string, ap); vfclose (fp); va_end (ap); return 1; } char *file2string (char *name) { FILE*fp; char *string; int a, c; if (!name || !file_exists (NULL,name))return NULL; else { a=0; if ((fp=fopen (name, "r"))) { while ( (c=fgetc(fp))!=EOF)a++; fclose (fp); } else return NULL; string=(char*)vcalloc (a+1, sizeof (char)); a=0; if ((fp=fopen (name, "r"))) { while ( (c=fgetc(fp))!=EOF)string[a++]=c; fclose (fp); } else return NULL; string[a]='\0'; return string; } } int file2size(char *name) { FILE *fp; char c; int n=0; fp=vfopen (name, "r"); while ((c=fgetc (fp)!=EOF))n++; vfclose (fp); return n; } /** * Read command line parameters. * * This function is repeatedly used in the beginning of ::batch_main to collect all the input from * the command line. Here is one example how it is called: * \code * declare_name (extend_mode); * get_cl_param(\ * /*argc* / argc , * /*argv* / argv ,\ * /*output* / &le ,\ * /*Name* / "-extend_mode" ,\ * /*Flag* / &garbage ,\ * /*TYPE* / "S" ,\ * /*OPTIONAL?* / OPTIONAL ,\ * /*MAX Nval* / 1 ,\ * /*DOC* / "Library extension mode" ,\ * /*Parameter* / &extend_mode ,\ * /*Def 1* / "very_fast_triplet" ,\ * /*Def 2* / "" ,\ * /*Min_value* / "any" ,\ * /*Max Value* / "any" \ * ); * \endcode * * \param argc number of argments * \param argv list * * \param para_name param * \param set_flag Set to 1 if param set * \param para_type F, I, S, R_FN (read_file, name), W_FN (written file, name), R_FP (pointer) * \param max_n_val maximum number of values * \param optional 1 for yes, 0 for no * \param usage usage list with optional value * \param val pointer to the varaible holding the value(s) * \param default1 default value (if value id not there) * \param default2 default value if the flag is there but no value set ("")indicates an error * \param range_left min value ( "any" for any) * \param range_right max_value ( "any" for any); */ int get_cl_param (int argc, char **argv, FILE **fp,const char para_name_in[], int *set_flag,const char type_in[], int optional, int max_n_val,const char usage_in[], ...) { int pos=0; int a; va_list ap; int *int_val=NULL; float *float_val=NULL; char **string_val=NULL; char *range_right; char *range_left; char *default_value1; char *default_value2; int n_para=0; double max, min; static char **parameter_list; static int number_of_parameters; char **para_name_list; int n_para_name; char **para_val; int n_para_val; char **pv_l=NULL; int n_pv_l; char **pv_r=NULL; int n_pv_r; char value[STRING]; /*CHECK THAT ALL THE PARAM IN ARG EXIST*/ if ( para_name_in==NULL) { for ( a=1; a< argc; a++) { if ( is_parameter ( argv[a])) { if (strstr (argv[a], "help"))myexit (EXIT_SUCCESS); else if ( name_is_in_list ( argv[a], parameter_list, number_of_parameters, STRING)==-1) { myexit(fprintf_error ( stderr, "\n%s IS NOT A PARAMETER OF %s [FATAL/%s %s]\n",argv[a], argv[0], argv[0], VERSION)); } } } free_char (parameter_list,-1); return 0; } char para_name[strlen(para_name_in)+1]; char type[strlen(type_in)+1]; char usage[strlen(usage_in)+1]; strcpy(para_name, para_name_in); strcpy(type, type_in); strcpy(usage, usage_in); if ( parameter_list==NULL)parameter_list=declare_char(MAX_N_PARAM,STRING); para_name_list=get_list_of_tokens(para_name,NULL, &n_para_name); for ( a=0; a< n_para_name; a++) { sprintf ( parameter_list[number_of_parameters++],"%s", para_name_list[a]); } free_char(para_name_list,-1); set_flag[0]=0; va_start (ap, usage); if (strm3 (type, "S","R_F","W_F")) string_val=va_arg(ap, char**); else if (strm2 (type, "D","FL")) int_val=va_arg(ap, int*); else if (strm (type, "F")) float_val=va_arg(ap, float*); else myexit (EXIT_FAILURE); default_value1=va_arg(ap, char*); default_value2=va_arg(ap, char*); range_left =va_arg(ap, char*); range_right =va_arg(ap, char*); va_end(ap); para_name_list=get_list_of_tokens(para_name, NULL, &n_para_name); for ( a=0; a=max_n_val) { n_para=max_n_val-1; } if ( !(strm ( argv[a], "NULL"))) { if ( strm3(type, "S", "R_F", "W_F")) { sprintf ( string_val[n_para],"%s", argv[a]); } else if (strm (type, "D")) { int_val[n_para]=atoi(argv[a]); } else if (strm ( type,"F")) { float_val[n_para]=atof(argv[a]); } } n_para++; } } if ( n_para==0 && !strm2(default_value2,"","NULL") && !strm(type, "FL")) { para_val=get_list_of_tokens(default_value2, NULL, &n_para_val); for ( n_para=0; n_paramax) { myexit(fprintf_error ( stderr, "\n%s out of range [%d %d] [FATAL/%s]\n", para_name, (int)min, (int)max,argv[0])); } } else { sprintf ( value, "%d", int_val[a]); if ( name_is_in_list(value, pv_l, n_pv_l, STRING)==-1) fprintf ( stderr, "\n%s out of range [%s: ", para_name, value); print_array_char (stderr, pv_l, n_pv_l, " "); fprintf ( stderr, "\n"); myexit(EXIT_FAILURE); } } else if ( strm (type, "F")) { if ( n_pv_l==1) { min=(double)atof(range_left); max=(double)atof(range_right); if ( float_val[a]max) { myexit(fprintf_error ( stderr, "\n%s out of range [%f %f] [FATAL/%s]\n", para_name, (float)min, (float)max,argv[0])); } } else { sprintf ( value, "%f", float_val[a]); if ( name_is_in_list(value, pv_l, n_pv_l, STRING)==-1) fprintf ( stderr, "\n%s out of range [%s: ", para_name, value); print_array_char (stderr, pv_l, n_pv_l, " "); fprintf ( stderr, "\n"); } } } if ( fp[0]!=NULL) { fprintf (fp[0], "%-15s\t%s\t[%d] ", para_name, type, set_flag[0]); for (a=0; a=buf_len) {buf_len+=100;buf=(char*)vrealloc (buf, buf_len*sizeof (char));} buf[l++]=c; } /*Add the cariage return*/ if ( c=='\n') { if (l>=buf_len){buf_len+=100,buf=(char*)vrealloc (buf, buf_len*sizeof (char));} buf[l++]='\n'; } /*add the terminator*/ if (l>=buf_len){buf_len+=100,buf=(char*)vrealloc (buf, buf_len*sizeof (char));} buf[l]='\0'; if ( bufin!=buf && bufin!=NULL && debug==1) fprintf ( stderr, "\nPointer change in vfgets..."); return buf; } FILE * find_token_in_file ( char *fname, FILE * fp, char *token) { int c; static char *name; int token_len; int only_start; /*Note: Token: any string If Token[0]=='\n' Then Token only from the beginning of the line */ if (!fp && !file_exists("CACHE",fname))return NULL; if ( token[0]=='\n'){token++;only_start=1;} else only_start=0; token_len=strlen (token); if (!fp) { if (name)vfree (name); name = (char*)vcalloc (((fname)?measure_longest_line_in_file (fname):10000)+1, sizeof (char)); fp=vfopen ( fname, "r"); } while ( (fscanf ( fp, "%s", name))!=EOF) { if ( name[0]=='*')while ( ((c=fgetc (fp))!='\n')&& (c!=EOF)); else if (strncmp ( name, token,token_len)==0){return fp;} else if (only_start) while ( ((c=fgetc (fp))!='\n')&& (c!=EOF)); } vfclose ( fp); return NULL; } // FILE * find_token_at_line_start ( char *fname, FILE * fp, char *token) // { // static char *name; // int token_len; // // int only_start; // const int LINE_LENGTH=1000; // char line[LINE_LENGTH]; // // // /*Note: Token: any string // If Token[0]=='\n' Then Token only from the beginning of the line // */ // // if (!fp && !file_exists("CACHE",fname))return NULL; // // if ( token[0]=='\n') // { // ++token; // only_start=1; // } // else // only_start=0; // // token_len=strlen (token); // if (!fp) // { // if (name)vfree (name); // name = vcalloc (((fname)?measure_longest_line_in_file (fname):10000)+1, sizeof (char)); // fp=vfopen ( fname, "r"); // } // // line[LINE_LENGTH-2]='\0'; // while (fgets(line, LINE_LENGTH, fp)!=NULL) // { // if ((line[LINE_LENGTH-2]!='\0') && (line[LINE_LENGTH-2]!='\n')) // line[LINE_LENGTH-2]='\0'; // else // { // if (!strncmp(line,token,token_len)) // return fp; // } // } // // // vfclose ( fp); // return NULL; // } // FILE * find_token_in_file ( char *fname, FILE * fp, char *token) // { // int c; // static char *name; // int token_len; // // int only_start; // // /*Note: Token: any string // If Token[0]=='\n' Then Token only from the beginning of the line // */ // // if (!fp && !file_exists("CACHE",fname)) // return NULL; // // // if ( token[0]=='\n') // return find_token_at_line_start (fname, fp, ++token); // else // only_start=0; // // token_len=strlen (token); // // // // if (!fp) // { // if (name)vfree (name); // name = vcalloc (((fname)?measure_longest_line_in_file (fname):10000)+1, sizeof (char)); // fp=vfopen ( fname, "r"); // } // // while ( (fscanf ( fp, "%s", name))!=EOF) // { // // if ( name[0]=='*') // while ( ((c=fgetc (fp))!='\n')&& (c!=EOF)); // else if (strncmp ( name, token,token_len)==0) // {return fp;} // } // // vfclose ( fp); // return NULL; // } int **get_file_block_pattern (char *fname, int *n_blocks, int max_n_line) { int c; FILE *fp; char *line; int lline; int **l; int in_block; int max_block_size; int block_size; int x; int n_line; lline=measure_longest_line_in_file (fname)+1; line=(char*)vcalloc ( sizeof (char),lline+1); fp=vfopen (fname, "r"); max_block_size=block_size=0; in_block=1; n_blocks[0]=0; n_line=0; while ((c=fgetc(fp))!=EOF && (n_line max_block_size)myexit(fprintf_error ( stderr, "\nERROR %d", l[n_blocks[0]][0])); l[n_blocks[0]] [l[n_blocks[0]][0]]=x; } else { in_block=0; } } n_blocks[0]++; vfree(line); vfclose (fp); return l; } char * strip_file_from_comments (char *com, char *in_file) { /*Removes in file in_file every portion of line to the right of one of the symbols included in com Writes the striped file into a vtmpnam file */ FILE *fp1; FILE *fp2; char *out_file; int c; out_file=vtmpnam(NULL); fp1=vfopen (in_file , "r"); fp2=vfopen (out_file, "w"); while ( (c=fgetc(fp1))!=EOF) { if (strchr(com, c)) { while ( (c=fgetc(fp1))!='\n' && c!=EOF); } else { fprintf (fp2, "%c", c); while ( (c=fgetc(fp1))!='\n' && c!=EOF)fprintf (fp2, "%c", c); if ( c!=EOF)fprintf (fp2, "%c", c); } } vfclose (fp1); vfclose (fp2); return out_file; } FILE * skip_commentary_line_in_file ( char com, FILE *fp) { int c=0; if ( fp==NULL)return NULL; while ((c=fgetc(fp))==com) { while ((c=fgetc(fp))!='\n' && c!=EOF); } if ( c!=EOF && c!='\n')ungetc(c, fp); return fp; } int check_for_update ( char *web_address) { char command[1000]; char *file; float new_version, old_version; FILE *fp; check_internet_connection (IS_NOT_FATAL); file=vtmpnam(NULL); sprintf ( command, "%s/%s.version",DISTRIBUTION_ADDRESS, PROGRAM); url2file ( command, file); fp=vfopen ( file, "r"); fscanf ( fp, "Version_%f", &new_version); vfclose ( fp); sscanf ( VERSION, "Version_%f", &old_version); if ( old_version new_version) { fprintf ( stdout, "\nUpdate Status: beta-release"); fprintf ( stdout, "\nYour are using a beta-release of %s(%s)\n", PROGRAM, VERSION); } else { fprintf (stdout, "\nUpdate Status: uptodate"); fprintf (stdout, "\nProgram %s(%s) is up to date\n", PROGRAM, VERSION); } return EXIT_SUCCESS; } int check_environement_variable_is_set ( char *variable, char *description, int fatal) { if ( getenv (variable)==NULL) { myexit(fprintf_error ( stderr, "\nERROR: You must set %s\n%s %s", variable, description, description)); if ( fatal==IS_FATAL) { myexit(fprintf_error ( stderr, "\n[%s:FATAL]\n", PROGRAM)); } else add_warning ( stderr, "\n[%s:WARNING]\n", PROGRAM); } return 1; } int url2file (char *address, char *out) { if (check_program_is_installed ("wget",NULL, NULL,WGET_ADDRESS, IS_NOT_FATAL)) printf_system( "wget \'%s\' -O%s >/dev/null 2>/dev/null", address, out); else if (check_program_is_installed ("curl",NULL, NULL,CURL_ADDRESS, IS_NOT_FATAL)) printf_system("curl \'%s\' -o%s >/dev/null 2>/dev/null", address, out); else { printf_exit (EXIT_FAILURE, stderr, "ERROR: Impossible to fectch external file: Neither wget nor curl is installed on your system [FATAL:%s]\n", PROGRAM); return EXIT_FAILURE; } if (check_file_exists (out) && file2size(out)>0)return 1; else return 0; } int wget (char *address, char *out) { return printf_system ( "wget %s -O%s >/dev/null 2>/dev/null", address, out); } int curl (char *address, char *out) { return printf_system ( "curl %s -o%s >/dev/null 2>/dev/null", address, out); } int simple_check_internet_connection (char *ref_site) { char *test; int n, internet=0; test=vtmpnam (NULL); if (url2file( const_cast( (ref_site)?ref_site:TEST_WWWSITE_4_TCOFFEE),test )!=EXIT_SUCCESS)internet=0; //Maria added this to cast a const char* to char* else if ((n=count_n_char_in_file(test))<10)internet=0; else internet =1; return internet; } int check_internet_connection (int mode) { int internet; internet=simple_check_internet_connection (NULL); if (internet)return 1; else if ( mode==IS_NOT_FATAL)return internet; else proxy_msg(stderr); myexit (EXIT_FAILURE); } char *pg2path (char *pg) { char *buf; char *dir; char *p1,*p; if (!pg || !(p1=getenv ("PATH")))return NULL; p=(char*)vcalloc ( strlen (p1)+strlen (pg) +1, sizeof (char)); buf=(char*)vcalloc( strlen (p1)+strlen (pg) +1, sizeof (char)); sprintf ( p, "%s", p1); dir=strtok (p, ":"); while( dir) { sprintf ( buf, "%s/%s", dir,pg); if ( file_exists (NULL,buf)) { vfree (p); return resize_string(buf); } sprintf ( buf, "%s/%s.exe", dir,pg); if (file_exists (NULL, buf)) { vfree (p); return resize_string(buf); } dir=strtok(NULL, ":"); } return NULL; } int check_program_is_installed ( char *program_name, char *path_variable, char *path_variable_name, char *where2getit, int fatal) { static char *path; int install_4_tcoffee=0; if (atoigetenv("INSTALL_4_TCOFFEE"))install_4_tcoffee=1; if ( strm (where2getit, "built_in"))return 1; if (path)vfree (path); if ( check_file_exists (path_variable)) { return 1; } else { path=pg2path (program_name); if (path && path[0])return 1; else { int install=EXIT_FAILURE; if ((fatal==INSTALL || fatal==INSTALL_OR_DIE) && install_4_tcoffee) { HERE ("************** %s is missing from your system. T-Coffee will make an attempt to install it.\n", program_name); install=printf_system ("install.pl %s -plugins=%s -clean", program_name, get_plugins_4_tcoffee()); } if ( install==EXIT_SUCCESS)return 1; else if ( fatal==INSTALL)return 0; else if ( fatal==NO_REPORT)return 0; if (fatal==IS_FATAL || fatal==INSTALL_OR_DIE)check_configuration4program(); fprintf ( stderr, "\n#*****************************************************************"); if (fatal) fprintf_error ( stderr, "\n#ERROR [FATAL:%s]", PROGRAM); else fprintf ( stderr, "\n#WARNING [%s]", PROGRAM); fprintf ( stderr, "\n# The Program %s Needed by %s Could not be found", program_name, PROGRAM); fprintf ( stderr, "\n# If %s is installed on your system:", program_name); fprintf ( stderr, "\n#\t -Make sure %s is in your $path:",program_name); fprintf ( stderr, "\n# If %s is NOT installed obtain a copy from:", program_name); fprintf ( stderr, "\n#\t%s\n#\n#",where2getit); fprintf ( stderr, "\n# and install it manualy"); fprintf ( stderr, "\n******************************************************************\n"); } } if ( fatal==IS_FATAL || fatal==INSTALL_OR_DIE) myexit (EXIT_FAILURE); return 0; } FILE * display_output_filename ( FILE *io, char *type, char *format, char *name, int check_output) { static char ***buf; static int nbuf; char *f; if ( strm ( name, "stdout") || strm (name, "stderr"))return io; if ( check_output==STORE) { int a; if ( buf==NULL)buf=(char***)vcalloc ( 1000, sizeof (char**)); for (a=0; a\n"); fprintf (out,"output\n"); fprintf (out,"%s\n", type); fprintf (out, "%s\n", format); fprintf (out, "%s\n", name); fprintf (out, "\n"); if ((fp=fopen (name, "r"))!=NULL) { while ((c=fgetc (fp))!=EOF){fprintf(out, "%c",c);} fclose (fp); } fprintf (out,"\n\n"); fclose (out); } } } return io; } FILE * display_input_filename ( FILE *io, char *type, char *format, char *name, int check_output) { if ( check_output==CHECK && check_file_exists(name)==NULL) { fprintf ( io, "\n\tIIII INPUT File Type= %10s Format= %10s Name= %s | NOT PRODUCED [WARNING:%s:%s]\n",type, format, name, PROGRAM, VERSION ); return io; } fprintf ( io, "\n\t#### File Type= %10s Format= %10s Name= %s",type, format, name ); return io; } int file_is_empty (char *fname) { struct stat s; if (!fname) return 1; stat (fname, &s); if (s.st_size)return 0; else return 1; } int file_exists (char *path, char *fname) { struct stat s; char file[1000]; if (!fname)return 0; else if (path && strm (path, "CACHE")) { if (file_exists (NULL, fname))return 1; else return file_exists (get_cache_dir(), fname); } else if (path) sprintf ( file, "%s/%s", path, fname); else if (!path)sprintf (file, "%s", fname); if (stat(file,& s)!=-1) return S_ISREG(s.st_mode); else return 0; } int isdir (char *file) { struct stat s; if (stat (file,&s)!=-1) return S_ISDIR(s.st_mode); else return 0; } int rrmdir (char *s) { if (isdir(s))return printf_system_direct ("rm -r %s", s); return EXIT_FAILURE; } int isexec (char *file) { char *state; state=ls_l(NULL,file); if (state[0]==0) return 0; if ( state[0]=='d') return 0; if ( state[3]=='x') return 1; if ( state[6]=='x') return 1; if ( state[9]=='x') return 1; return 0; } char *ls_l ( char *path,char *file) { char *tmpfile; static char *state; FILE *fp; int a; tmpfile=vtmpnam (NULL); if (!state) { state=(char*)vcalloc (100, sizeof (char)); } for (a=0;a<100; a++)state[a]=0; if (!file || !file_exists (path, file))return state; printf_system_direct ("ls -l %s%s%s >%s 2>/dev/null",(path!=NULL)?path:"", (path!=NULL)?"/":"",file, tmpfile); fp=vfopen (tmpfile, "r"); if (!fscanf ( fp, "%s", state)) { vfclose(fp); return 0; } vfclose (fp); return state; } int my_rmdir ( char *dir_in) { int dir_sep='/'; int a, buf; char *dir; if (atoigetenv ("NO_RMDIR_4_TCOFFEE")==1)return 1; dir=(char*)vcalloc ( strlen (dir_in)+strlen (get_home_4_tcoffee())+100, sizeof (char)); sprintf ( dir, "%s", dir_in); tild_substitute ( dir, "~",get_home_4_tcoffee()); if (access(dir, F_OK)==-1); else { if ( strstr (dir, "coffee"))printf_system_direct ( "rm -rf %s", dir); else myexit(fprintf_error ( stderr, "\nERROR: directory %s does not contain 'coffee' [FATAL:%s]", dir, PROGRAM)); } vfree (dir); return 1; } int my_mkdir ( char *dir_in) { int dir_sep='/'; int a, buf; char *dir; dir=(char*)vcalloc ( strlen (dir_in)+strlen (get_home_4_tcoffee())+100, sizeof (char)); sprintf ( dir, "%s", dir_in); tild_substitute ( dir, "~",get_home_4_tcoffee()); a=0; while (dir[a]!='\0') { if ( dir[a]==dir_sep || dir[a+1]=='\0') { buf= dir[a+1]; dir[a+1]='\0'; if (access(dir, F_OK)==-1) { mode_t oldmask = umask(0); mkdir (dir, S_IRWXU | S_IRWXG | S_IRWXO); umask(oldmask); if ( access (dir, F_OK)==-1) { myexit(fprintf_error ( stderr, "\nERROR: Could Not Create Directory %s [FATAL:%s]", dir, PROGRAM)); } } dir[a+1]=buf; } a++; } vfree (dir); return 1; } int filename_is_special (char *fname) { if ( strm5 (fname, "default", "stdin", "stdout","stderr", "/dev/null"))return 1; if ( strm3 (fname, "STDIN", "STDOUT", "STDERR"))return 1; return 0; } char* check_url_exists ( char *fname_in) { static char ***lu; static int n; int a; char *tmp; if (!fname_in)return NULL; for (a=0; a0)sprintf (lu[n][1], "%s", tmp); else{vfree (lu[n][1]); lu[n][1]=NULL;} return lu[n++][1]; } char* check_file_exists ( char *fname_in) { static char *fname1; static char *fname2; if (!fname_in)return NULL; if (!fname_in[0])return NULL; if (fname_in[0]=='-')return NULL; if (strstr (fname_in, "tp://"))return check_url_exists(fname_in); if (!fname1){fname1=(char*)vcalloc (1000, sizeof (char));} if (!fname2){fname2=(char*)vcalloc (1000, sizeof (char));} sprintf ( fname1, "%s", fname_in);tild_substitute (fname1, "~", get_home_4_tcoffee()); sprintf ( fname2, "%s%s", get_cache_dir(),fname1); if ( filename_is_special (fname1))return fname1; if ( strm5 (fname1, "no", "NO", "No", "NO_FILE","no_file"))return NULL/*fname1*/; if (!file_exists( NULL,fname1)) { if (!file_exists (NULL,fname2))return NULL; else return fname2; } else return fname1; return NULL; } void create_file ( char *name) { FILE *fp; fp=fopen (name, "w"); fclose (fp); } void delete_file ( char *fname) { FILE * fp; fp=fopen ( fname, "w"); fprintf ( fp, "x"); fclose ( fp); printf_system_direct ("rm %s", fname); } int util_rename ( char *from, char *to) { FILE *fp_from; FILE *fp_to; int c; if ( !check_file_exists (from))return 0; else if ( check_file_exists (to) && !vremove (to) && !rename ( from, to)==0 ); else { fp_from=vfopen ( from, "r"); fp_to=vfopen ( to, "w"); while ( (c=fgetc (fp_from))!=EOF)fprintf ( fp_to, "%c", c); fclose (fp_from); fclose ( fp_to); vremove ( from); return 1; } return 0; } int util_copy ( char *from, char *to) { FILE *fp_from; FILE *fp_to; int c; if (!check_file_exists (from))return 0; else { fp_from=vfopen ( from, "r"); fp_to=vfopen ( to, "w"); while ( (c=fgetc (fp_from))!=EOF)fprintf ( fp_to, "%c", c); fclose (fp_from); fclose ( fp_to); return 1; } return 0; } FILE * output_completion4halfmat ( FILE *fp,int n, int tot, int n_reports, char *s) { int max, left, achieved; int up; if (n>=0)up=1; else up=-1; max=((tot*tot)-tot)/2; left=((tot-n)*(tot-n)-(tot-n))/2; achieved=max-left; if (up==1); else { int b; b=achieved; achieved=left; left=b; } return output_completion (fp,achieved, max, n_reports, s); } FILE * output_completion ( FILE *fp,int n, int tot, int n_reports, char *string) { static int ref_val; static int flag; static int ref_time; int t, elapsed; n++; if ( n==1) { ref_val=flag=0; ref_time=get_time()/1000; } t=get_time()/1000; elapsed=t-ref_time; if ( !ref_val && !flag) { fprintf (fp, "\n!\t\t[%s][TOT=%5d][%3d %%][ ELAPSED TIME: %4d sec.]",(string)?string:"",tot,(tot==1)?100:0, elapsed); flag=1; } else if ( n>=tot)fprintf (fp, "\r!\t\t[%s][TOT=%5d][%3d %%][ ELAPSED TIME: %4d sec.]\n",(string)?string:"", tot,100, elapsed); else if ( ((n*100)/tot)>ref_val) { ref_val=((n*100)/tot); t=(ref_val==0)?0:elapsed/ref_val; t=t*(100-ref_val); t=0; elapsed=((float)100-(float)ref_val)*((float)elapsed/(float)ref_val); fprintf (fp, "\r!\t\t[%s][TOT=%5d][%3d %%][REMAINING TIME: %4d sec.]", (string)?string:"",tot,ref_val, elapsed); flag=0; } return fp; } void * null_function (int a,...) { myexit(fprintf_error ( stderr, "\n[ERROR] Attempt to use the Null Function [FATAL:%s]", PROGRAM)); return NULL; } int btoi ( int nc,...) { va_list ap; int a, b; va_start (ap, nc); for ( a=0, b=0; a< nc; a++) { b+=pow(2,a)*va_arg (ap,int); } va_end(ap); return b; } /*********************************************************************/ /* */ /* Geometric FUNCTIONS */ /* */ /* */ /*********************************************************************/ float get_geometric_distance ( float ** matrix, int ncoor, int d1, int d2, char *mode) { float d; float t=0; int a; if ( strm (mode, "euclidian")) { for ( a=0; a< ncoor; a++) { d=(matrix[d1][a]-matrix[d2][a]); t+=d*d; } return (float)sqrt((double)t); } return 0; } /*********************************************************************/ /* */ /* MATHEMATICAL FUNCTIONS */ /* */ /* */ /*********************************************************************/ static double EXP_UNDERFLOW_THRESHOLD = -4.60f; static double LOG_UNDERFLOW_THRESHOLD = 7.50f; static double LOG_ZERO = -FLT_MAX; static double LOG_ONE = 0.0f; double log_addN (int N, double*L) { double v; int a; if (N==0)return 0; if ( N==1)return L[0]; v=L[0]; for ( a=1; a= LOG_UNDERFLOW_THRESHOLD)) ? y : log (exp (x-y) + 1) + x; else x = (y == LOG_ZERO || ((x - y) >= LOG_UNDERFLOW_THRESHOLD)) ? x : log (exp (x-y) + 1) + y; return x; } float M_chooses_Nlog ( int m, int N) { /*Choose M elemets in N*/ float z1, z2,z=0; if ( m==N) return 0; else if ( m>N) { myexit(fprintf_error ( stderr, "\nERROR: M chosses N out of bounds ( M>N) [FATAL:%s]", PROGRAM)); myexit (EXIT_FAILURE); } else { z1=factorial_log (m+1, N); z2=factorial_log (1, N-m); z=z1-z2; return z; } return -1; } float factorial_log ( int start, int end) { if ( end==0)return 0; else if ( end==start) return (float)my_int_log((double)start); else if ( start>end) { fprintf_error ( stderr, "\nERROR: factorial log out of bounds (%d %d) [FATAL:%s]",start, end, PROGRAM); myexit (EXIT_FAILURE); } else { int a=0; float x=0; for ( x=0,a=start; a<=end; a++) { x+=(float)my_int_log(a); } return x; } return 0; } float my_int_log(int a) { if ( a>=100000)return log(a); else { static float *lu; if (!lu) lu=(float*)vcalloc ( 100000, sizeof (float)); if ( !lu[a]){lu[a]=log(a);} return lu[a]; } return 0; } double factorial (int start, int end); double M_chooses_N ( int m, int N) { /*Choose M elemets in N*/ if ( m==N) return 1; else if ( m>N) { fprintf_error ( stderr, "\nERROR: M chosses N out of bounds ( M>N) [FATAL:%s]", PROGRAM); myexit (EXIT_FAILURE); } else if ( N<50) { return factorial (m+1, N)/factorial (1, N-m); } else { fprintf_error ( stderr, "\nERROR: M chosses N out of bounds ( N>50). Use log space [FATAL:%s]", PROGRAM); myexit (EXIT_FAILURE); } return -1; } double factorial (int start, int end) { if ( start>end || start<0 || end<0) { fprintf_error ( stderr, "\nERROR: Negative Factorial [FATAL:%s]", PROGRAM); myexit ( EXIT_FAILURE); } else if (end==0) return 1; else if (end==start) return end; else { static double **lu; if ( !lu)lu=declare_double (100, 100); if ( lu[start][end])return lu[start][end]; else { int a; lu[start][end]=(double)start; for ( a=start+1; a<=end; a++) { lu[start][end]*=(double)a; } return lu[start][end]; } } return -1; } /*********************************************************************/ /* */ /* Fast Log Additions (adapted from Probcons)*/ /* */ /* */ /*********************************************************************/ double EXP (double x){ //return exp(x); if (x > -2){ if (x > -0.5){ if (x > 0) return exp(x); return (((0.03254409303190190000*x + 0.16280432765779600000)*x + 0.49929760485974900000)*x + 0.99995149601363700000)*x + 0.99999925508501600000; } if (x > -1) return (((0.01973899026052090000*x + 0.13822379685007000000)*x + 0.48056651562365000000)*x + 0.99326940370383500000)*x + 0.99906756856399500000; return (((0.00940528203591384000*x + 0.09414963667859410000)*x + 0.40825793595877300000)*x + 0.93933625499130400000)*x + 0.98369508190545300000; } if (x > -8){ if (x > -4) return (((0.00217245711583303000*x + 0.03484829428350620000)*x + 0.22118199801337800000)*x + 0.67049462206469500000)*x + 0.83556950223398500000; return (((0.00012398771025456900*x + 0.00349155785951272000)*x + 0.03727721426017900000)*x + 0.17974997741536900000)*x + 0.33249299994217400000; } if (x > -16) return (((0.00000051741713416603*x + 0.00002721456879608080)*x + 0.00053418601865636800)*x + 0.00464101989351936000)*x + 0.01507447981459420000; return 0; } float LOOKUP (float x){ if (x <= 1.00f) return ((-0.009350833524763f * x + 0.130659527668286f) * x + 0.498799810682272f) * x + 0.693203116424741f; if (x <= 2.50f) return ((-0.014532321752540f * x + 0.139942324101744f) * x + 0.495635523139337f) * x + 0.692140569840976f; if (x <= 4.50f) return ((-0.004605031767994f * x + 0.063427417320019f) * x + 0.695956496475118f) * x + 0.514272634594009f; return ((-0.000458661602210f * x + 0.009695946122598f) * x + 0.930734667215156f) * x + 0.168037164329057f; } void LOG_PLUS_EQUALS (float *x, float y){ if (x[0] < y) x[0] = (x[0] == LOG_ZERO || y - x[0] >= LOG_UNDERFLOW_THRESHOLD) ? y : LOOKUP(y-x[0]) + x[0]; else x[0] = (y == LOG_ZERO || x[0] - y >= LOG_UNDERFLOW_THRESHOLD) ? x[0] : LOOKUP(x[0]-y) + y; } float LOG_ADD (float x, float y){ if (x < y) return (x == LOG_ZERO || y - x >= LOG_UNDERFLOW_THRESHOLD) ? y : LOOKUP((y-x)) + x; return (y == LOG_ZERO || x - y >= LOG_UNDERFLOW_THRESHOLD) ? x : LOOKUP((x-y)) + y; } float LOG_ADD3 (float x1, float x2, float x3){ return LOG_ADD (x1, LOG_ADD (x2, x3)); } float LOG_ADD4 (float x1, float x2, float x3, float x4){ return LOG_ADD (x1, LOG_ADD (x2, LOG_ADD (x3, x4))); } float LOG_ADD5 (float x1, float x2, float x3, float x4, float x5){ return LOG_ADD (x1, LOG_ADD (x2, LOG_ADD (x3, LOG_ADD (x4, x5)))); } float LOG_ADD6 (float x1, float x2, float x3, float x4, float x5, float x6){ return LOG_ADD (x1, LOG_ADD (x2, LOG_ADD (x3, LOG_ADD (x4, LOG_ADD (x5, x6))))); } float LOG_ADD7 (float x1, float x2, float x3, float x4, float x5, float x6, float x7){ return LOG_ADD (x1, LOG_ADD (x2, LOG_ADD (x3, LOG_ADD (x4, LOG_ADD (x5, LOG_ADD (x6, x7)))))); } #define LONG_SIZE 2 #define SHORT_SIZE 1 #define SPACE_PAD 4 #define STD_SIZE 0 char *strscn(char *s, char *pattern); long unsigned strtou(char *s, int base, char **scan_end); long int strtoi(char *s, int base, char **scan_end); int my_isnumber(char c, int base); int tonumber(char c); int my_vsscanf(char *buf, char *fmt, va_list parms) { int scanned = 0, size = 0, suppress = 0; int w = 0, flag = 0, l = 0; char c, *c_ptr; long int n1, *n1l; int *n1b; short int *n1s; long unsigned n2, *n2l, parsing = 0; unsigned *n2b; short unsigned *n2s; double n3, *n3l; float *n3s; char *base = buf; while (*fmt != 0) { if (*fmt != '%' && !parsing) { /* No token detected */ fmt++; } else { /* We need to make a conversion */ if (*fmt == '%') { fmt++; parsing = 1; size = STD_SIZE; suppress = 0; w = 0; flag = 0; l = 0; } /* Parse token */ switch (*fmt) { case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '0': if (parsing == 1) { w = strtou(fmt, 10, &base); /* We use SPACE_PAD to parse %10s * commands where the number is the * maximum number of char to store! */ flag |= SPACE_PAD; fmt = base - 1; } break; case 'c': c = *buf++; c_ptr = va_arg(parms, char *); *c_ptr = c; scanned++; parsing = 0; break; case 's': c_ptr = va_arg(parms, char *); while (*buf != 0 && isspace(*buf)) buf++; l = 0; while (*buf != 0 && !isspace(*buf)) { if (!(flag & SPACE_PAD)) *c_ptr++ = *buf; else if (l < w) { *c_ptr++ = *buf; l++; } buf++; } *c_ptr = 0; scanned++; parsing = 0; break; case 'i': case 'd': buf = strscn(buf, "1234567890-+"); n1 = strtoi(buf, 10, &base); buf = base; if (!suppress) { switch (size) { case STD_SIZE: n1b = va_arg(parms, int *); *n1b = (int) n1; break; case LONG_SIZE: n1l = va_arg(parms, long int *); *n1l = n1; break; case SHORT_SIZE: n1s = va_arg(parms, short int *); *n1s = (short) (n1); break; } scanned++; } parsing = 0; break; case 'u': buf = strscn(buf, "1234567890"); n2 = strtou(buf, 10, &base); buf = base; if (!suppress) { switch (size) { case STD_SIZE: n2b = va_arg(parms, unsigned *); *n2b = (unsigned) n2; break; case LONG_SIZE: n2l = va_arg(parms, long unsigned *); *n2l = n2; break; case SHORT_SIZE: n2s = va_arg(parms, short unsigned *); *n2s = (short) (n2); break; } scanned++; } parsing = 0; break; case 'x': buf = strscn(buf, "1234567890xabcdefABCDEF"); n2 = strtou(buf, 16, &base); buf = base; if (!suppress) { switch (size) { case STD_SIZE: n2b = va_arg(parms, unsigned *); *n2b = (unsigned) n2; break; case LONG_SIZE: n2l = va_arg(parms, long unsigned *); *n2l = n2; break; case SHORT_SIZE: n2s = va_arg(parms, short unsigned *); *n2s = (short) (n2); break; } scanned++; } parsing = 0; break; case 'f': case 'g': case 'e': buf = strscn(buf, "1234567890.e+-"); n3 = strtod(buf, &base); buf = base; if (!suppress) { switch (size) { case STD_SIZE: n3l = va_arg(parms, double *); *n3l = n3; break; case LONG_SIZE: n3l = va_arg(parms, double *); *n3l = n3; break; case SHORT_SIZE: n3s = va_arg(parms, float *); *n3s = (float) (n3); break; } scanned++; } parsing = 0; break; case 'l': size = LONG_SIZE; break; case 'h': case 'n': size = SHORT_SIZE; break; case '*': suppress = 1; break; default: parsing = 0; break; } fmt++; } } return (scanned); } char *strscn(char *s, char *pattern) { char *scan; while (*s != 0) { scan = pattern; while (*scan != 0) { if (*s == *scan) return (s); else scan++; } s++; } return (NULL); } long unsigned strtou(char *s, int base, char **scan_end) { int value, overflow = 0; long unsigned result = 0, oldresult; /* Skip trailing zeros */ while (*s == '0') s++; if (*s == 'x' && base == 16) { s++; while (*s == '0') s++; } /* Convert number */ while (my_isnumber(*s, base)) { value = tonumber(*s++); if (value > base || value < 0) return (0); oldresult = result; result *= base; result += value; /* Detect overflow */ if (oldresult > result) overflow = 1; } if (scan_end != 0L) *scan_end = s; if (overflow) result = INT_MAX; return (result); } long int strtoi(char *s, int base, char **scan_end) { int sign, value, overflow = 0; long int result = 0, oldresult; /* Evaluate sign */ if (*s == '-') { sign = -1; s++; } else if (*s == '+') { sign = 1; s++; } else sign = 1; /* Skip trailing zeros */ while (*s == '0') s++; /* Convert number */ while (my_isnumber(*s, base)) { value = tonumber(*s++); if (value > base || value < 0) return (0); oldresult = result; result *= base; result += value; /* Detect overflow */ if (oldresult > result) overflow = 1; } if (scan_end != 0L) *scan_end = s; if (overflow) result = INT_MAX; result *= sign; return (result); } int my_isnumber(char c, int base) { static char *digits = "0123456789ABCDEF"; if ((c >= '0' && c <= digits[base - 1])) return (1); else return (0); } int tonumber(char c) { if (c >= '0' && c <= '9') return (c - '0'); else if (c >= 'A' && c <= 'F') return (c - 'A' + 10); else if (c >= 'a' && c <= 'f') return (c - 'a' + 10); else return (c); } /////////////////////////////////////////////////////////////////////////////////////////// // Hash function //////////////////////////////////////////////////////////////////////////////////////////// unsigned long hash_file(char* file) //returns the hash value for key { // Calculate a hash value by the division method: // Transform key into a natural number k = sum ( key[i]*128^(L-i) ) and calculate i= k % num_slots. // Since calculating k would lead to an overflow, i is calculated iteratively // and at each iteration the part divisible by num_slots is subtracted, i.e. (% num_slots is taken). unsigned long i=0; // Start of iteration: k is zero unsigned long num_slots=999999999; FILE *fp; unsigned long c; if (file==NULL || !check_file_exists (file) ) {printf("Warning from util.c:hasch_file: No File [FATAL:%s]\n", PROGRAM); myexit (EXIT_FAILURE);} num_slots/=128; fp=vfopen (file, "r"); while ( (c=fgetc (fp))!=EOF) { i = ((i<<7) + c) % num_slots; } vfclose (fp); return i; } int ** r_generate_array_int_list ( int len, int min, int max,int step, int **array, int f, int *n,FILE *fp, int *c_array); int **generate_array_int_list (int len, int min, int max, int step, int *n, char *file) { int **array, *c_array; FILE *fp=NULL; if (n==NULL) { array=NULL; fp=vfopen (file, "w"); } else { int a,s; n[0]=0; for (s=1, a=0; a %d -- %s %s (%s)\n", getpid(), getppid(), getpid(), PROGRAM, VERSION, BUILD_INFO); lock (getpid(), LERROR, LSET, "%d -- COM: %s\n",getpid(),in_cl ); // } if (is_rootpid()) { kill_child_pid(getpid()); if (has_error_lock()) { char *e=NULL; stack_msg (stderr); warning_msg (stderr); e=lock (getpid(), LERROR, LREAD, NULL); //explicit the most common error messages if ( strstr (e, "EMAIL"))email_msg (stderr); if ( strstr (e, "INTERNET"))proxy_msg (stderr); if ( strstr (e, "PG")) install_msg(stderr); if ( strstr (e, "COREDUMP")) { error_msg (stderr); dump_error_file(); } print_exit_failure_message (); vfree (e); } else if ( has_warning_lock()) { warning_msg (stderr); } else print_exit_success_message(); if ( (f=get_string_variable ("dump"))) { dump_tcoffee (f, "standard dump"); //unset_string_variable ("dump"); //unset_string_variable ("dump_output_file"); //display_output_filename (stdout, "DUMP", "DUMP_4_TCOFFEE",f, CHECK); } lock (getpid(), LLOCK, LRELEASE, ""); lock (getpid(), LWARNING, LRELEASE, ""); lock (getpid(), LERROR, LRELEASE, ""); add_method_output2method_log (NULL, NULL, NULL, NULL, decode_name (NULL, CODELIST)); } //Remove all temporary files debug=(atoigetenv ("DEBUG_TMP_FILE")); while ( start && start->name) { if (!debug) { if (isdir(start->name))rrmdir (start->name); else { char test[1000]; vremove (start->name); if (start->name)sprintf (test, "%s.dnd", start->name);vremove (test); if (start->name)sprintf (test, "%s.html",start->name);vremove (test); } } else { if (isdir(start->name)) {fprintf ( stderr, "DEBUG_TMP_FILE SET : Dir %s not removed (%d)\n", start->name, getpid());} else {fprintf ( stderr, "DEBUG_TMP_FILE SET : File %s not removed (%d)\n", start->name, getpid());} } b=start; start=start->next; //vfree(b->name);vfree(b); } if (!debug && is_rootpid())my_rmdir (get_tmp_4_tcoffee()); //Remove the lock //lock (getpid(), LLOCK, LRELEASE,NULL); Now keep the lock unless it is a parent process //UNIQUE TERMINATION FOR EVERYBODY!!!!!! return; } int cputenv4path (char *p) { if (!p)return 0; else if (isdir4path (p)) { cputenv ("PATH=%s:%s", p, getenv("PATH")); return 1; } else { return 0; } } int string_putenv ( char *s) { //extract from command line all the occurences -setenv val1 val2 and sets environement char *p; int n; char *v1, *v2; if (!s) return 0; v1=(char*)vcalloc ( strlen (s)+1, sizeof (char)); v2=(char*)vcalloc ( strlen (s)+1, sizeof (char)); p=s; n=0; while ( (p=strstr (p, "-setenv"))) { if (sscanf (p, "-setenv %s %s", v1,v2)==2) { if (strm (v1, "PATH"))cputenv4path (v2); else cputenv ( "%s=%s", v1, v2); } p+=strlen ("-setenv"); n++; } p=s; if ( (p=strstr (p, "-plugins"))) { sscanf (p, "-plugins %s", v1); cputenv ("PROXY_4_TCOFFEE=%s",v1); cputenv4path (v1); } p=s; if ( (p=strstr (p, "-email"))) { sscanf (p, "-email %s", v1); cputenv ("EMAIL_4_TCOFFEE=%s", v1); } p=s; if ( (p=strstr (p, "-proxy"))) { sscanf (p, "-proxy %s", v1); cputenv ("PROXY_4_TCOFFEE=%s", v1); } vfree (v1); vfree (v2); return n; } char* file_putenv (char *file) { //puts in environement all the variables conatinned in file //format VAR=value on each line char ***list; int n=0; if (!file || !file_exists(NULL,file)) return NULL; list=file2list (file, "\n="); fprintf ( stderr, "Import Environement Variables from %s\n", file); while (list[n]) { if ( list[n][1][0]!='#') { if ( strm (list[n][1], "PATH")) { cputenv ( "PATH=%s:%s",list[n][2], getenv ("PATH")); fprintf ( stderr, "\tPATH=%s:$PATH", list[n][2]); } else { cputenv("%s=%s", list[n][1],list[n][2]); fprintf ( stderr, "\t%s=%s", list[n][1],list[n][2]); } n++; } } free_arrayN ((void ***)list, 3); return NULL; } char * bachup_env (char *mode,char *f) { static char *file; static char *buf; if (!file) { file=vtmpnam (NULL); buf=(char*)vcalloc ( 10000, sizeof (char)); } if (!f)f=file; if (strm (mode, "DUMP")) { printf_system_direct ("/usr/bin/env > %s", f); return EXIT_SUCCESS; } else if ( strm (mode,"RESTAURE") && file_exists (NULL,f)) { file_putenv (f); return EXIT_SUCCESS; } return NULL; } /////////////////////////////////////////////////////////////////////////////// // // // // // Kmeans // /////////////////////////////////////////////////////////////////////////////// void km_output_data ( double **data, int n, int dim, int len, char *infile, char *outfile); int km_main (int argc, char *argv[]); int km_main (int argc, char *argv[]) { double **data, **sdata; int dim, len, n; int a, b; int k=2; char *infile=NULL; char *outfile=NULL; double t=0.0001; int mode=1; int scan=0; char **field_list; int nf=0; field_list=(char**)calloc (1000, sizeof (char*)); srand(time(NULL)); for (a=1; a -i -o -f -f \n", argv[a]); } } km_file2dim (infile,&n, &dim, &len); data=km_read_data(infile, n, dim, len,field_list); if ( k<0) { k*=-1; mode=(mode<=1)?10:mode; for (a=2; amlen)?clen:mlen; } len[0]=mlen+10; vfclose (fp); n[0]=0; fp=vfopen (file, "r"); buf=(char*)calloc(len[0]+1, sizeof (char)); while ((fgets (buf,len[0], fp))) { if ( buf[0]=='#') { n[0]++; cdim=0; strtok(buf, ";");//pass #d; strtok(NULL, ";"); //pass exp; strtok(NULL, ";"); //pass recid; while ((s1=strtok(NULL, ";"))) { s2=strtok(NULL, ";"); if (strstr (s1, "value::")) { cdim++; } } mdim=(cdim>mdim)?cdim:mdim; } } free (buf); n[0]; dim[0]=mdim; vfclose (fp); return n[0]; } double ** km_read_data ( char *file, int n, int dim, int mlen, char **fl) { FILE *fp; double **data; char *buf; char *s1; char *s2; int cdim,cn; int a,b,c,p; int *fi; fi=(int*)calloc (1000,sizeof (int)); for (a=0; a<1000; a++)fi[a]=-1; buf =(char*)calloc (mlen+1,sizeof (char)); data=(double**)calloc (n+1, sizeof (double*)); for (a=0; a 0; c[i][j] = data[h][j]); } /**** ** main loop */ do { /* save error from last step */ old_error = error, error = 0; /* clear old counts and temp centroids */ for (i = 0; i < k; counts[i++] = 0) { for (j = 0; j < m; c1[i][j++] = 0); } for (h = 0; h < n; h++) { /* identify the closest cluster */ double min_distance = DBL_MAX; for (i = 0; i < k; i++) { double distance = 0; for (j = m; j-- > 0; distance += pow(data[h][j] - c[i][j], 2)); if (distance < min_distance) { data[h][m+1]=i; min_distance = distance; } } /* update size and temp centroid of the destination cluster */ for (j = m; j-- > 0; c1[(int)data[h][m+1]][j] += data[h][j]); counts[(int)data[h][m+1]]++; /* update standard error */ error += min_distance; } for (i = 0; i < k; i++) { /* update all centroids */ for (j = 0; j < m; j++) { c[i][j] = counts[i] ? c1[i][j] / counts[i] : c1[i][j]; } } } while (fabs(error - old_error) > t); /**** ** housekeeping */ for (i = 0; i < k; i++) { if (!centroids) { free(c[i]); } free(c1[i]); } if (!centroids) { free(c); } free(c1); free(counts); return 1; } int km_kmeans_new(double **data, int n, int m, int k, double t, double **centroids) { /* output cluster label for each data point */ int a; int h, i, j; /* loop counters, of course :) */ int *counts = (int*)calloc(k, sizeof(int)); /* size of each cluster */ double old_error, error = DBL_MAX; /* sum of squared euclidean distance */ double **c = centroids ? centroids : (double**)calloc(k, sizeof(double*)); double **c1 = (double**)calloc(k, sizeof(double*)); /* temp centroids */ //data must be allocated as data[n][m+2] for (a=0; a 0; c[i][j] = data[h][j]); // } // // reserve space; for (i = 0; i < k; ++i) { c1[i] = (double*)calloc(m, sizeof(double)); if (!centroids) { c[i] = (double*)calloc(m, sizeof(double)); } } int index = (int)((double)rand() / RAND_MAX * n); for (j=0; ++j 0; distance += pow(data[h][j] - c[i][j], 2)); if (distance < min_distance) { data[h][m+1]=i; min_distance = distance; } } /* update size and temp centroid of the destination cluster */ for (j = m; j-- > 0; c1[(int)data[h][m+1]][j] += data[h][j]); counts[(int)data[h][m+1]]++; /* update standard error */ error += min_distance; } for (i = 0; i < k; i++) { /* update all centroids */ for (j = 0; j < m; j++) { c[i][j] = counts[i] ? c1[i][j] / counts[i] : c1[i][j]; } } } while (fabs(error - old_error) > t); /**** ** housekeeping */ for (i = 0; i < k; i++) { if (!centroids) { free(c[i]); } free(c1[i]); } if (!centroids) { free(c); } free(c1); free(counts); return 1; } double km_kmeans_bs (double **data, int n, int dim, int k,double t, double **centroids, int nrounds) { double **R; double **S; double score=0; double cscore=0; int **B; int BR; double tot=100; int a, b,c; int p1, p2; srand(time(NULL)); B=declare_int (nrounds, 2); R=declare_double(n, nrounds); S=(double**)vcalloc ( n, sizeof (double*)); for (a=0; a