
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <sys/stat.h>

#include "util.h"

/*
 * Generate a random double in the range [0..range).
 */
double randDouble(int range) {
	return (range * drand48());
}

/*
 * Removes any whitespace or newlines from the end of the given string.
 * The given string must be null-terminated.
 */
void trim(char *string) {
	int i;
	int len = strlen(string);
	
	for (i = len - 1; i >= 0; i--) {
		if (isspace(string[i])) {
			string[i] = '\0';
		}
		else {
			return;
		}
	}
}


/*
 * Given a filename path, this function parses the name of the file
 * without the enclosing directory. filename must point to a char[]
 * with enough memory to hold the short filename plus null
 * terminator.
 */
void get_filename_from_path(char *path, char *filename) {
	char *filename_start;
	
	filename_start = strrchr(path, (int) '/'); // Find last '/' character.
	
	if (filename_start != NULL) {
		strcpy(filename, &filename_start[1]);
	}
	else {
		strcpy(filename, path);
	}
	
}


/*
 * Given a filename path, this function parses the name of the file
 * without the enclosing directory and without the suffix ".pdb" or
 * ".pdbH" if it exists. e.g. from this path:
 *
 *    files/ribosomal_protein_L30e/1w41.pdb
 *
 * pdb_name should be set to "1w41". pdb_name must point to a char[]
 * with enough memory to hold the short filename plus suffix plus null
 * terminator.
 */
void get_PDB_name_from_path(char *path, char *pdb_name) {
	char *suffix_start;
	
	get_filename_from_path(path, pdb_name);
	
	suffix_start = strrchr(pdb_name, (int) '.'); // Find last '.' character.
	if (suffix_start != NULL &&
			(strncmp(suffix_start, ".pdb", 4) == 0 || strncmp(suffix_start, ".pdbH", 5) == 0)) {
		suffix_start[0] = '\0';
	}
}


/*
 * Checks whether the file with the given filename exists and is readable. If not,
 * an error message is printed and the program exits.
 */
void check_file_readability(char *filename) {
	
	FILE *test_fp;
	struct stat buf;
	
	// Check if file exists.
	if (stat(filename, &buf) != 0) {
		perror(filename);
		exit(-1);
	}
	
	// Check if the file is readable.
	test_fp = fopen(filename,"r");
	if (test_fp) {
		fclose(test_fp);
	}
	else {
		fprintf(stderr, "Error: Could not read file %s.\n", filename);
		exit(-1);
	}
	
}
