00001
00002 #ifndef ARG_PARSER_HH
00003 #define ARG_PARSER_HH
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030 #include "bool.hh"
00031
00032 #include <cstdlib>
00033 #include <cstring>
00034 #include <iostream>
00035 using std::ostream;
00036 using std::cout;
00037 using std::cerr;
00038 using std::endl;
00039
00040 class arg_parser {
00041
00074 friend ostream &operator<<(ostream &, arg_parser &);
00075
00076 public:
00077 enum arg_type {BOOLEAN, INTEGER, STRING, STRING_LIST};
00078
00079 struct arg_record {
00080 const char *arg_text;
00081 const char *arg_help;
00082 void *data;
00083 arg_type type;
00084 };
00085
00086 arg_parser( arg_record *record_ptr, void (*init_help_func)() ){
00087 get_arg_array(record_ptr);
00088 help_func = init_help_func;
00089 }
00090
00091 ~arg_parser() {}
00092
00095 void check_args(int &, char **, bool = true );
00096
00097 void print_usage( char *binary_name );
00098
00099 private:
00100 arg_record *array_of_arg_records;
00101 int num_args;
00102 void (*help_func)();
00103
00106 void remove_arg( int arg_to_remove, int &argc, char **argv);
00107
00111 void check_remaining( int argc, char **argv,
00112 bool complain_and_exit_on_error);
00113
00114 void get_arg_array(arg_record[]);
00115
00116 };
00117
00118 inline
00119 ostream &operator<<(ostream &os, arg_parser &ap){
00120 const int num_spaces = 3;
00121 const unsigned int indentation = 2;
00122
00123
00124 int i = 0;
00125 unsigned int maxlen = 0;
00126 while( ap.array_of_arg_records[i].arg_text != NULL ){
00127 if( strlen(ap.array_of_arg_records[i].arg_text) > maxlen ){
00128 maxlen = strlen(ap.array_of_arg_records[i].arg_text);
00129 }
00130 i++;
00131 }
00132
00133
00134 unsigned int j;
00135 i = 0;
00136 while( ap.array_of_arg_records[i].arg_text != NULL ){
00137
00138
00139 for( j = 0; j < indentation; j++ ){
00140 os << " ";
00141 }
00142
00143
00144 os << ap.array_of_arg_records[i].arg_text;
00145
00146
00147
00148 for( j = 0; j < maxlen - strlen( ap.array_of_arg_records[i].arg_text )
00149 + num_spaces ; j++ ){
00150 os << " ";
00151 }
00152
00153
00154 os << ap.array_of_arg_records[i].arg_help << endl;
00155 i++;
00156 }
00157
00158 for( j = 0; j < indentation; j++ ){
00159 os << " ";
00160 }
00161
00162 os << "--help";
00163 for( j = 0; j < maxlen - strlen("--help") + num_spaces ; j++ ){
00164 os << " ";
00165 }
00166 os << "print this message" << endl;
00167
00168 return os;
00169 }
00170
00171 #endif