libStatGen Software  1
StringAlias.cpp
1 /*
2  * Copyright (C) 2010 Regents of the University of Michigan
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program. If not, see <http://www.gnu.org/licenses/>.
16  */
17 
18 #include "StringAlias.h"
19 #include "InputFile.h"
20 
21 void StringAlias::SetAlias(String & string, String & alias)
22 {
23  int index = lookup.Integer(string);
24 
25  if (index < 0)
26  {
27  aliases.Push(alias);
28  lookup.SetInteger(string, aliases.Length() - 1);
29  }
30  else
31  aliases[index] = alias;
32 }
33 
34 const String & StringAlias::GetAlias(const String & string) const
35 {
36  int index = lookup.Integer(string);
37 
38  if (index < 0)
39  return string;
40  else
41  return aliases[index];
42 }
43 
44 
45 int StringAlias::GetAliases(StringArray & list) const
46 {
47  if(lookup.Entries() == 0)
48  {
49  return 0;
50  }
51 
52  int edits = 0;
53  for(int i = 0; i < list.Length(); i++)
54  {
55  int index = lookup.Integer(list[i]);
56  if(index >= 0)
57  {
58  list[i] = aliases[index];
59  edits++;
60  }
61  }
62  return edits;
63 }
64 
65 
66 bool StringAlias::ReadFromFile(const char * filename)
67 {
68  IFILE input = ifopen(filename, "rt");
69 
70  if (input == NULL)
71  return false;
72 
73  ReadFromFile(input);
74 
75  ifclose(input);
76 
77  return true;
78 }
79 
80 bool StringAlias::ReadFromFile(IFILE & input)
81 {
82  StringArray lines, tokens;
83  lines.Read(input);
84 
85  for (int j = 0; j < lines.Length(); j++)
86  {
87  tokens.ReplaceTokens(lines[j]);
88 
89  if (tokens.Length() != 2) continue;
90 
91  SetAlias(tokens[0], tokens[1]);
92  }
93 
94  return true;
95 }
String
Definition: StringBasics.h:39
ifopen
IFILE ifopen(const char *filename, const char *mode, InputFile::ifileCompression compressionMode=InputFile::DEFAULT)
Open a file with the specified name and mode, using a filename of "-" to indicate stdin/stdout.
Definition: InputFile.h:562
InputFile.h
InputFile
Class for easily reading/writing files without having to worry about file type (uncompressed,...
Definition: InputFile.h:37
ifclose
int ifclose(IFILE &file)
Close the file.
Definition: InputFile.h:580
StringArray
Definition: StringArray.h:24