File: main.cc

package info (click to toggle)
xmds 1.6.6-4
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 3,752 kB
  • ctags: 1,571
  • sloc: cpp: 35,402; sh: 7,408; ansic: 1,029; makefile: 244
file content (1003 lines) | stat: -rw-r--r-- 34,877 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
/*
  Copyright (C) 2000-2008

  Code contributed by Greg Collecutt, Joseph Hope and Paul Cochrane

  This file is part of xmds.

  This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU General Public License
  as published by the Free Software Foundation; either version 2
  of the License, or (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/

/*
  $Id: main.cc 1885 2008-03-18 15:24:56Z paultcochrane $
*/

/*!
  @mainpage Documentation for xmds

  @section intro Introduction

  xmds is the eXtensible Multi-Dimensional Simulator.

  XMDS is a code generator that integrates equations. You write them down in
  human readable form in a XML file, and it goes away and writes and
  compiles a C++ program that integrates those equations as fast as it can
  possibly be done in your architecture.

  Originally written by Greg Collecutt (and the majority of the code base is
  still due to him), however is now maintained by Joe Hope and the xmds
  development team.

  @section install Installation

  Download the source tarball from http://www.xmds.org, unpack, and run the
  configure script in the xmds directory.<br>
  (as root, to be installed into /usr/local/bin)<br>
  ./configure<br>
  (as a user, to be installed the bin/ directory in your home directory)<br>
  ./configure --with-user<br>

  For more details you can also read the INSTALL file, and even the
  hand-written documentation.
*/

/*!
  @file main.cc
  @brief The main routine and supporting routines

  More detailed explanation...
*/

// This is the main entry routine for xmds

#include <config.h>
#include <xmds_common.h>
#include <kissdom.h>
#include <xml_parser.h>
#include <xmds_simulation.h>
#include <string>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include <getopt_xmds.h>
#include "version.h"

using namespace std;

//! Escape the given string for inclusion as a string in C source.
//! e.g. escapeStringC(a\b"c) -> a\\b\"c
//! (Read the above as actual strings, not C strings.)
//! \todo Should we also escape e.g. non-printable characters?
void escapeStringC(string& s)
{
  for (size_t i = 0; i < s.length(); i++) {
    if (s[i] == '\\' || s[i] == '"') {
      // escape the character
      s.insert(i, "\\");
      // move one forward
      i++;
    }
  }
}

// *********************************************************************

//! Displays xmds usage
void display_usage() {
  cout << "\n" <<
    "This is xmds version " << VERSION <<
    " (" << REVISION << ")\n\n" <<
    "      using C compiler " << XMDS_CC;
  if (strcmp(MPICC, "")) {
    cout << " (and C compiler " << MPICC << " for parallel work)\n";
  }
  cout <<
    "\n"
    "Usage: xmds [options] infile\n"
    "Options:\n"
    "  infile:         required,  The input file\n"
    "  -h/--help:      optional,  Display this information\n"
    "  -v/--verbose:   optional,  Verbose mode\n"
    "  -n/--nocompile: optional,  "
    "Turns off automatic compilation of simulation\n"
    "  -t/--template:  optional,  "
    "Outputs an xmds template either to the terminal,\n"
    "                               or to an optionally specified file\n"
    "\n"
    "For further help, please see http://www.xmds.org\n"
    ;
}

// ********************************************************************

/*!
  @brief Routine to parse the preferences file

  @param fPrefs         The input preferences file stream
  @param cc             The string representing the C/C++ compiler
  @param cflags         The C/C++ compiler flags
  @param clibs          The libraries and library directories for the C/C++ compiler
  @param cincludes      The include files and directories for the C/C++ compiler
  @param cthreadlibs    The threading libraries for the C/C++ compiler
  @param mpicc          The C/C++ compiler for MPI (i.e. parallel) simulations
  @param mpicflags      The C/C++ compiler flags for the MPI C/C++ compiler
  @param fftwlibs       The libraries for using fftw
  @param fftw_mpi_libs  The libraries necessary for using fftw with MPI
  @param fftw3libs      The libraries for using fftw3
  @param fftw3threadlibs The libraries for using fftw3 with threads
  @param verbose        Whether or not to print verbose information
  @param debug          Whether or not to print debugging information
*/
int parsePrefs(ifstream &fPrefs,
               string &cc,
               string &cflags,
               string &clibs,
               string &cincludes,
               string &cthreadlibs,
               string &mpicc,
               string &mpicflags,
               string &fftwlibs,
               string &fftw_mpi_libs,
               string &fftw3libs,
               string &fftw3threadlibs,
               bool verbose,
               bool debug) {

  /*!
    \todo
    I've thought of a better way to do this, but first I'll just get this
    version going so that the feature is in, and then I'll go back and make
    it a bit more elegant.  The idea is to read in each line of the prefs
    file individually (into a string), and then process the line.  I'll
    need to read characters until I find an equals sign (ignoring spaces as
    I go), biff that into macroVar and then grab everything else and put
    that into macroVarValue.  I could treat the string read in (ie the line
    I'm parsing) as a stack and pop characters off it until the equals sign
    is found, putting chars into macroVar and then put the rest (without
    equals sign into macroVarValue.  Anyway, to be done...

    Also, I should make this into a function so that the code is only
    written the once!
  */

  /*!
   * \todo this routine should really be part of xmdsUtility, and therefore
   * an instance of an xmdsUtility object (or something like that), because
   * there are far too many parameters being passed into the function, and
   * they could be packaged more nicely into an object, rather than as
   * params.  Anyway, something else to do....
   */

  //! \todo replace if (debug) etc... with debug() routine.

  // grab the text
  char currentChar;
  string macroVar, macroVarValue, prefsString;
  bool commentCharFlag;
  prefsString = "";
  while (!fPrefs.eof()) {
    // now we try the next line
    macroVar = "";
    macroVarValue = "";
    commentCharFlag = 0;

    // wait until we find the equals sign
    while ((currentChar = fPrefs.get()) != '=' &&
            !fPrefs.eof() &&
            !commentCharFlag) {
      if (currentChar == ' ') {
        if (debug) { cout << "space character before '=' found\n"; }
      }
      else if (currentChar == '#') {
        if (debug) { cout << "comment character found (before '=' found)\n"; }
        commentCharFlag = 1;
        while ((currentChar = fPrefs.get()) != '\n' &&
                !fPrefs.eof()) {
          if (debug) { cout << "looping until end of line\n"; }
        }
        break;
      }
      else {
        macroVar = macroVar + currentChar;
      }
    }

    // now loop until we find the return character
    while (!commentCharFlag &&
            (currentChar = fPrefs.get()) != '\n' &&
            !fPrefs.eof()) {
      if (currentChar == '#') {
        if (debug) { cout << "comment character found\n"; }
        commentCharFlag = 1;
        while ((currentChar = fPrefs.get()) != '\n' &&
                !fPrefs.eof()) {
          if (debug) { cout << "looping until end of line\n"; }
        }
        break;
      }
      macroVarValue = macroVarValue + currentChar;
    }

    /*!
     * \todo this if-elseif sequence can be replaced by a switch-case
     * sequence if the strings are replaced by enums or something similar
     */
    // now do some assignments
    if (macroVar == "XMDS_CC") {
      cc = macroVarValue;
      if (verbose) { cout << "cc set to " + macroVarValue + "\n"; }
    }
    else if (macroVar == "XMDS_CFLAGS") {
      cflags = macroVarValue;
      if (verbose) { cout << "cflags set to " + macroVarValue + "\n"; }
    }
    else if (macroVar == "XMDS_LIBS") {
      clibs = macroVarValue;
      if (verbose) { cout << "clibs set to " + macroVarValue + "\n"; }
    }
    else if (macroVar == "XMDS_INCLUDES") {
      cincludes = macroVarValue;
      if (verbose) { cout << "cincludes set to " + macroVarValue + "\n"; }
    }
    else if (macroVar == "THREADLIBS") {
      cthreadlibs = macroVarValue;
      if (verbose) { cout << "cthreadlibs set to " + macroVarValue + "\n"; }
    }
    else if (macroVar == "MPICC") {
      mpicc = macroVarValue;
      if (verbose) { cout << "mpicc set to " + macroVarValue + "\n"; }
    }
    else if (macroVar == "MPICCFLAGS") {
      mpicflags = macroVarValue;
      if (verbose) { cout << "mpicflags set to " + macroVarValue + "\n"; }
    }
    else if (macroVar == "FFTW_LIBS") {
      fftwlibs = macroVarValue;
      if (verbose) { cout << "fftwlibs set to " + macroVarValue + "\n"; }
    }
    else if (macroVar == "FFTW3_LIBS") {
      fftw3libs = macroVarValue;
      if (verbose) { cout << "fftw3libs set to " + macroVarValue + "\n"; }
    }
    else if (macroVar == "FFTW3_THREADLIBS") {
      fftw3threadlibs = macroVarValue;
      if (verbose) { cout << "fftw3threadlibs set to " + macroVarValue + "\n"; }
    }
    else if (macroVar == "FFTW_MPI_LIBS") {
      fftw_mpi_libs = macroVarValue;
      if (verbose) { cout << "fftw_mpi_libs set to " + macroVarValue + "\n"; }
    }
  }
  return 0;
}

// ********************************************************************

//! Routine to write to either stdout or file a template simulation script
/*!
  @param outfilename The output filename to sent the template simulation script to
*/
void outputTemplate(const char* outfilename) {

  // this is the template text, at present taken directly from the
  // tutorial, tutTemplateStart.tex of the latex documentation
  // and relevant characters escaped so that they print out properly
  const string templateText =
    "<?xml version=\"1.0\"?>\n"
    "<simulation>\n"
    "  \n"
    "  <name> </name>      <!-- the name of the simulation -->\n"
    "  \n"
    "  <author> </author>  <!-- the author of the simulation -->\n"
    "  <description>\n"
    "    <!-- a description of what the simulation is supposed to do -->\n"
    "  </description>\n"
    "  \n"
    "  <!-- Global system parameters and functionality -->\n"
    "  <prop_dim> </prop_dim>    <!-- name of main propagation dim -->\n"
    "  \n"
    "  <stochastic> no </stochastic>  <!-- defaults to no -->\n"
    "  <!-- these four tags only necessary when stochastic is yes -->\n"
    "  <paths> </paths>               <!-- no. of paths -->\n"
    "  <seed> 1 2 </seed>             <!-- seeds for rand no. gen -->\n"
    "  <noises> </noises>             <!-- no. of noises -->\n"
    "  \n"
    "  <use_mpi> no </use_mpi>            <!-- defaults to no -->\n"
    "   <!-- this tag only meaninful when stochastic and mpi are yes -->\n"
    "   <MPI_Method>Scheduling</MPI_Method>  <!-- Scheduling or Uniform -->\n"
    "  <error_check> yes </error_check>   <!-- defaults to yes -->\n"
    "  <use_wisdom> yes </use_wisdom>     <!-- defaults to no -->\n"
    "  <benchmark> yes </benchmark>       <!-- defaults to no -->\n"
    "  <use_prefs> yes </use_prefs>       <!-- defaults to yes -->\n"
    "  \n"
    "  <!-- Global variables for the simulation -->\n"
    "  <globals>\n"
    "  <![CDATA[\n"
    "    \n"
    "  ]]>\n"
    "  </globals>\n"
    "  \n"
    "  <!-- Field to be integrated over -->\n"
    "  <field>\n"
    "    <name> main </name>\n"
    "    <dimensions> </dimensions> <!-- transverse dims -->\n"
    "    <lattice> </lattice>       <!-- no. of points for each dim -->\n"
    "    <domains> (, ) </domains>   <!-- domain of each dimension -->\n"
    "    <samples> </samples>       <!-- sample 1st point of dim? -->\n"
    "    \n"
    "    <vector>\n"
    "      <name> main </name>\n"
    "      <type> complex </type>           <!-- data type of vector -->\n"
    "      <components> </components>       <!-- names of components -->\n"
    "      <fourier_space> </fourier_space> <!-- defined in k-space? -->\n"
    "      <![CDATA[\n"
    "        \n"
    "      ]]>\n"
    "    </vector>\n"
    "  </field>\n"
    "  \n"
    "  <!-- The sequence of integrations to perform -->\n"
    "  <sequence>\n"
    "    <integrate>\n"
    "      <algorithm> </algorithm> <!-- ARK45EX, ARK45IP, RK4EX, RK4IP, SIEX, SIIP -->\n"
    "      <iterations> </iterations> <!-- default=3 for SI- algs -->\n"
    "      <interval> </interval>   <!-- how far in main dim? -->\n"
    "      <lattice> </lattice>     <!-- no. points in main dim -->\n"
    "      <samples> </samples> <!-- no. pts in output moment group -->\n"
    "      \n"
    "      <k_operators>\n"
    "        <constant> yes </constant>         <!-- yes/no -->\n"
    "        <operator_names> </operator_names>\n"
    "        <![CDATA[\n"
    "          \n"
    "        ]]>\n"
    "      </k_operators>\n"
    "      \n"
    "      <vectors> </vectors>     <!-- vector names -->\n"
    "      <![CDATA[\n"
    "        \n"
    "      ]]>\n"
    "    </integrate>\n"
    "  </sequence>\n"
    "  \n"
    "  <!-- The output to generate -->\n"
    "  <output format=\"ascii\" precision=\"single\">\n"
    "    <group>\n"
    "      <sampling>\n"
    "        <fourier_space> </fourier_space> <!-- sample in k-space? -->\n"
    "        <lattice> </lattice>           <!-- no. points to sample -->\n"
    "        <moments> </moments>           <!-- names of moments -->\n"
    "        <![CDATA[\n"
    "          \n"
    "        ]]>\n"
    "      </sampling>\n"
    "    </group>\n"
    "  </output>\n"
    "  \n"
    "</simulation>\n";

  // check to see if an output file was given
  if (outfilename == 0) {
    // ok, so no input file specified, we therefore spit it out to stdout
    cout << templateText;
  }
  else if (outfilename != 0) {
    // ok, we have an input file, open it, biff out the string, close it
    // btw, why am I using the old C syntax for this and not C++???
    ofstream templateFile;
    templateFile.open(outfilename);
    if (templateFile.fail()) {
      // make sure can actually open the file
      cout << "Unable to open output file: " << outfilename << "\n";
      cout << "Sending output to stdout\n\n";

      cout << templateText;
    }
    else {
      /*!
       * \todo the xmds version/copyright info is repeated too often
       * put this into a routine!
       */
      cout << "This is xmds, version " << VERSION <<
        " (" << REVISION <<")\n" <<
        "Copyright 2000-2008 Greg Collecutt, Joseph Hope "<<
        "and the xmds-devel team\n" <<
        "xmds is available from http://www.xmds.org\n\n" <<
        "Writing a template to file with filename: " << outfilename << "\n";

      // actually write the template to the file
      templateFile << templateText;

      cout << "Done!\n";
    }
    templateFile.close();
  }
}

/* ******************************************************************** */

bool debugFlag = 0;             //!< Print debugging info about xmds processes
bool xmlDebugFlag = 0;          //!< Print debugging info about xml parsing processes
vector<string> simulationText;  //!< The text of the xmds simulation script

//! The lines of the xmds script's header. Escaped for source output.
vector<string> simHeaderText;
//! The lines of the xmds script's body. Escaped for source output.
vector<string> simBodyText;
//! The lines of the xmds script's footer. Escaped for source output.
vector<string> simFooterText;

/*!
  @brief The main routine.

  @param argc The number of arguments to the program
  @param argv The "vector" of arguments to the program
*/
int main(
         int argc,
         char **argv)
{
  bool verbose = 0;
  bool compileFlag = 1;
  bool templateGenFlag = 0;
  const char* infilename = 0;

  int resp;
  while (1) {
    static struct option long_options[] =
      {
        {"help", no_argument, 0, 'h'},
        {"verbose", no_argument, 0, 'v'},
        {"debug", no_argument, 0, 'd'},
        {"nocompile", no_argument, 0, 'n'},
        {"template", optional_argument, 0, 't'},
        {"xmldebug", no_argument, 0, 'x'},
        {0, 0, 0, 0}
      };
    int option_index = 0;
    resp = getopt_xmds_long(argc, argv, "hvdnxt", long_options, &option_index);
    if (resp == -1) {
      break;
    }
    switch (resp) {
    case 'h':
      display_usage();
      return 0;
    case 'v':
      verbose = 1;
      break;
    case 'd':
      debugFlag = 1;
      break;
    case 'n':
      compileFlag = 0;
      break;
    case 't':
      templateGenFlag = 1;
      break;
    case 'x':
      xmlDebugFlag = 1;
      break;
    default:
      display_usage();
      return 0;
    }
  }

  // process non-option command line elements
  if (optind_xmds < argc) {
    int fnameCount = 0;
    while (optind_xmds < argc) {
      fnameCount++;
      if (fnameCount > 1) {
        // error, input file name already exists
        printf("Error: multiple input files not allowed\n\n");
        display_usage();
        return 0;
      }

      // assign infilename pointer to the appropriate
      // member of the argv array
      infilename = argv[optind_xmds++];
    }
  }

  // if asked to make a template, then just spit it out, either to file
  // or to stdout and then return nicely
  if (templateGenFlag) {
    /*! \todo
     * at present, we'll reuse the input file.  I intend to change this to
     * use the getopt_xmds stuff later, so will have to do that at some stage.
     */
    outputTemplate(infilename);
    return 0;
  }

  // check to see that an input file was given
  if (infilename == 0) {
    // error, no input file was specified
    cout << "Error: no input file specified!\n\n";
    display_usage();
    return 1;
  }

  if (verbose) {
    cout << "xmds: inputfile = '" << infilename << "'\n";
  }

  // create the XMLParser
  XMLParser myXMLParser;

  // now load xmds script into the DOMImplementation
  Document* theDocument=0;

  if (verbose) {
    cout << "Parsing file '" << infilename << "' ...\n";
  }

  try {
    theDocument=myXMLParser.parseFromFile(infilename);
    // now load the xmds file into memory for later use
    // I tried doing this in vanilla C++, but couldn't
    // it looks like it'll have to be in C for the most part
    FILE *fin;
    if ((fin = fopen(infilename, "r")) == NULL) {
      cerr << "Can't open the input xmds script file: " << infilename
           << "Exiting\n";
      return 1;  // and barf
    }

    // now grab the file one line at a time
    unsigned char temp;
    string tempString = "";
    while (!feof(fin)) {
      temp = fgetc(fin);
      if (temp != '\n') {
        tempString += temp;
      }
      else {
        simulationText.push_back(tempString);
        tempString = "";
      }
    }
    fclose(fin);

    if (debugFlag) {
      for (unsigned int i=0; i<simulationText.size(); i++) {
        cout << simulationText[i] << "\n";
      }
    }

    // now we need to tear the text to bits a little
    // first, grab the test up until we have a <simulation> tag
    // then, go from the back, dropping anything that isn't a > symbol,
    // keep that, and then try and get a </simulation> tag.
    // the header, (ie the <?xml version="1.0"?> (plus possibly more text)
    // and then the <simulation> tag), the body (the rest of the simulationText
    // up until the footer, which is just the </simulation> tag.
    // This ripping to bits is necessary so that we can piece together the
    // simulation script with the xsil output at the end of the simulation
    // without relying on system() calls.

    // search for the text "<simulation>"
    // barf if we get to the end of the file, and still haven't found it.
    string simulationStartTag = "<simulation>";
    string simulationEndTag = "</simulation>";

    bool foundSimStartTag = false, foundSimEndTag = false;

    // go through the text and rip out the header, body and footer
    for (unsigned int i=0; i<simulationText.size(); i++) {
      if (simulationText[i].find(simulationStartTag) != string::npos) {
        foundSimStartTag = true;
        if (verbose) {
          printf("Found the <simulation> start tag when pulling to bits!\n");
        }
      }
      if (simulationText[i].find(simulationEndTag) != string::npos) {
        foundSimEndTag = true;
        if (verbose) {
          printf("Found the </simulation> end tag when pulling to bits!\n");
        }
      }
      if (!foundSimStartTag && !foundSimEndTag) {
        simHeaderText.push_back(simulationText[i]);
        escapeStringC(simHeaderText.back());
      }
      if (foundSimStartTag && !foundSimEndTag) {
        simBodyText.push_back(simulationText[i]);
        escapeStringC(simBodyText.back());
      }
      if (foundSimStartTag && foundSimEndTag) {
        simFooterText.push_back(simulationText[i]);
        escapeStringC(simFooterText.back());
      }
    }

    // if we got to here and foundSimStart tag is still false, then barf appropriately
    if (!foundSimStartTag) {
      cerr << "Failed to find the string \"<simulation>\" within the simulation text\n";
      cerr << "Exiting\n";
      // I'm sure we should do something more intelligent here...
      //! \todo use xmdsException objects to handle exceptions/exits properly
      return 1;
    }

    if (debugFlag) {
      // have a look at the header if it exists
      cout << "-----------------------------\n";
      cout << "The simulation header follows:\n";
      for (unsigned int i=0; i<simHeaderText.size(); i++) {
        cout << simHeaderText[i] << "\n";
      }
      cout << "-----------------------------\n";
    }

    if (debugFlag) {
      // have a look at the body if it exists
      cout << "-----------------------------\n";
      cout << "The simulation body follows:\n";
      for (unsigned int i=0; i<simBodyText.size(); i++) {
        cout << simBodyText[i] << "\n";
      }
      cout << "-----------------------------\n";
    }

    if (!foundSimEndTag) {
      cerr << "Failed to find the string \"</simulation>\" within the simulation text\n";
      cerr << "Exiting\n";
      // I'm sure we should do something more intelligent here...
      //! \todo use xmdsException objects to handle exceptions/exits properly
      return 1;
    }

    if (debugFlag) {
      // have a look at the footer if it exits
      cout << "-----------------------------\n";
      cout << "The simulation footer follows:\n";
      for (unsigned int i=0; i<simFooterText.size(); i++) {
        cout << simFooterText[i] << "\n";
      }
      cout << "-----------------------------\n";
    }

  }
  catch(XMLParserException XMLRoutinesErr) {
    cerr << "Could not load Document\n" <<
      "due to the following XMLParserException:\n" <<
      XMLRoutinesErr.getError() <<
      "Exiting.\n";
    return 1;
  }

  if (*theDocument->documentElement()->nodeName() != "simulation") {
    cerr << "Error: Expecting root element in '" << infilename <<
      "' to be <simulation>\n" <<
      "Exiting.\n";
    return 1;
  }

  unsigned long xmdsBytePoint = myXMLParser.xmdsBytePoint();

  // create the xmdsSimulation
  xmdsSimulation myxmdsSimulation(infilename, verbose, strcmp(MPICC, ""));

  if (verbose) {
    cout << "Processing simulation ...\n";
  }

  // print out some info about xmds
  cout << "This is xmds, version " <<
    myxmdsSimulation.parameters()->version.c_str() <<
    " (" << REVISION << ")" << "\n";
  cout << "Copyright 2000-2008 Greg Collecutt, Joseph Hope " <<
    "and the xmds-devel team\n" <<
    "xmds is available from http://www.xmds.org\n\n";

  try {
    myxmdsSimulation.processElement(theDocument->documentElement());
  }
  catch(xmdsException xmdsExceptionErr) {
    cerr << "Error: simulation element could not be processed\n" <<
      "due to the following xmdsException:\n" <<
      xmdsExceptionErr.getError() <<
      "Exiting.\n";
    return 1;
  }

  if (verbose) {
    cout << "Writing output code ...\n";
  }

  try {
    myxmdsSimulation.makeCode(xmdsBytePoint);
  }
  catch(xmdsException xmdsExceptionErr) {
    cerr << "Error: simulation failed to write output code\n" <<
      "due to the following xmdsException:\n" <<
      xmdsExceptionErr.getError() <<
      "Exiting.\n";
    return 1;
  }

  string cc            = XMDS_CC;
  string cflags        = XMDS_CFLAGS;
  string mpicc         = MPICC;
  string mpicflags     = MPICCFLAGS;
  string cincludes     = XMDS_INCLUDES;
  string clibs         = XMDS_LIBS;
  string fftwlibs      = FFTW_LIBS;
  string fftw3libs     = FFTW3_LIBS;
  string fftw_mpi_libs = FFTW_MPI_LIBS;
  string cthreadlibs   = THREADLIBS;
  string fftw3threadlibs = FFTW3_THREADLIBS;

  // this is just some code to show what the defaults are
  if (verbose) {
    cout << "Defaults:  (from when xmds was built)\n"
         << "  cc = " << cc << "\n"
         << "  cflags = " << cflags << "\n"
         << "  mpicc = " << mpicc << "\n"
         << "  mpicflags = " << mpicflags << "\n"
         << "  cincludes = " << cincludes << "\n"
         << "  clibs = " << clibs << "\n"
         << "  fftwlibs = " << fftwlibs << "\n"
         << "  fftw3libs = " << fftw3libs << "\n"
         << "  fftw_mpi_libs = " << fftw_mpi_libs << "\n"
         << "  cthreadlibs = " << cthreadlibs << "\n"
         << "  fftw3_threadlibs = " << fftw3threadlibs << "\n";
  }

  // if the usePrefs flag is true then try to find the prefs file
  // and then try to parse it, falling back to the above values if
  // we fail
  if (myxmdsSimulation.parameters()->usePrefs) {
    if (verbose) {
      cout << "Using user-defined preferences\n";
    }
    // now try and open the file
    // first look in ~/.xmds/xmds.prefs

    // work out what the home directory is
    ifstream fIn, fPrefs;
    string findHomeString, homeStuff, homeDir, rmString;
    homeStuff = "home.stuff";
    findHomeString = "echo $HOME > " + homeStuff;
    system(findHomeString.c_str());

    fIn.open(homeStuff.c_str());
    if (fIn.fail()) {
      cerr << "Unable to determine the user's home directory\n"
           << "Exiting\n";
      return 1;
    }
    fIn >> homeDir;
    fIn.close();
    rmString = "rm " + homeStuff;
    system(rmString.c_str());

    // ~/.xmds/xmds.prefs
    string prefsFname;
    prefsFname = homeDir + "/.xmds/xmds.prefs";

    fPrefs.open(prefsFname.c_str());
    if (!fPrefs.fail()) {
      if (verbose) {
        cout << "Prefs file found: " << prefsFname.c_str() << "\n";
      }
      // ok, now try and parse the sucker...
      parsePrefs(fPrefs,
                 cc, cflags, clibs, cincludes, cthreadlibs,
                 mpicc, mpicflags,
                 fftwlibs, fftw_mpi_libs, fftw3libs, fftw3threadlibs,
                 verbose, debugFlag);

      fPrefs.close();
    }
    // if that didn't work, try the local directory
    else if (fPrefs.fail()) {
      string localDir;
      if (verbose) {
        cout << "Prefs file not found at " << prefsFname.c_str() << "\n";
        cout << "Trying in the local directory\n";
        // work out what the local directory is, and report it
        system("echo $PWD > localDir.test");
        fIn.open("localDir.test");
        if (fIn.fail()) {
          cerr << "Unable to properly determine the current directory\n"
               << "Exiting\n";
          return 1;
        }
        fIn >> localDir;
        fIn.close();
        system("rm localDir.test");
        cout << "The local directory is " << localDir.c_str() << "\n";
      }
      prefsFname = "xmds.prefs";
      ifstream fPrefs;  // need to define fPrefs again (local to this block)
      fPrefs.open(prefsFname.c_str());
      if (!fPrefs.fail()) {
        if (verbose) {
          cout << "Prefs file found in local directory: " <<
            localDir.c_str() << "\n";
        }
        // ok, now try and parse the sucker...
        parsePrefs(fPrefs,
                   cc, cflags, clibs, cincludes, cthreadlibs,
                   mpicc, mpicflags,
                   fftwlibs, fftw_mpi_libs, fftw3libs, fftw3threadlibs,
                   verbose, debugFlag);

        fPrefs.close();
      }

      // if we get to here, and things have still failed, print a warning
      // and just use the defaults
      else if (fPrefs.fail() && verbose) {
        cout << "Warning: no preferences file found.  "
             << "Using default values instead\n";
      }
    }

  }

  if (!myxmdsSimulation.parameters()->usePrefs && verbose) {
    cout << "Warning: User-defined preferences NOT being used.  " <<
      "Using defaults instead\n";
  }


  // this is just some code to show what the compilation values are after the prefs have been added
  if (verbose) {
    cout << "User defined preferences: (some will be the default values)\n"
         << "These are used by xmds to build the simulation\n"
         << "  cc = " << cc << "\n"
         << "  cflags = " << cflags << "\n"
         << "  mpicc = " << mpicc << "\n"
         << "  mpicflags = " << mpicflags << "\n"
         << "  cincludes = " << cincludes << "\n"
         << "  clibs = " << clibs << "\n"
         << "  fftwlibs = " << fftwlibs << "\n"
         << "  fftw_mpi_libs = " << fftw_mpi_libs << "\n"
         << "  fftw3libs = " << fftw3libs << "\n"
         << "  cthreadlibs = " << cthreadlibs << "\n"
         << "  fftw3threadlibs = " << fftw3threadlibs << "\n";
  }

  // now set up the system command to compile the simulation
  char command[1024];

  if (compileFlag) {
    if (myxmdsSimulation.parameters()->usempi) { //Joe mark
      if ((myxmdsSimulation.parameters()->nThreads > 1) ||
          (myxmdsSimulation.parameters()->mpiMethod == "Scheduling")) {
        cout << "compiling for MPI parallel execution with threads...\n";
        sprintf(command, "%s -D_REENTRANT -o %s %s.cc %s %s %s %s %s %s",
                mpicc.c_str(),
                myxmdsSimulation.parameters()->simulationName.c_str(),
                myxmdsSimulation.parameters()->simulationName.c_str(),
                mpicflags.c_str(),
                cincludes.c_str(),
                clibs.c_str(),
                myxmdsSimulation.parameters()->fftwVersion == 2
                  ? cthreadlibs.c_str() : fftw3threadlibs.c_str(),
                myxmdsSimulation.parameters()->fftwVersion == 2
                  ? fftw_mpi_libs.c_str() : fftw3libs.c_str(),
                myxmdsSimulation.parameters()->useIntelMKL ? "-lguide -lvml" : "");
        cout << "        " << command << "\n";
        if (system(command)) {
          cout << "compilation failed.\n";
          return 1;
        }
      }
      else if (!(myxmdsSimulation.parameters()->stochastic)) {
        cout << "compiling for MPI parallel execution for a "
          "nondeterministic simulation...\n";
        sprintf(command, "%s -o %s %s.cc %s %s %s %s %s",
                mpicc.c_str(),
                myxmdsSimulation.parameters()->simulationName.c_str(),
                myxmdsSimulation.parameters()->simulationName.c_str(),
                mpicflags.c_str(),
                clibs.c_str(),
                cincludes.c_str(),
                myxmdsSimulation.parameters()->fftwVersion == 2
                  ? fftw_mpi_libs.c_str() : fftw3libs.c_str(),
                myxmdsSimulation.parameters()->useIntelMKL ? "-lguide -lvml" : "");
        cout << "        " << command << "\n";
        if (system(command)) {
          cout << "compilation failed.\n";
          return 1;
        }
      }
      else {
        printf("compiling for MPI parallel execution ...\n");
        sprintf(command, "%s -o %s %s.cc %s %s %s %s %s",
                mpicc.c_str(),
                myxmdsSimulation.parameters()->simulationName.c_str(),
                myxmdsSimulation.parameters()->simulationName.c_str(),
                mpicflags.c_str(),
                clibs.c_str(),
                cincludes.c_str(),
                myxmdsSimulation.parameters()->fftwVersion == 2
                  ? fftw_mpi_libs.c_str() : fftw3libs.c_str(),
                myxmdsSimulation.parameters()->useIntelMKL ? "-lguide -lvml" : "");
        cout << "        " << command << "\n";
        if (system(command)) {
          cout << "compilation failed.\n";
          return 1;
        }
      }
    }
    else {
      if (myxmdsSimulation.parameters()->nThreads > 1) {
        cout << "compiling for threaded parallel execution...\n";
        sprintf(command, "%s -D_REENTRANT %s -o %s %s.cc %s %s %s %s %s %s",
                cc.c_str(),
                cflags.c_str(),
                myxmdsSimulation.parameters()->simulationName.c_str(),
                myxmdsSimulation.parameters()->simulationName.c_str(),
                cincludes.c_str(),
                clibs.c_str(),
                myxmdsSimulation.parameters()->fftwVersion == 2
                  ? cthreadlibs.c_str() : fftw3threadlibs.c_str(),
                myxmdsSimulation.parameters()->fftwVersion == 2
                  ? fftwlibs.c_str() : fftw3libs.c_str(),
                myxmdsSimulation.parameters()->useOpenMP ? "-openmp" : "",
                myxmdsSimulation.parameters()->useIntelMKL ? "-lguide -lvml" : "");
        cout << "        " << command << "\n";
        if (system(command)) {
          cout << "compilation failed.\n";
          return 1;
        }
      }
      else {
        cout << "compiling ...\n";
        sprintf(command, "%s %s -o %s %s.cc %s %s %s %s",
                cc.c_str(),
                cflags.c_str(),
                myxmdsSimulation.parameters()->simulationName.c_str(),
                myxmdsSimulation.parameters()->simulationName.c_str(),
                cincludes.c_str(),
                clibs.c_str(),
                myxmdsSimulation.parameters()->fftwVersion == 2
                  ? fftwlibs.c_str() : fftw3libs.c_str(),
                myxmdsSimulation.parameters()->useIntelMKL ? "-lguide -lvml" : "");
        cout << "        " << command << "\n";
        if (system(command)) {
          cout << "compilation failed.\n";
          return 1;
        }
      }
    }

    // ok, we're ready to go; tell the user about it
    cout << "\n" << myxmdsSimulation.parameters()->simulationName.c_str() <<
      " ready to execute\n";
  }
  return 0;
}

/*
 * Local variables:
 * c-indentation-style: bsd
 * c-basic-offset: 2
 * indent-tabs-mode: nil
 * End:
 *
 * vim: tabstop=2 expandtab shiftwidth=2:
 */