/*
 * calculator_v2.c
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>


int calculator(char * s, float * result)
{
    float first_operand, second_operand;
    char *operation_position;
    char tmp[30];
    int i;

    operation_position = strchr(s, '+');
    if (operation_position == NULL) operation_position = strchr(s, '-');
    if (operation_position == NULL) operation_position = strchr(s, '*');
    if (operation_position == NULL) operation_position = strchr(s, '/');
    if (operation_position == NULL) return 1; // no valid operation symbol found!

    // from 's' to 'operation_position'-1 there is the first operand
    // now copy from s to operation_position into a temporary string
    // and convert it into float
    i = 0;
    while (s != operation_position) {
        tmp[i] = *s;
        ++s;
        ++i;
    }
    // add end of string character
    tmp[i] = 0;
    // now convert it to float
    first_operand = atof(tmp);

    // from 'operation_position'+1 to the end of the string, there is the second operand
    // now convert it to float
    second_operand = atof(operation_position + 1);

    // do the operation
    switch (*operation_position) {
    case '+': *result = first_operand + second_operand; break;
    case '-': *result = first_operand - second_operand; break;
    case '*': *result = first_operand * second_operand; break;
    case '/': *result = first_operand / second_operand; break;
    }

    return 0;

}


void main()
{
    float result;
    char * s;

    s = "1.34 +   6.2";
    printf("Computing '%s' = ", s);
    if (calculator(s, &result) == 1)
        printf("SYNTAX ERROR\n");
    else
        printf("%f\n", result);

    s = "   1.34+6.2   ";
    printf("Computing '%s' = ", s);
    if (calculator(s, &result) == 1)
        printf("SYNTAX ERROR\n");
    else
        printf("%f\n", result);

    s = "1   1.34+6.2   ";
    printf("Computing '%s' = ", s);
    if (calculator(s, &result) == 1)
        printf("SYNTAX ERROR\n");
    else
        printf("%f\n", result);

    s = "10*5";
    printf("Computing '%s' = ", s);
    if (calculator(s, &result) == 1)
        printf("SYNTAX ERROR\n");
    else
        printf("%f\n", result);

}

