Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void merge(char *merge, char *shortest, char* longest);
void getMaxOverlap(char **array, int *size);
int compare(char *shortest, char *longest, int *bestOffset);
void getFragments(FILE *fp, char **array, int *arraySize);
void updateArray(char **array, int **size, int one, int two, char *mergedString);
int main (int argc, const char * argv[]) {
FILE *fp = fopen(argv[1], "r");
if(fp==NULL) {
printf("Invalid file. Try again.\n");
return -1;
}
char *array[10000];
int arraySize = 0;
getFragments(fp, array, &arraySize);
while(arraySize>1) {
printf("array size: %d\n", arraySize);
getMaxOverlap(array, &arraySize);
}
printf("FINAL PARAGRAPH: \n%s\n", array[0]);
return 0;
}
void getFragments(FILE *fp, char **array, int *arraySize) {
char frag[1000];
fscanf(fp, "%*[#]"); // gets rid of original # for first fragment
while(fscanf(fp,"%999[^#]%*[#]", frag) == 1) {
array[*arraySize] = (char*) malloc(sizeof(char)*strlen(frag));
strcpy(array[*arraySize], frag);
*arraySize += 1;
}
}
void getMaxOverlap(char **array, int *size) {
int maxOverlap = 0;
int bestI, bestJ;
// omitted calculation of bestI, bestJ, maxOverlap
char *merged;
merge(merged, array[bestI], array[bestJ]);
updateArray(array, &size, bestI, bestJ, merged);
}
int compare(char* one, char* two, int *bestOffset) {
int comparison = 0;
// omitted calculation of comparison
return comparison;
}
void merge(char *merge, char *shortest, char *longest) {
int offset = 0;
int overlap = compare(shortest, longest, &offset);
int diff = strlen(longest)-strlen(shortest);
char *mergedString;
if(offset<0) {
mergedString = (char*)malloc(sizeof(char)*((-offset)+strlen(longest)));
} else {
mergedString = (char*)malloc(sizeof(char)*(strlen(longest)+(offset-diff)));
}
if(offset<0) {
strcpy(mergedString,shortest);
char end[1000];
int count;
for(count = 0; count < strlen(longest)-overlap; count++) {
end[count] = longest[count+overlap];
}
strcat(mergedString, end);
} else {
strcpy(mergedString,longest);
if(offset>diff) {
char end[1000];
int count;
for(count = 0; count < strlen(shortest)-overlap; count++) {
end[count] = shortest[count+overlap];
}
strcat(mergedString, end);
}
}
strcpy(merge, mergedString);
}
void updateArray(char **array, int **size, int one, int two, char *mergedString) {
if(one>two) {
int temp = one;
one = two;
two = temp;
}
array[one] = (char*)realloc(array[one],sizeof(char)*strlen(mergedString));
array[two] = (char*)realloc(array[two],sizeof(char)*strlen(array[**size-1]));
strcpy(array[one], mergedString);
strcpy(array[two], array[**size-1]);
free(mergedString); // <-- I think this is where the free should go
**size-=1;
}