Restructure and rework the code
[whatever.git] / parse.cpp
blob4c100574c58d4065d843875d2e13a8c0f957791a
1 #include"parse.h"
2 using namespace std;
4 int number_from_pos(string form, int& index)
6 if (index < 0 || index >= form.length())
8 return 0;
10 int res = 0;
11 while (isdigit(form.at(index)))
13 res *= 10;
14 res += (form[index] - '0');
15 if (++index >= form.length())
17 break;
20 return res;
23 vector<int> parse_from_pos(string form, vector<element> e, int& index)
25 int i = index;
26 vector<int> result;
27 vector<int> tmpres;
28 result.resize(e.size());
29 tmpres.resize(e.size());
30 if (i >= form.size())
32 cerr << "Index greater than size of formula!" << endl;
34 else if (i < 0)
36 cerr << "Index is negative!" << endl;
38 while (i < form.size())
40 char c = form[i];
41 if (c == '(')
43 i++;
44 tmpres = parse_from_pos(form, e, i);
45 // i now points at the first character *AFTER* closing parenthesis
46 if (i < form.size() && isdigit(form[i]))
48 int multiply = number_from_pos(form, i);
49 mulv(tmpres, multiply);
52 else if (c == ')')
54 i++;
55 break;
57 else if (isalpha(c))
59 string z;
60 while (i < form.size() && isalpha(c = form[i++]))
62 z.push_back(c);
63 int fi;
64 if ((fi = find_symbol(e, z)) != -1)
66 bool flag = false;
67 flag |= (i >= form.size());
68 if (i < form.size())
70 flag |= !islower(form[i]);
72 if (flag)
74 tmpres[fi]++;
75 break;
79 if (isdigit(form[i]))
81 int multiply = number_from_pos(form, i);
82 mulv(tmpres, multiply);
85 addv(result, tmpres);
86 tmpres.clear();
87 tmpres.resize(e.size());
89 index = i;
90 return result;
93 void parse(string form, vector<element> e, vector<int>& result)
95 int _i = 0;
96 result = parse_from_pos(form, e, _i);
97 if (_i != form.length())
99 cerr << "Final index is NOT the length of formula string." << endl;
101 return;