Add a unit-manager object to track units
[gcalctool.git] / src / gcalccmd.c
blob5fb2d4524feb1575aee1614d5ef0bb6ba9890e2a
1 /* $Header$
3 * Copyright (c) 2009 Rich Burridge
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2, or (at your option)
8 * any later version.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
18 * 02111-1307, USA.
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/types.h>
25 #include <time.h>
26 #include <locale.h>
28 #include "mp-equation.h"
29 #include "mp-serializer.h"
31 #define MAXLINE 1024
33 static MpSerializer *result_serializer;
35 static void
36 solve(const char *equation)
38 int ret;
39 MPEquationOptions options;
40 MPNumber z;
41 gchar *result_str = NULL;
43 memset(&options, 0, sizeof(options));
44 options.base = 10;
45 options.wordlen = 32;
46 options.angle_units = MP_DEGREES;
48 ret = mp_equation_parse(equation, &options, &z, NULL);
50 if (ret == PARSER_ERR_MP)
51 fprintf(stderr, "Error %s\n", mp_get_error());
52 else if (ret)
53 fprintf(stderr, "Error %d\n", ret);
54 else {
55 result_str = mp_serializer_to_string(result_serializer, &z);
56 printf("%s\n", result_str);
58 g_free(result_str);
62 /* Adjust user input equation string before solving it. */
63 static void
64 str_adjust(char *str)
66 int i, j = 0;
68 str[strlen(str)-1] = '\0'; /* Remove newline at end of string. */
69 for (i = 0; str[i] != '\0'; i++) { /* Remove whitespace. */
70 if (str[i] != ' ' && str[i] != '\t')
71 str[j++] = str[i];
73 str[j] = '\0';
74 if (j > 0 && str[j-1] == '=') /* Remove trailing '=' (if present). */
75 str[j-1] = '\0';
78 int
79 main(int argc, char **argv)
81 char *equation, *line;
82 size_t nbytes = MAXLINE;
84 /* Seed random number generator. */
85 srand48((long) time((time_t *) 0));
87 g_type_init ();
88 setlocale(LC_ALL, "");
90 result_serializer = mp_serializer_new(MP_DISPLAY_FORMAT_AUTOMATIC, 10, 9);
92 equation = (char *) malloc(MAXLINE * sizeof(char));
93 while (1) {
94 printf("> ");
95 line = fgets(equation, nbytes, stdin);
97 if (line != NULL)
98 str_adjust(equation);
100 if (line == NULL || strcmp(equation, "exit") == 0 || strcmp(equation, "quit") == 0 || strlen(equation) == 0)
101 break;
103 solve(equation);
105 free(equation);
107 return 0;