#include <limits.h>
/* calculate the length of a string */
int strlen(const char* str) {
	int len = 0;
	while(*str++) len++;
	return len;
}

/* 
    reverse a string from element left to element right
    eg: "how are you" => "uoy era woh"
*/
void reverse(char* str, int left, int right) {
	int i, len;
	char temp;
	len = (right + 1 - left) / 2;
	for (i = 0; i < len; ++i) {
		temp = str[left + i];
		str[left + i] = str[right - i];
		str[right - i] = temp;
	}
}

/* 
    reverse order of words in a string
    eg: "how are you" => "you are how"
*/
void reverse_words(char* str) {
	int len, i, word_start = 0;
	len = strlen(str);
	/* first reverse the whole sentence */
	reverse(str, 0, len - 1);
	for( i = 0; i < len; i++) {
		/* when a space is encountered, reverse the word */
		if (str[i] == ' ') {
			reverse(str, word_start, i - 1);
			word_start = i + 1;
		/* when i == len - 1, end of sentence */
		} else if ( i == len - 1) {
			reverse(str, word_start, i);
		}
	}
}

/* 
    convert a string of integer representation to an integer
    eg: "1234" => 1234
*/
int atoi(const char* str) {
	char c;
	int sign = 1, result = 0;
	const int max = INT_MAX / 10;

	/* sign */
	if (*str == '-') {
		sign = -1;
		str++;
	}
	while((c = *str++)) {
		/* overflow check*/
		if (result >= max) {
			printf("Integer overflow!\n");
			return 0;
		}
		/* digit left shift */
		result *= 10;
		/* add current digit*/
		result += c - '0';
	}
	return result * sign;
}