diff --git a/main-random-seq.c b/main-random-seq.c index f8037fc..266ceb6 100644 --- a/main-random-seq.c +++ b/main-random-seq.c @@ -7,7 +7,7 @@ int main(int argc, char **argv) { uint i, n, *pairs, *useq; - char *vienna; + char *vienna, *str; if (argc != 2 && argc != 3) { printf("ERROR: wrong number of arguments\n" @@ -18,6 +18,7 @@ int main(int argc, char **argv) n = strlen(vienna); pairs = xmalloc(n * sizeof(*pairs)); useq = xmalloc(n * sizeof(*useq)); + str = xmalloc((n + 1) * sizeof(*str)); if (argc == 3) { random_seed(atoi(argv[2])); @@ -27,11 +28,10 @@ int main(int argc, char **argv) xvienna_to_pairs(n, vienna, pairs); random_useq(n, pairs, useq); - /* TODO: move this to useq_to_str function */ - for (i = 0; i < n; i++) - printf("%c", NA_BASE_NAMES[useq[i]]); - printf("\n"); + xuseq_to_str(n, useq, str); + printf("%s\n", str); + free(str); free(pairs); free(useq); return EXIT_SUCCESS; diff --git a/na.c b/na.c index b369e90..80fdcfd 100644 --- a/na.c +++ b/na.c @@ -244,6 +244,37 @@ xstr_to_pseq(uint n, uint ndim, const char *str, double **p) } } +/* translate from uint sequence representation to string, exiting on + errors */ +void +xuseq_to_str(uint n, const uint *useq, char *str) +{ + bool verbose = true; + int retcode = useq_to_str(n, useq, verbose, str); + if (retcode != EXIT_SUCCESS) { + exit(EXIT_FAILURE); + } +} + +/* translate from uint sequence representation to string, return + EXIT_SUCCESS on success */ +int +useq_to_str(uint n, const uint *useq, bool verbose, char *str) +{ + uint i; + str[n] = '\0'; + for (i = 0; i < n; i++) { + if (useq[i] >= NA_NBASES) { + if (verbose) { + printf("ERROR: illegal base at position %u, base id = %u\n", i, useq[i]); + } + return EXIT_FAILURE; + } + str[i] = NA_BASE_NAMES[useq[i]]; + } + return EXIT_SUCCESS; +} + void nn_multiloop_xalloc(struct nn_multiloop *ml, uint nstems, uint ndangle5, uint ndangle3) diff --git a/na.h b/na.h index 24b9ebe..8bd8814 100644 --- a/na.h +++ b/na.h @@ -68,6 +68,8 @@ char * xpairs_to_vienna(uint n, const uint *pairs, char *vienna); void xstr_to_useq(uint n, const char *str, uint *useq); void xstr_to_pseq(uint n, uint ndim, const char *str, double **p); void pseq_to_str(double **p, uint n, uint ndim, char *str); +void xuseq_to_str(uint n, const uint *useq, char *str); +int useq_to_str(uint n, const uint *useq, bool verbose, char *str); struct nn_inter * nn_inter_xnew(uint n); void nn_inter_delete(struct nn_inter *inter);