This file is indexed.

/usr/include/meep.hpp is in libmeep-mpich2-dev 1.1.1-10build1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
/* Copyright (C) 2005-2009 Massachusetts Institute of Technology
%
%  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, 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.
*/
#ifndef MEEP_H
#define MEEP_H

#include <stdio.h>
#include <math.h>

#include "meep/vec.hpp"
#include "meep/mympi.hpp"

namespace meep {

/* We use the type realnum for large arrays, e.g. the fields.
   For local variables and small arrays, we use double precision,
   but for things like the fields we can often get away with
   single precision (since the errors are not dominated by roundoff). 
   However, we will default to using double-precision for large 
   arrays, as the factor of two in memory and the moderate increase
   in speed currently don't seem worth the loss of precision. */
#define MEEP_SINGLE 0 // 1 for single precision, 0 for double
#if MEEP_SINGLE
typedef float realnum;
#else
typedef double realnum;
#endif

extern bool quiet; // if true, suppress all non-error messages from Meep

const double pi = 3.141592653589793238462643383276;

const double infinity = HUGE_VAL;

#ifdef NAN
const double nan = NAN;
#else
const double nan = -7.0415659787563146e103; // ideally, a value never encountered in practice
#endif

class polarizability_identifier {
 public:
  field_type ft;
  double gamma, omeganot;
  bool operator==(const polarizability_identifier &);
};
class polarizability;
class polarization;
class grace;

// h5file.cpp: HDF5 file I/O.  Most users, if they use this
// class at all, will only use the constructor to open the file, and
// will otherwise use the fields::output_hdf5 functions.
class h5file {
public:
  typedef enum {
    READONLY, READWRITE, WRITE
  } access_mode;
  
  h5file(const char *filename_, access_mode m=READWRITE, bool parallel_=true);
  ~h5file(); // closes the files (and any open dataset)
  
  bool ok();
  
  realnum *read(const char *dataname, int *rank, int *dims, int maxrank);
  void write(const char *dataname, int rank, const int *dims, realnum *data,
	     bool single_precision = true);
  
  char *read(const char *dataname);
  void write(const char *dataname, const char *data);
  
  void create_data(const char *dataname, int rank, const int *dims,
		   bool append_data = false,
		   bool single_precision = true);
  void extend_data(const char *dataname, int rank, const int *dims);
  void create_or_extend_data(const char *dataname, int rank,
			     const int *dims,
			     bool append_data, bool single_precision);
  void write_chunk(int rank, const int *chunk_start, const int *chunk_dims,
		   realnum *data);
  void done_writing_chunks();
  
  void read_size(const char *dataname, int *rank, int *dims, int maxrank);
  void read_chunk(int rank, const int *chunk_start, const int *chunk_dims,
		  realnum *data);
  
  void remove();
  void remove_data(const char *dataname);
  
  const char *file_name() const { return filename; }

  void prevent_deadlock(); // hackery for exclusive mode
private:
  access_mode mode;
  char *filename;
  bool parallel;

  bool is_cur(const char *dataname);
  void unset_cur();
  void set_cur(const char *dataname, void *data_id);
  char *cur_dataname;
  bool cur_append_data;
  
  /* linked list to keep track of which datasets we are extending...
     this is necessary so that create_or_extend_data can know whether
     to create (overwrite) a dataset or extend it. */
  struct extending_s {
    int dindex;
    char *dataname;
    struct extending_s *next;
  } *extending;
  extending_s *get_extending(const char *dataname) const;
  
  /* store hid_t values as hid_t* cast to void*, so that
     files including meep.h don't need hdf5.h */
  void *id; /* file */
  void *cur_id; /* dataset, if any */

  void *get_id(); // get current (file) id, opening/creating file if needed
  void close_id();
};

typedef double (*pml_profile_func)(double u, void *func_data);

#define DEFAULT_SUBPIXEL_TOL 1e-4
#define DEFAULT_SUBPIXEL_MAXEVAL 100000

/* This class is used to compute position-dependent material properties
   like the dielectric function, permeability (mu), polarizability sigma, 
   nonlinearities, et cetera.  Simple cases of stateless functions are
   handled by canned subclasses below, but more complicated cases
   can be handled by creating a user-defined subclass of material_function.
   It is useful to group different properties into one class because
   it is likely that complicated implementations will share state between
   properties. */
class material_function {
  material_function(const material_function &ef) {(void)ef;} // prevent copying
public:
  material_function() : omega(nan), gamma(nan) {}
  
  virtual ~material_function() {}
  
  /* Specify a restricted grid_volume: all subsequent eps/sigma/etc
     calls will be for points inside v, until the next set_volume. */
  virtual void set_volume(const volume &v) {(void)v;}
  virtual void unset_volume(void) {} // unrestrict the grid_volume
  
  virtual double chi1p1(field_type ft, const vec &r) { (void)ft; (void)r; return 1.0; }

  /* scalar dielectric function */
  virtual double eps(const vec &r) { return chi1p1(E_stuff, r);  }

  /* scalar permeability function */
  virtual bool has_mu() { return false; } /* true if mu != 1 */
  virtual double mu(const vec &r) { return chi1p1(H_stuff, r);  }
  
  /* scalar conductivity function */
  virtual bool has_conductivity(component c) { (void)c; return false; }
  virtual double conductivity(component c, const vec &r) { 
    (void) c; (void)r; return 0.0; }  

  // fallback routine based on spherical quadrature
  vec normal_vector(field_type ft, const volume &v);

  /* Return c'th row of effective 1/(1+chi1) tensor in the given grid_volume v
     ... virtual so that e.g. libctl can override with more-efficient
     libctlgeom-based routines.  maxeval == 0 if no averaging desired. */
  virtual void eff_chi1inv_row(component c, double chi1inv_row[3],
			       const volume &v, 
			       double tol=DEFAULT_SUBPIXEL_TOL, 
			       int maxeval=DEFAULT_SUBPIXEL_MAXEVAL);
  
  /* polarizability sigma function: return c'th row of tensor */
  virtual void sigma_row(component c, double sigrow[3], const vec &r) {
    (void) c; (void) r; sigrow[0] = sigrow[1] = sigrow[2] = 0.0;
  }

  /* specify polarizability used for subsequent calls to sigma(r) */
  virtual void set_polarizability(field_type ft, double omega_, double gamma_){
    pol_ft=ft; omega=omega_; gamma=gamma_;
  }
  
  // Nonlinear susceptibilities
  virtual bool has_chi3(component c) { (void)c; return false; }
  virtual double chi3(component c, const vec &r) { (void)c; (void)r; return 0.0; }
  virtual bool has_chi2(component c) { (void)c; return false; }
  virtual double chi2(component c, const vec &r) { (void)c; (void)r; return 0.0; }
  
  // TODO: dielectric tensor, ...

protected:
  // current polarizability for calls to sigma(r):
  field_type pol_ft;
  double omega, gamma;
};

class simple_material_function : public material_function {
  double (*f)(const vec &);
  
public:
  simple_material_function(double (*func)(const vec &)) { f = func; }
  
  virtual ~simple_material_function() {}
  
  virtual double chi1p1(field_type ft, const vec &r) { (void)ft; return f(r); }
  virtual double eps(const vec &r) { return f(r); }
  virtual double mu(const vec &r) { return f(r); }
  virtual double conductivity(component c, const vec &r) { 
    (void)c; return f(r); }
  virtual void sigma_row(component c, double sigrow[3], const vec &r) {
    sigrow[0] = sigrow[1] = sigrow[2] = 0.0;
    sigrow[component_index(c)] = f(r);
  }
  virtual double chi3(component c, const vec &r) { (void)c; return f(r); }
  virtual double chi2(component c, const vec &r) { (void)c; return f(r); }
};

class structure;

class structure_chunk {
 public:
  double a, Courant, dt; // res. a, Courant num., and timestep dt=Courant/a
  realnum *chi3[NUM_FIELD_COMPONENTS], *chi2[NUM_FIELD_COMPONENTS];
  realnum *chi1inv[NUM_FIELD_COMPONENTS][5];
  bool trivial_chi1inv[NUM_FIELD_COMPONENTS][5];
  realnum *conductivity[NUM_FIELD_COMPONENTS][5];
  realnum *condinv[NUM_FIELD_COMPONENTS][5]; // cache of 1/(1+conduct*dt/2)
  bool condinv_stale; // true if condinv needs to be recomputed
  double *sig[5], *siginv[5]; // conductivity array for uPML
  int sigsize[5]; // conductivity array size
  grid_volume gv;  // integer grid_volume that could be bigger than non-overlapping v below
  volume v;
  polarizability *pb;

  int refcount; // reference count of objects using this structure_chunk

  ~structure_chunk();
  structure_chunk(const grid_volume &gv,
            const volume &vol_limit, double Courant, int proc_num);
  structure_chunk(const structure_chunk *);
  void set_chi1inv(component c, material_function &eps,
                   bool use_anisotropic_averaging,
		   double tol, int maxeval);
  bool has_chi1inv(component c, direction d) const;
  void set_conductivity(component c, material_function &eps);
  void update_condinv();
  void set_chi3(component c, material_function &eps);
  void set_chi2(component c, material_function &eps);
  void use_pml(direction, double dx, double boundary_loc, double Rasymptotic, 
	       pml_profile_func pml_profile, void *pml_profile_data,
	       double pml_profile_integral);

  void add_polarizability(material_function &sigma, field_type ft, double omega, double gamma);

  void mix_with(const structure_chunk *, double);

  int n_proc() const { return the_proc; } // Says which proc owns me!
  int is_mine() const { return the_is_mine; }

  void remove_polarizabilities();

  // monitor.cpp
  double get_chi1inv(component, direction, const ivec &iloc) const;
  double get_inveps(component c, direction d, const ivec &iloc) const {
    return get_chi1inv(c, d, iloc); }
  double max_eps() const;
 private:
  double pml_fmin;
  int the_proc;
  int the_is_mine;
};

double pml_quadratic_profile(double, void*);

// linked list of descriptors for boundary regions (currently just for PML)
class boundary_region {
public:
  typedef enum { NOTHING_SPECIAL, PML } boundary_region_kind;
  
  boundary_region() :
    kind(NOTHING_SPECIAL), thickness(0.0), Rasymptotic(1e-16), pml_profile(NULL), pml_profile_data(NULL), pml_profile_integral(1.0), d(NO_DIRECTION), side(Low), next(0) {}
  boundary_region(boundary_region_kind kind, double thickness, double Rasymptotic, pml_profile_func pml_profile, void* pml_profile_data, double pml_profile_integral, direction d, boundary_side side, boundary_region *next = 0) : kind(kind), thickness(thickness), Rasymptotic(Rasymptotic), pml_profile(pml_profile), pml_profile_data(pml_profile_data), pml_profile_integral(pml_profile_integral), d(d), side(side), next(next) {}

  boundary_region(const boundary_region &r) : kind(r.kind), thickness(r.thickness), Rasymptotic(r.Rasymptotic), pml_profile(r.pml_profile), pml_profile_data(r.pml_profile_data), pml_profile_integral(r.pml_profile_integral), d(r.d), side(r.side) { 
    next = r.next ? new boundary_region(*r.next) : 0;
  }

  ~boundary_region() { if (next) delete next; }
  
  void operator=(const boundary_region &r) {
    kind = r.kind; thickness = r.thickness; Rasymptotic = r.Rasymptotic;
    pml_profile = r.pml_profile; pml_profile_data = r.pml_profile_data;
    pml_profile_integral = r.pml_profile_integral;
    d = r.d; side = r.side;
    if (next) delete next;
    next = r.next ? new boundary_region(*r.next) : 0;
  }
  boundary_region operator+(const boundary_region &r0) const {
    boundary_region r(*this), *cur = &r;
    while (cur->next) cur = cur->next;
    cur->next = new boundary_region(r0);
    return r;
  }

  boundary_region operator*(double strength_mult) const {
    boundary_region r(*this), *cur = &r;
    while (cur) {
      cur->Rasymptotic = pow(cur->Rasymptotic, strength_mult);
      cur = cur->next;
    }
    return r;
  }

  void apply(structure *s) const;
  void apply(const structure *s, structure_chunk *sc) const;
  bool check_ok(const grid_volume &gv) const;

private:
  boundary_region_kind kind;
  double thickness, Rasymptotic;
  pml_profile_func pml_profile;
  void *pml_profile_data;
  double pml_profile_integral;
  direction d;
  boundary_side side;
  boundary_region *next;
};

boundary_region pml(double thickness, direction d, boundary_side side);
boundary_region pml(double thickness, direction d);
boundary_region pml(double thickness);
#define no_pml() boundary_region()

class structure {
 public:
  structure_chunk **chunks;
  int num_chunks;
  grid_volume gv, user_volume;
  double a, Courant, dt; // res. a, Courant num., and timestep dt=Courant/a
  volume v;
  symmetry S;
  const char *outdir;
  grid_volume *effort_volumes;
  double *effort;
  int num_effort_volumes;

  ~structure();
  structure();
  structure(const grid_volume &gv, material_function &eps,
	    const boundary_region &br = boundary_region(),
	    const symmetry &s = meep::identity(),
	    int num_chunks = 0, double Courant = 0.5,
	    bool use_anisotropic_averaging=false,
	    double tol=DEFAULT_SUBPIXEL_TOL,
	    int maxeval=DEFAULT_SUBPIXEL_MAXEVAL);
  structure(const grid_volume &gv, double eps(const vec &), 
	    const boundary_region &br = boundary_region(),
	    const symmetry &s = meep::identity(),
	    int num_chunks = 0, double Courant = 0.5,
	    bool use_anisotropic_averaging=false,
	    double tol=DEFAULT_SUBPIXEL_TOL,
	    int maxeval=DEFAULT_SUBPIXEL_MAXEVAL);
  structure(const structure *);
  structure(const structure &);

  void set_materials(material_function &mat,
		     bool use_anisotropic_averaging=true,
		     double tol=DEFAULT_SUBPIXEL_TOL,
		     int maxeval=DEFAULT_SUBPIXEL_MAXEVAL);
  void set_chi1inv(component c, material_function &eps,
                   bool use_anisotropic_averaging=true,
		   double tol=DEFAULT_SUBPIXEL_TOL,
		   int maxeval=DEFAULT_SUBPIXEL_MAXEVAL);
  bool has_chi1inv(component c, direction d) const;
  void set_epsilon(material_function &eps,
                   bool use_anisotropic_averaging=true,
		   double tol=DEFAULT_SUBPIXEL_TOL,
		   int maxeval=DEFAULT_SUBPIXEL_MAXEVAL);
  void set_epsilon(double eps(const vec &),
                   bool use_anisotropic_averaging=true,
		   double tol=DEFAULT_SUBPIXEL_TOL,
		   int maxeval=DEFAULT_SUBPIXEL_MAXEVAL);
  void set_mu(material_function &eps,
	      bool use_anisotropic_averaging=true,
	      double tol=DEFAULT_SUBPIXEL_TOL,
	      int maxeval=DEFAULT_SUBPIXEL_MAXEVAL);
  void set_mu(double mu(const vec &),
	      bool use_anisotropic_averaging=true,
	      double tol=DEFAULT_SUBPIXEL_TOL,
	      int maxeval=DEFAULT_SUBPIXEL_MAXEVAL);
  void set_conductivity(component c, material_function &conductivity);
  void set_conductivity(component C, double conductivity(const vec &));
  void set_chi3(component c, material_function &eps);
  void set_chi3(material_function &eps);
  void set_chi3(double eps(const vec &));
  void set_chi2(component c, material_function &eps);
  void set_chi2(material_function &eps);
  void set_chi2(double eps(const vec &));
  polarizability_identifier
     add_polarizability(double sigma(const vec &), field_type ft, double omega, double gamma);
  polarizability_identifier
     add_polarizability(material_function &sigma, field_type ft, double omega, double gamma);
  polarizability_identifier
     add_polarizability(double sigma(const vec &), double omega, double gamma) {
    return add_polarizability(sigma, E_stuff, omega, gamma); }
  polarizability_identifier
     add_polarizability(material_function &sigma, double omega, double gamma) {
    return add_polarizability(sigma, E_stuff, omega, gamma); }

  void remove_polarizabilities();

  void set_output_directory(const char *name);
  void mix_with(const structure *, double);

  bool equal_layout(const structure &) const;
  void print_layout(void) const;

  // monitor.cpp
  double get_chi1inv(component, direction, const ivec &origloc) const;
  double get_chi1inv(component, direction, const vec &loc) const;
  double get_inveps(component c, direction d, const ivec &origloc) const {
    return get_chi1inv(c, d, origloc); }
  double get_inveps(component c, direction d, const vec &loc) const {
    return get_chi1inv(c, d, loc); }
  double get_eps(const vec &loc) const;
  double get_mu(const vec &loc) const;
  double max_eps() const;

  friend class boundary_region;

 private:
  void use_pml(direction d, boundary_side b, double dx);
  void add_to_effort_volumes(const grid_volume &new_effort_volume, 
			     double extra_effort);
  void choose_chunkdivision(const grid_volume &gv, int num_chunks,
			    const boundary_region &br, const symmetry &s);
  void check_chunks();
  void changing_chunks();
};

class src_vol;
class bandsdata;
class fields;
class fields_chunk;
class flux_vol;

// Time-dependence of a current source, intended to be overridden by
// subclasses.  current() and dipole() are be related by
// current = d(dipole)/dt (or rather, the finite-difference equivalent).
class src_time {
 public:
  // the following variable specifies whether the current
  // source is specified as a current or as an integrated
  // current (a dipole moment), if possible.  In the original Meep,
  // by default electric sources are integrated and magnetic
  // sources are not, but this may change.
  bool is_integrated;

  src_time() { is_integrated = true; current_time = nan; current_current = 0.0; next = NULL; }
  virtual ~src_time() { delete next; }
  src_time(const src_time &t) { 
       is_integrated = t.is_integrated;
       current_time = t.current_time;
       current_current = t.current_current;
       current_dipole = t.current_dipole;
       if (t.next) next = t.next->clone(); else next = NULL;
  }
  
  complex<double> dipole() const { return current_dipole; }
  complex<double> current() const { return current_current; }
  void update(double time, double dt) {
    if (time != current_time) {
      current_dipole = dipole(time);
      current_current = current(time, dt);
      current_time = time;
    }
  }

  // subclasses *can* override this method in order to specify the
  // current directly rather than as the derivative of dipole.
  // in that case you would probably ignore the dt argument.
  virtual complex<double> current(double time, double dt) const { 
    return ((dipole(time + dt) - dipole(time)) / dt);
  }

  double last_time_max() { return last_time_max(0.0); }
  double last_time_max(double after);
  
  src_time *add_to(src_time *others, src_time **added) const;
  src_time *next;

  // subclasses should override these methods:
  virtual complex<double> dipole(double time) const { (void)time; return 0; }
  virtual double last_time() const { return 0.0; }
  virtual src_time *clone() const { return new src_time(*this); }
  virtual bool is_equal(const src_time &t) const { (void)t; return 1; }
  virtual complex<double> frequency() const { return 0.0; }
  virtual void set_frequency(complex<double> f) { (void) f; }

 private:
  double current_time;
  complex<double> current_dipole, current_current;
};

bool src_times_equal(const src_time &t1, const src_time &t2);

// Gaussian-envelope source with given frequency, width, peak-time, cutoff
class gaussian_src_time : public src_time {
 public:
  gaussian_src_time(double f, double fwidth, double s = 5.0);
  gaussian_src_time(double f, double w, double start_time, double end_time);
  virtual ~gaussian_src_time() {}

  virtual complex<double> dipole(double time) const;
  virtual double last_time() const { return float(peak_time + cutoff); };
  virtual src_time *clone() const { return new gaussian_src_time(*this); }
  virtual bool is_equal(const src_time &t) const;
  virtual complex<double> frequency() const { return freq; }
  virtual void set_frequency(complex<double> f) { freq = real(f); }

 private:
  double freq, width, peak_time, cutoff;
};

// Continuous (CW) source with (optional) slow turn-on and/or turn-off.
class continuous_src_time : public src_time {
 public:
  continuous_src_time(complex<double> f, double w = 0.0, 
		      double st = 0.0, double et = infinity,
		      double s = 3.0) : freq(f), width(w), start_time(float(st)),
					end_time(float(et)), slowness(s) {}
  virtual ~continuous_src_time() {}
  
  virtual complex<double> dipole(double time) const;
  virtual double last_time() const { return end_time; };
  virtual src_time *clone() const { return new continuous_src_time(*this); }
  virtual bool is_equal(const src_time &t) const;
  virtual complex<double> frequency() const { return freq; }
  virtual void set_frequency(complex<double> f) { freq = f; }
  
 private:
  complex<double> freq;
  double width, start_time, end_time, slowness;
};

// user-specified source function with start and end times
class custom_src_time : public src_time {
 public:
  custom_src_time(complex<double> (*func)(double t, void *), void *data,
		  double st = -infinity, double et = infinity)
    : func(func), data(data), start_time(float(st)), end_time(float(et)) {}
  virtual ~custom_src_time() {}
  
  virtual complex<double> current(double time, double dt) const { 
    if (is_integrated) return src_time::current(time,dt);
    else return dipole(time);
  }
  virtual complex<double> dipole(double time) const { float rtime = float(time);
    if (rtime >= start_time && rtime <= end_time) return func(time,data); else return 0.0; }
  virtual double last_time() const { return end_time; };
  virtual src_time *clone() const { return new custom_src_time(*this); }
  virtual bool is_equal(const src_time &t) const;
  
 private:
  complex<double> (*func)(double t, void *);
  void *data;
  double start_time, end_time;
};

class monitor_point {
 public:
  monitor_point();
  ~monitor_point();
  vec loc;
  double t;
  complex<double> f[NUM_FIELD_COMPONENTS];
  monitor_point *next;

  complex<double> get_component(component);
  double poynting_in_direction(direction d);
  double poynting_in_direction(vec direction_v);

  // When called with only its first four arguments, fourier_transform
  // performs an FFT on its monitor points, putting the frequencies in f
  // and the amplitudes in a.  Yes, the frequencies are trivial and
  // redundant, but this saves you the risk of making a mistake in
  // converting your units.  Note also, that in this case f is always a
  // real number, although it's stored in a complex.
  //
  // Note that in either case, fourier_transform assumes that the monitor
  // points are all equally spaced in time.
  void fourier_transform(component w,
                         complex<double> **a, complex<double> **f, int *numout,
                         double fmin=0.0, double fmax=0.0, int maxbands=100);
  // harminv works much like fourier_transform, except that it is not yet
  // implemented.
  void harminv(component w,
               complex<double> **a, complex<double> **f,
               int *numout, double fmin, double fmax,
               int maxbands);
};

// dft.cpp
// this should normally only be created with fields::add_dft
class dft_chunk {
public:
  dft_chunk(fields_chunk *fc_,
	    ivec is_, ivec ie_,
	    vec s0_, vec s1_, vec e0_, vec e1_,
	    double dV0_, double dV1_,
	    complex<double> scale_,
	    complex<double> extra_weight_,
	    component c_,
	    bool use_centered_grid,
	    const void *data_);
  ~dft_chunk();
  
  void update_dft(double time);

  void scale_dft(complex<double> scale);

  void operator-=(const dft_chunk &chunk);

  // the frequencies to loop_in_chunks
  double omega_min, domega;
  int Nomega;

  component c; // component to DFT (possibly transformed by symmetry)

  int N; // number of spatial points (on epsilon grid)
  complex<realnum> *dft; // N x Nomega array of DFT values.

  struct dft_chunk *next_in_chunk; // per-fields_chunk list of DFT chunks
  struct dft_chunk *next_in_dft; // next for this particular DFT vol./component

  /* When computing things like -0.5*|E|^2 for the stress tensor,
     we cannot incorporate the minus sign into the scale factor
     because we only ever compute |scale|^2.  Thus, it is necessary
     to store an additional weight factor with the dft_chunk to record
     any additional negative or complex weight factor to be used
     in computations involving the fourier-transformed fields.  Because
     it is used in computations involving dft[...], it needs to be public. */
     complex<double> extra_weight;

private:
  // parameters passed from field_integrate:
  fields_chunk *fc;
  ivec is, ie;
  vec s0, s1, e0, e1;
  double dV0, dV1;
  bool sqrt_dV_and_interp_weights;
  complex<double> scale; // scale factor * phase from shift and symmetry

  // cache of exp(iwt) * scale, of length Nomega
  complex<realnum> *dft_phase;

  int avg1, avg2; // index offsets for average to get epsilon grid
};

void save_dft_hdf5(dft_chunk *dft_chunks, component c, h5file *file,
		   const char *dprefix = 0);
void load_dft_hdf5(dft_chunk *dft_chunks, component c, h5file *file,
		   const char *dprefix = 0);
void save_dft_hdf5(dft_chunk *dft_chunks, const char *name, h5file *file,
		   const char *dprefix = 0);
void load_dft_hdf5(dft_chunk *dft_chunks, const char *name, h5file *file,
		   const char *dprefix = 0);

// dft.cpp (normally created with fields::add_dft_flux)
class dft_flux {
public:
  dft_flux(const component cE_, const component cH_,
	   dft_chunk *E_, dft_chunk *H_,
	   double fmin, double fmax, int Nf);
  dft_flux(const dft_flux &f);

  double *flux();

  void save_hdf5(h5file *file, const char *dprefix = 0);
  void load_hdf5(h5file *file, const char *dprefix = 0);

  void operator-=(const dft_flux &fl) { if (E && fl.E) *E -= *fl.E; if (H && fl.H) *H -= *fl.H; }

  void save_hdf5(fields &f, const char *fname, const char *dprefix = 0,
		 const char *prefix = 0);
  void load_hdf5(fields &f, const char *fname, const char *dprefix = 0,
		 const char *prefix = 0);

  void scale_dfts(complex<double> scale);

  void remove();

  double freq_min, dfreq;
  int Nfreq;
  dft_chunk *E, *H;
  component cE, cH;
};

// stress.cpp (normally created with fields::add_dft_force)
class dft_force {
public:
  dft_force(dft_chunk *offdiag1_, dft_chunk *offdiag2_, dft_chunk *diag_,
	    double fmin, double fmax, int Nf);
  dft_force(const dft_force &f);

  double *force();

  void save_hdf5(h5file *file, const char *dprefix = 0);
  void load_hdf5(h5file *file, const char *dprefix = 0);

  void operator-=(const dft_force &fl);

  void save_hdf5(fields &f, const char *fname, const char *dprefix = 0,
		 const char *prefix = 0);
  void load_hdf5(fields &f, const char *fname, const char *dprefix = 0,
		 const char *prefix = 0);

  void scale_dfts(complex<double> scale);

  void remove();

  double freq_min, dfreq;
  int Nfreq;
  dft_chunk *offdiag1, *offdiag2, *diag;
};

enum in_or_out { Incoming=0, Outgoing };
enum connect_phase { CONNECT_PHASE = 0, CONNECT_NEGATE=1, CONNECT_COPY=2 };

class fields_chunk {
 public:
  realnum *f[NUM_FIELD_COMPONENTS][2]; // fields at current time

  // auxiliary fields needed for PML (at least in some components)
  realnum *f_u[NUM_FIELD_COMPONENTS][2]; // integrated from D/B
  realnum *f_w[NUM_FIELD_COMPONENTS][2]; // E/H integrated from these
  realnum *f_cond[NUM_FIELD_COMPONENTS][2]; // aux field for PML+conductivity

  /* sometimes, to synchronize the E and H fields, e.g. for computing
     flux at a given time, we need to timestep H by 1/2; in this case
     we save backup copies of (some of) the fields to resume timestepping */
  realnum *f_backup[NUM_FIELD_COMPONENTS][2];
  realnum *f_u_backup[NUM_FIELD_COMPONENTS][2];
  realnum *f_w_backup[NUM_FIELD_COMPONENTS][2];
  realnum *f_cond_backup[NUM_FIELD_COMPONENTS][2];

  // used to store D-P and B-P, e.g. when P implements dispersive media
  realnum *f_minus_p[NUM_FIELD_COMPONENTS][2];

  realnum *f_rderiv_int; // cache of helper field for 1/r d(rf)/dr derivative

  dft_chunk *dft_chunks;

  realnum **zeroes[NUM_FIELD_TYPES]; // Holds pointers to metal points.
  int num_zeroes[NUM_FIELD_TYPES];
  realnum **connections[NUM_FIELD_TYPES][CONNECT_COPY+1][Outgoing+1];
  int num_connections[NUM_FIELD_TYPES][CONNECT_COPY+1][Outgoing+1];
  complex<realnum> *connection_phases[NUM_FIELD_TYPES];

  polarization *pols[NUM_FIELD_TYPES], *olpols[NUM_FIELD_TYPES];
  double a, Courant, dt; // res. a, Courant num., and timestep dt=Courant/a
  grid_volume gv;
  volume v;
  double m; // angular dependence in cyl. coords
  bool zero_fields_near_cylorigin; // fields=0 m pixels near r=0 for stability
  double beta;
  int is_real, store_pol_energy;
  bandsdata *bands;
  src_vol *sources[NUM_FIELD_TYPES];
  structure_chunk *new_s;
  structure_chunk *s;
  const char *outdir;

  fields_chunk(structure_chunk *, const char *outdir, double m,
	       bool store_pol_energy, double beta,
	       bool zero_fields_near_cylorigin);
  fields_chunk(const fields_chunk &);
  ~fields_chunk();

  // step.cpp
  double peek_field(component, const vec &);

  void use_real_fields();
  bool have_component(component c, bool is_complex = false) {
    switch (c) {
    case Dielectric: case Permeability:
      return !is_complex;
    default:
      return (f[c][0] && f[c][is_complex]);
    }
  }

  double last_source_time();
  // monitor.cpp
  complex<double> get_field(component, const ivec &) const;

  // for non-collective interpolation:
  volume get_field_gv(component) const;
  complex<double> get_field(component, const vec &) const;

  double get_polarization_energy(const ivec &) const;
  double my_polarization_energy(const ivec &) const;
  double get_polarization_energy(const polarizability_identifier &, const ivec &) const;
  double my_polarization_energy(const polarizability_identifier &, const ivec &) const;
  double get_chi1inv(component, direction, const ivec &iloc) const;
  complex<double> analytic_chi1(component c, double freq, const vec &) const;
  
  void backup_component(component c);
  void average_with_backup(component c);
  void restore_component(component c);
  
  void set_output_directory(const char *name);
  void verbose(int gv=1) { verbosity = gv; }

  double count_volume(component);
  friend class fields;

  int n_proc() const { return s->n_proc(); };
  int is_mine() const { return s->is_mine(); };
  // boundaries.cpp
  void zero_metal(field_type);
  // fields.cpp
  void remove_sources();
  void remove_polarizabilities();
  void zero_fields();

  bool update_eh(field_type ft, bool skip_w_components = false);

  bool alloc_f(component c);
  void figure_out_step_plan();

  void set_solve_cw_omega(complex<double> omega) {
    doing_solve_cw = true;
    solve_cw_omega = omega;
  }
  void unset_solve_cw_omega() {
    doing_solve_cw = false;
    solve_cw_omega = 0.0;
  }

 private: 
  // we set a flag during cw_solve to replace some
  // time-dependent stuff with the analogous frequency-domain operation
  bool doing_solve_cw; // true when inside solve_cw
  complex<double> solve_cw_omega; // current omega for solve_cw

  int verbosity; // Turn on verbosity for debugging purposes...
  // fields.cpp
  bool have_plus_deriv[NUM_FIELD_COMPONENTS], have_minus_deriv[NUM_FIELD_COMPONENTS];
  component plus_component[NUM_FIELD_COMPONENTS], minus_component[NUM_FIELD_COMPONENTS];
  direction plus_deriv_direction[NUM_FIELD_COMPONENTS],
            minus_deriv_direction[NUM_FIELD_COMPONENTS];
  // bands.cpp
  void record_bands(int tcount);
  // step.cpp
  void phase_in_material(structure_chunk *s);
  void phase_material(int phasein_time);
  bool step_db(field_type ft);
  void step_source(field_type ft, bool including_integrated);
  void update_pols(field_type ft);
  void calc_sources(double time);

  // initialize.cpp
  void initialize_field(component, complex<double> f(const vec &));
  void initialize_with_nth_te(int n, double kz);
  void initialize_with_nth_tm(int n, double kz);
  // boundaries.cpp
  void alloc_extra_connections(field_type, connect_phase, in_or_out, int);
  // dft.cpp
  void update_dfts(double timeE, double timeH);

  void changing_structure();
};

enum boundary_condition { Periodic=0, Metallic, Magnetic, None };
enum time_sink { Connecting, Stepping, Boundaries, MpiTime,
                 FieldOutput, FourierTransforming, Other };

typedef void (*field_chunkloop)(fields_chunk *fc, int ichunk, component cgrid,
				ivec is, ivec ie,
				vec s0, vec s1, vec e0, vec e1,
				double dV0, double dV1,
				ivec shift, complex<double> shift_phase, 
				const symmetry &S, int sn,
				void *chunkloop_data);
typedef complex<double> (*field_function)(const complex<double> *fields,
					   const vec &loc,
					   void *integrand_data_);
typedef double (*field_rfunction)(const complex<double> *fields,
				   const vec &loc,
				   void *integrand_data_);

field_rfunction derived_component_func(derived_component c, const grid_volume &gv,
				       int &nfields, component cs[12]);

class fields {
 public:
  int num_chunks;
  fields_chunk **chunks;
  src_time *sources;
  flux_vol *fluxes;
  symmetry S;

  // The following is an array that is num_chunks by num_chunks.  Actually
  // it is two arrays, one for the imaginary and one for the real part.
  realnum **comm_blocks[NUM_FIELD_TYPES];
  // This is the same size as each comm_blocks array, and store the sizes
  // of the comm blocks themselves for each connection-phase type
  int *comm_sizes[NUM_FIELD_TYPES][CONNECT_COPY+1];
  int comm_size_tot(int f, int pair) const {
    int sum = 0; for (int ip=0; ip<3; ++ip) sum+=comm_sizes[f][ip][pair];
    return sum;
  }

  double a, dt; // The resolution a and timestep dt=Courant/a
  grid_volume gv, user_volume;
  volume v;
  double m;
  double beta;
  int t, phasein_time, is_real;
  complex<double> k[5], eikna[5];
  double coskna[5], sinkna[5];
  boundary_condition boundaries[2][5];
  bandsdata *bands;
  char *outdir;

  // fields.cpp methods:
  fields(structure *, double m=0, bool store_pol_energy=0, double beta=0,
	 bool zero_fields_near_cylorigin=true);
  fields(const fields &);
  ~fields();
  bool equal_layout(const fields &f) const;
  void use_real_fields();
  void zero_fields();
  void remove_sources();
  void remove_polarizabilities();
  void remove_fluxes();
  void reset();

  // time.cpp
  double time_spent_on(time_sink);
  void print_times();
  // boundaries.cpp
  void set_boundary(boundary_side,direction,boundary_condition);
  void use_bloch(direction d, double k) { use_bloch(d, (complex<double>) k); }
  void use_bloch(direction, complex<double> kz);
  void use_bloch(const vec &k);
  vec lattice_vector(direction) const;
  // update_eh.cpp
  void update_eh(field_type ft, bool skip_w_components = false);

  volume total_volume(void) const;

  // h5fields.cpp:
  // low-level function:
  void output_hdf5(h5file *file, const char *dataname,
		   int num_fields, const component *components,
		   field_function fun, void *fun_data_, int reim,
		   const volume &where,
		   bool append_data = false,
		   bool single_precision = false);
  // higher-level functions
  void output_hdf5(const char *dataname,  // OUTPUT COMPLEX-VALUED FUNCTION
		   int num_fields, const component *components,
		   field_function fun, void *fun_data_,
		   const volume &where,
		   h5file *file = 0,
		   bool append_data = false,
		   bool single_precision = false,
		   const char *prefix = 0,
		   bool real_part_only = false);
  void output_hdf5(const char *dataname,  // OUTPUT REAL-VALUED FUNCTION
		   int num_fields, const component *components,
		   field_rfunction fun, void *fun_data_,
		   const volume &where,
		   h5file *file = 0,
		   bool append_data = false,
		   bool single_precision = false,
		   const char *prefix = 0);
  void output_hdf5(component c,   // OUTPUT FIELD COMPONENT (or Dielectric)
		   const volume &where,
		   h5file *file = 0,
		   bool append_data = false,
		   bool single_precision = false,
		   const char *prefix = 0);
  void output_hdf5(derived_component c,   // OUTPUT DERIVED FIELD COMPONENT
		   const volume &where,
		   h5file *file = 0,
		   bool append_data = false,
		   bool single_precision = false,
		   const char *prefix = 0);
  h5file *open_h5file(const char *name, 
		      h5file::access_mode mode = h5file::WRITE,
		      const char *prefix = NULL, bool timestamp = false);
  const char *h5file_name(const char *name,
			  const char *prefix = NULL, bool timestamp = false);

  // step.cpp methods:
  double last_step_output_wall_time;
  int last_step_output_t;
  void step();

  // when comparing times, e.g. for source cutoffs, it
  // is useful to round to float to avoid gratuitous sensitivity
  // to floating-point roundoff error
  inline double round_time() const { return float(t*dt); };
  inline double time() const { return t*dt; };

  // cw_fields.cpp:
  bool solve_cw(double tol, int maxiters, complex<double> frequency, int L=2);
  bool solve_cw(double tol = 1e-8, int maxiters = 10000, int L=2);

  // sources.cpp:
  double last_source_time();
  void add_point_source(component c, double freq, double width, double peaktime,
                        double cutoff, const vec &, complex<double> amp = 1.0,
                        int is_continuous = 0);
  void add_point_source(component c, const src_time &src,
                        const vec &, complex<double> amp = 1.0);
  void add_volume_source(component c, const src_time &src,
			 const volume &, 
			 complex<double> A(const vec &),
			 complex<double> amp = 1.0);
  void add_volume_source(component c, const src_time &src,
			 const volume &, 
			 complex<double> amp = 1.0);
  void require_component(component c);

  // mpb.cpp
  void add_eigenmode_source(component c, const src_time &src,
			    const volume &where,
			    const volume &eig_vol,
			    int band_num, const vec &kpoint, int parity,
			    double eig_resolution, double eigensolver_tol,
			    complex<double> amp,
			    complex<double> A(const vec &) = 0);

  // initialize.cpp:
  void initialize_field(component, complex<double> f(const vec &));
  void initialize_with_nth_te(int n);
  void initialize_with_nth_tm(int n);
  void initialize_with_n_te(int n);
  void initialize_with_n_tm(int n);
  int phase_in_material(const structure *s, double time);
  int is_phasing();

  // loop_in_chunks.cpp
  void loop_in_chunks(field_chunkloop chunkloop, void *chunkloop_data,
		      const volume &where,
		      component cgrid = Centered,
		      bool use_symmetry = true,
		      bool snap_unit_dims = false);
  
  // integrate.cpp
  complex<double> integrate(int num_fields, const component *components,
			    field_function fun, void *fun_data_,
			    const volume &where,
			    double *maxabs = 0);
  double integrate(int num_fields, const component *components,
		   field_rfunction fun, void *fun_data_,
		   const volume &where,
		   double *maxabs = 0);
  complex<double> integrate2(const fields &fields2,
			     int num_fields1,
			     const component *components1,
			     int num_fields2, 
			     const component *components2,
			     field_function integrand,
			     void *integrand_data_,
			     const volume &where,
			     double *maxabs = 0);
  double integrate2(const fields &fields2,
		    int num_fields1, const component *components1,
		    int num_fields2, const component *components2,
		    field_rfunction integrand,
		    void *integrand_data_,
		    const volume &where,
		    double *maxabs = 0);


  double max_abs(int num_fields, const component *components,
		 field_function fun, void *fun_data_,
		 const volume &where);
  double max_abs(int num_fields, const component *components,
		 field_rfunction fun, void *fun_data_,
		 const volume &where);

  double max_abs(int c, const volume &where);
  double max_abs(component c, const volume &where);
  double max_abs(derived_component c, const volume &where);
  
  // dft.cpp
  dft_chunk *add_dft(component c, const volume &where,
		     double freq_min, double freq_max, int Nfreq,
		     bool include_dV_and_interp_weights = true,
		     complex<double> weight = 1.0, dft_chunk *chunk_next = 0,
		     bool sqrt_dV_and_interp_weights = false,
		     complex<double> extra_weight = 1.0,
		     bool use_centered_grid = true);
  dft_chunk *add_dft_pt(component c, const vec &where,
			double freq_min, double freq_max, int Nfreq);
  dft_chunk *add_dft(const volume_list *where,
		     double freq_min, double freq_max, int Nfreq,
		     bool include_dV = true);
  void update_dfts();
  dft_flux add_dft_flux(direction d, const volume &where,
			double freq_min, double freq_max, int Nfreq);
  dft_flux add_dft_flux_box(const volume &where,
			    double freq_min, double freq_max, int Nfreq);
  dft_flux add_dft_flux_plane(const volume &where,
			      double freq_min, double freq_max, int Nfreq);
  dft_flux add_dft_flux(const volume_list *where,
			double freq_min, double freq_max, int Nfreq);

  // stress.cpp
  dft_force add_dft_force(const volume_list *where,
			  double freq_min, double freq_max, int Nfreq);

  // monitor.cpp
  double get_chi1inv(component, direction, const vec &loc) const;
  double get_inveps(component c, direction d, const vec &loc) const {
    return get_chi1inv(c, d, loc);
  }
  double get_eps(const vec &loc) const;
  double get_mu(const vec &loc) const;
  void get_point(monitor_point *p, const vec &) const;
  monitor_point *get_new_point(const vec &, monitor_point *p=NULL) const;
  complex<double> analytic_chi1(component,double freq, const vec &) const;
  
  void prepare_for_bands(const vec &, double end_time, double fmax=0,
                         double qmin=1e300, double frac_pow_min=0.0);
  void record_bands();
  complex<double> get_band(int n, int maxbands=100);
  void grace_bands(grace *, int maxbands=100);
  void output_bands(FILE *, const char *, int maxbands=100);
  complex<double> get_field(int c, const vec &loc) const;
  complex<double> get_field(component c, const vec &loc) const;
  double get_field(derived_component c, const vec &loc) const;

  // energy_and_flux.cpp
  void synchronize_magnetic_fields();
  void restore_magnetic_fields();
  double energy_in_box(const volume &);
  double electric_energy_in_box(const volume &);
  double magnetic_energy_in_box(const volume &);
  double thermo_energy_in_box(const volume &);
  double total_energy();
  double field_energy_in_box(const volume &);
  double field_energy_in_box(component c, const volume &);
  double field_energy();
  double flux_in_box_wrongH(direction d, const volume &);
  double flux_in_box(direction d, const volume &);
  flux_vol *add_flux_vol(direction d, const volume &where);
  flux_vol *add_flux_plane(const volume &where);
  flux_vol *add_flux_plane(const vec &p1, const vec &p2);
  double electric_energy_max_in_box(const volume &where);
  double modal_volume_in_box(const volume &where);
  double electric_sqr_weighted_integral(double (*deps)(const vec &),
				       const volume &where);
  double electric_energy_weighted_integral(double (*f)(const vec &),
					   const volume &where);

  void set_output_directory(const char *name);
  void verbose(int gv=1);
  double count_volume(component);
  // fields.cpp
  bool have_component(component);
  // material.cpp
  double max_eps() const;
  // step.cpp
  void step_boundaries(field_type);

  bool nosize_direction(direction d) const;
  direction normal_direction(const volume &where) const;

  // casimir.cpp
  complex<double> casimir_stress_dct_integral(direction dforce,
					      direction dsource,
					      double mx, double my, double mz,
					      field_type ft,
					      volume where,
					      bool is_bloch = false);

  void set_solve_cw_omega(complex<double> omega);
  void unset_solve_cw_omega();

 private: 
  int verbosity; // Turn on verbosity for debugging purposes...
  int synchronized_magnetic_fields; // count number of nested synchs
  double last_wall_time;
  time_sink working_on, was_working_on;
  double times_spent[Other+1];
  // fields.cpp
  void figure_out_step_plan();
  // time.cpp
  void am_now_working_on(time_sink);
  void finished_working();
  // boundaries.cpp
  bool chunk_connections_valid;
  void find_metals();
  void disconnect_chunks();
  void connect_chunks();
  void connect_the_chunks(); // Intended to be ultra-private...
  bool on_metal_boundary(const ivec &);
  ivec ilattice_vector(direction) const;
  bool locate_component_point(component *, ivec *, complex<double> *) const;
  bool locate_point_in_user_volume(ivec *, complex<double> *phase) const;
  void locate_volume_source_in_user_volume(const vec p1, const vec p2, vec newp1[8], vec newp2[8],
                                           complex<double> kphase[8], int &ncopies) const;
  // mympi.cpp
  void boundary_communications(field_type);
  // step.cpp
  void phase_material();
  void step_db(field_type ft);
  void step_source(field_type ft, bool including_integrated = false);
  void update_pols(field_type ft);
  void calc_sources(double tim);
  int cluster_some_bands_cleverly(double *tf, double *td, complex<double> *ta,
                                  int num_freqs, int fields_considered, int maxbands,
                                  complex<double> *fad, double *approx_power);
  void out_bands(FILE *, const char *, int maxbands);
  complex<double> *clever_cluster_bands(int maxbands, double *approx_power = NULL);
  // monitor.cpp
  complex<double> get_field(component c, const ivec &iloc) const;
  double get_polarization_energy(const ivec &) const;
  double get_polarization_energy(const vec &) const;
  double get_polarization_energy(const polarizability_identifier &, const ivec &) const;
  double get_polarization_energy(const polarizability_identifier &, const vec &) const;
  double get_chi1inv(component, direction, const ivec &iloc) const;
};

class flux_vol {
 public:
  flux_vol(fields *f_, direction d_, const volume &where_) : where(where_) {
    f = f_; d = d_; cur_flux = cur_flux_half = 0; 
    next = f->fluxes; f->fluxes = this;
  }
  ~flux_vol() { delete next; }

  void update_half() { cur_flux_half = flux_wrongE(); 
                       if (next) next->update_half(); }
  void update() { cur_flux = (flux_wrongE() + cur_flux_half) * 0.5;
                  if (next) next->update(); }

  double flux() { return cur_flux; }

  flux_vol *next;
 private:
  double flux_wrongE() { return f->flux_in_box_wrongH(d, where); }
  fields *f;
  direction d;
  volume where;
  double cur_flux, cur_flux_half;
};

class grace_point;
enum grace_type { XY, ERROR_BARS };

class grace {
 public:
  grace(const char *fname, const char *dirname = ".");
  ~grace();
  
  void new_set(grace_type t = XY);
  void new_curve();
  void set_legend(const char *);
  void set_range(double xmin, double xmax, double ymin, double ymax);
  void output_point(double x, double y,
                    double dy = -1.0, double extra = -1.0);
  void output_out_of_order(int n, double x, double y,
                           double dy = -1.0, double extra= -1.0);
 private:
  void flush_pts();
  FILE *f;
  char *fn, *dn;
  grace_point *pts;
  int set_num,sn;
};

// The following is a utility function to parse the executable name use it
// to come up with a directory name, avoiding overwriting any existing
// directory, unless the source file hasn't changed.

const char *make_output_directory(const char *exename, const char *jobname = NULL);
void trash_output_directory(const char *dirname);
FILE *create_output_file(const char *dirname, const char *fname);

// The following allows you to hit ctrl-C to tell your calculation to stop
// and clean up.
void deal_with_ctrl_c(int stop_now = 2);
// When a ctrl_c is called, the following variable (which starts with a
// zero value) is incremented.
extern int interrupt;

int do_harminv(complex<double> *data, int n, double dt,
	       double fmin, double fmax, int maxbands,
	       complex<double> *amps, double *freq_re, double *freq_im,
	       double *errors = NULL,
	       double spectral_density = 1.1, double Q_thresh = 50,
	       double rel_err_thresh = 1e20, double err_thresh = 0.01, 
	       double rel_amp_thresh = -1, double amp_thresh = -1);

complex<double> *make_casimir_gfunc(double T, double dt, double sigma, field_type ft,
				complex<double> (*eps_func)(complex<double> omega) = 0,
				double Tfft = 0);

complex<double> *make_casimir_gfunc_kz(double T, double dt, double sigma, field_type ft);

#if MEEP_SINGLE
// in mympi.cpp ... must be here in order to use realnum type
void broadcast(int from, realnum *data, int size);
#endif

} /* namespace meep */

#endif /* MEEP_H */