~reducedmodelling/fluidity/ROM_RES_DEIM

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
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
#    Copyright (C) 2006 Imperial College London and others.
#
#    Please see the AUTHORS file in the main source directory for a full list
#    of copyright holders.
#
#    Prof. C Pain
#    Applied Modelling and Computation Group
#    Department of Earth Science and Engineering
#    Imperial College London
#
#    amcgsoftware@imperial.ac.uk
#
#    This library is free software; you can redistribute it and/or
#    modify it under the terms of the GNU Lesser General Public
#    License as published by the Free Software Foundation,
#    version 2.1 of the License.
#
#    This library 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
#    Lesser General Public License for more details.
#
#    You should have received a copy of the GNU Lesser General Public
#    License along with this library; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
#    USA

dnl Process this file with autoconf to produce a configure script.

AC_INIT(fluidity, None)

AC_CONFIG_HEADERS(include/config.h)

# we ignore PACKAGE_VERSION as it is useless
# instead we pass on FLUIDITY_VERSION from the env. if it is set
AC_SUBST(FLUIDITY_VERSION)

echo "Hostname: `hostname`"

# Store enviroment variables
env_f77="${F77}"
env_fflags="${FFLAGS}"
env_flibs="${FLIBS}"

env_fc="${FC}"
env_fcflags="${FCFLAGS}"
env_fclibs="${FCLIBS}"
env_cflags="${CFLAGS}"
env_cxxflags="${CXXFLAGS}"
env_cppflags="${CPPFLAGS}"

env_libs="${LIBS}"

# Set the default compile flags.
if test "no$FFLAGS" = "no"; then
    FFLAGS=""
fi

if test "no$FCFLAGS" = "no"; then
    FCFLAGS=""
fi

if test "no$CFLAGS" = "no"; then
    CFLAGS=""
fi

if test "no$CXXFLAGS" = "no"; then
    CXXFLAGS=""
fi

#
# Name fluidity
#
AC_ARG_ENABLE(gcov,
    [AC_HELP_STRING([--enable-gcov],
	    [turns on GNUs coverage tool - gcov])])

AC_ARG_ENABLE(debugging,
    [AC_HELP_STRING([--enable-debugging],
	    [turns on debugging flags])])

if test "x$enable_gcov" == "xyes" ; then
    enable_debugging="yes"
    FCFLAGS="$FCFLAGS -fprofile-arcs -ftest-coverage"
    CFLAGS="$CFLAGS -fprofile-arcs -ftest-coverage"
    CXXFLAGS="$CXXFLAGS -fprofile-arcs -ftest-coverage"
    LDFLAGS="$LDFLAGS -fprofile-arcs -ftest-coverage"
fi
 
FLFEMDEM="femdem"

# Check system type
AC_CANONICAL_HOST

# Find compilers
AC_MSG_NOTICE([*** Fishing for legacy fortran compiler.])
AC_PROG_F77(ifort ifc efc sunf95 gfortran pgf95 pathf95 g95 f90,,f90,$PATH)
AC_F77_LIBRARY_LDFLAGS
fcompiler=`basename $F77`

AC_MSG_NOTICE([*** Fishing for modern Fortran compiler])
AC_PROG_FC(ifort ifc efc sunf95 gfortran pgf95 pathf95 g95 f90,,f90,$PATH)
AC_FC_LIBRARY_LDFLAGS
fccompiler=`basename $FC`

if test "$fcompiler" = "sunf95" ; then
    MODINC_FLAG="-M"
    FFLAGS="-M../include $FFLAGS"
    FCFLAGS="-M../include $FCFLAGS"
else
    MODINC_FLAG="-I"
fi

# We're calling the fortran compiler and testing if gcc is in the output. If so
# we're using gfortran. Fixes cases where we're using gfortran, but the compiler binary
# is not called gfortran
if $FC -v 2>&1 | grep 'gcc version'; then
  USING_GFORTRAN="yes"
  GFORTRAN_VERSION=$($FC -v 2>&1 | grep 'gcc version' | awk '{print $3}')
  # test really is so retarded that it can't lexicographically compare strings
  if test "$(python -c "print \"$GFORTRAN_VERSION\" >= \"4.5\"")" = "True"; then
    GFORTRAN_4_5_OR_NEWER="yes"
    AC_SUBST(GFORTRAN_4_5_OR_NEWER)
  fi
else
  USING_GFORTRAN="no"
fi

# How to specify where .mod files are placed.
if test "$FC" = "ifort"; then
   MOD_FLAG="-module "
elif test "$USING_GFORTRAN" = "yes"; then
   MOD_FLAG="-J"
else
   AC_MSG_ERROR(Don't know how to specify the module output directory for $FC.)
fi
AC_SUBST(MOD_FLAG)


if test "$F77" = "$FC" ; then
    smart_fortran="yes"
    AC_MSG_NOTICE([*** Assuming that $FC can process both free and fixed form fortran files.])
else
    AC_MSG_NOTICE([*** Assuming that $FC cannot process both free and fixed form fortran files (silly fortran).])
    smart_fortran="no"
fi

if test "$fcompiler" = "ifort" ; then
    if ifort -v 2>&1 |grep 11.0; then 
      AC_MSG_ERROR(Intel 11.0 is bugged and cannot be used to compile Fluidity. Try a working version of the compiler such as 10.1.)
    fi
    if ifort -v 2>&1 |grep 11.1; then 
      AC_MSG_WARN(Early versions of intel 11.1 are bugged and cannot be used to compile Fluidity. Make sure you have at least version 11.1.073.)
    fi
    FFLAGS="$FFLAGS -vec-report=0"
    FCFLAGS="$FCFLAGS -vec-report=0"
fi


AC_PROG_CC(icc ecc suncc pgcc gcc cc)
AC_PROG_CXX(icpc icc ecc sunCC pgCC g++ CC)
AC_PROG_CPP
LINKER=$CXX

AC_LONG_64_BITS

# Find fortran libraries required when linking with C++ main.

AC_F77_LIBRARY_LDFLAGS
AC_FC_LIBRARY_LDFLAGS

AC_F77_WRAPPERS

# Find python to link against.
AC_ARG_ENABLE(python,
[AC_HELP_STRING([--enable-python],
[embed python in fluidity for generic functions.])])

if test "$enable_python" != "no"
then
    AC_MSG_NOTICE([Checking for Python automagic.])
    AC_LANG_PUSH([C++])
    AC_LINK_IFELSE(
        [AC_LANG_PROGRAM([[
     #include <Python.h>
                        ]],[[
                        Py_Initialize();
                        PyRun_SimpleString("from time import time,ctime\n"
                            "print 'Today is',ctime(time())\n");
                        Py_Finalize();
		        ]])],
        [
	    AC_MSG_NOTICE([Python automagic works.])
	    CPPFLAGS="$CPPFLAGS -DHAVE_PYTHON"],
        [
            AC_MSG_NOTICE([No Python automagic.])
	    search_for_python=yes	    
        ])
    AC_LANG_POP([C++])
    
    if test "x$search_for_python" == "xyes" ; then
        mycppflag=$CPPFLAGS
        AC_PYTHON_DEVEL
        CPPFLAGS=$mycppflag
    # Save variables...
        if test "$pythonexists" = "yes";
        then
	    if  test "$fcompiler" = "pgf90"; then
	        PYTHON_EXTRA_LDFLAGS=${PYTHON_EXTRA_LDFLAGS/-Xlinker/}
	        PYTHON_EXTRA_LDFLAGS=${PYTHON_EXTRA_LDFLAGS/-export-dynamic/}
	    fi
      if test "$enable_debugging" = "yes"; then
        export PYTHON_EXTRA_LDFLAGS=$(echo $PYTHON_EXTRA_LDFLAGS | sed -e 's/-O1/-O0/g' -e 's/-O2/-O0/g' -e 's/-O3/-O0/g')
      fi
	    LIBS="$LIBS $PYTHON_LDFLAGS $PYTHON_EXTRA_LDFLAGS $PYTHON_EXTRA_LIBS"
	    CXXFLAGS="$CXXFLAGS $PYTHON_CPPFLAGS"
	    CPPFLAGS="$CPPFLAGS $PYTHON_CPPFLAGS"
            CFLAGS="$CFLAGS $PYTHON_CPPFLAGS"
        fi
    fi
    
    # Additionally check for numpy
    NUMPY=$(python -c 'import numpy; print numpy.get_include()' 2>/dev/null)
    if ! test -z "$NUMPY"; then	
	echo "Numpy is " $NUMPY	
	CXXFLAGS="$CXXFLAGS -DHAVE_NUMPY -I$NUMPY"
        CPPFLAGS="$CPPFLAGS -DHAVE_NUMPY -I$NUMPY"
        CFLAGS="$CFLAGS -DHAVE_NUMPY -I$NUMPY"
        FFLAGS="$FFLAGS -DHAVE_NUMPY -I$NUMPY"
        FCFLAGS="$FCFLAGS -DHAVE_NUMPY -I$NUMPY"
    else
	echo "Failed to locate Numpy"
    fi
fi
AC_SUBST(HAVE_PYTHON)

AC_ARG_ENABLE(cgal, [AC_HELP_STRING([--enable-cgal], [turns on use of the CGAL library])])
if test "$enable_cgal" = "yes" ; then
  AC_CHECK_LIB(CGAL, cos, [HAVE_CGAL=yes], [HAVE_CGAL=no])
  AC_SUBST(HAVE_CGAL)
  if test "$HAVE_CGAL" = "yes"; then
    cat >> confdefs.h << EOF
#define HAVE_CGAL 1
EOF
    LIBS="$LIBS -lCGAL -lgmp -lmpfr"
  else
    AC_MSG_ERROR("Use of CGAL enabled but cannot identify CGAL. Check that it is installed.")
  fi
fi

# Find a library which will give us blas and lapack routines
AC_LANG_PUSH([C])
found_blas="no"
if test -z "$with_lapack" -a -z "$with_blas" && \
   test \( "$fcompiler" = "ifc" \) -o \( "$fcompiler" = "ifort" \) -o \( "$fcompiler" = "efc" \)
    then
    AC_MSG_NOTICE([Appear to be using Intel compiler suite. Check if MKL is also available.])
    for i in `echo $LD_LIBRARY_PATH | sed -e 's/:/ /g'`
      do
      echo "looking in $i"
      if test \( -f $i/libmkl.a \) -o \( -f $i/libmkl.so \)
      then
          AC_MSG_NOTICE([Will look in $i for MKL.])
      LIBS="$LIBS -L$i"
      LAPACK_LIBS="-L$i $LAPACK_LIBS"
      fi
    done
    ACX_BLAS([found_blas="yes"],[found_blas="no"])
elif  test "$fcompiler" = "pgf90"
    then
    AC_MSG_NOTICE([Appear to be using Portland Group compiler suite. Check if ACML is also available.])
    AC_CHECK_LIB(acml, dgesv, [found_blas=yes], [found_blas=no])

elif test "$fcompiler" = "sunf95"
    then
    LIBS="$LIBS -lfui -lfai -lfsu -lmtsk -lpthread -lm"
    AC_MSG_NOTICE([Appear to be using Sun Studio compiler suite. Check if Sun Performance Library is also available.])
    AC_CHECK_LIB(sunperf, dgesv, [found_blas=yes ; acx_blas_ok=yes], [found_blas=no])
fi
AC_LANG_POP([C])

AC_LANG_PUSH([Fortran 77])
if test "$found_blas" = "no"
    then
    AC_MSG_NOTICE([checking the position of the stars to help find a versions of BLAS])
    ACX_BLAS([],[AC_MSG_ERROR("Cannot identify BLAS. Check that it is installed.")])
fi
ACX_LAPACK([],[AC_MSG_ERROR("Cannot identify LAPACK. Check that it is installed.")])
AC_LANG_POP([Fortran 77])

# Check for standard libraries
AC_LANG_PUSH([C])
AC_CHECK_LIB(stdc++,main,,)
AC_CHECK_LIB(m,main,,)
AC_CHECK_LIB(pthread,main,,)
AC_SEARCH_LIBS(utInit,[udunits udunits2],[have_udunits="yes"],)
if test "$have_udunits" = "yes"; then
  cat >> confdefs.h << EOF
#define HAVE_LIBUDUNITS 1
EOF
fi

AC_ARG_ENABLE(openmp,
    [AC_HELP_STRING([--enable-openmp],
	    [turns on OpenMP support])])
if test "x$enable_openmp" == "xyes" ; then      
    AC_LANG_PUSH([C++])
    AC_OPENMP()
    CXXFLAGS="$CXXFLAGS $OPENMP_CXXFLAGS"
    LDFLAGS="$LDFLAGS $OPENMP_CXXFLAGS"
    AC_LANG_POP([C++])

    # Assume same flag for FC
    FCFLAGS="$FCFLAGS $OPENMP_CXXFLAGS"
fi
LIBS="$LAPACK_LIBS $BLAS_LIBS $LIBS $FCLIBS $FLIBS"

AC_SUBST(LAPACK_LIBS)
AC_SUBST(BLAS_LIBS)

LINKER=$CXX

AC_ARG_ENABLE(shared,
[AC_HELP_STRING([--enable-shared],
[Compile objects with -fPIC to enable the 'make shared' target.])])

if test "$enable_shared" = "yes" ; then
  PIC_FLAG="-fPIC"
  FFLAGS="$FFLAGS $PIC_FLAG"
  FCFLAGS="$FCFLAGS $PIC_FLAG"
  CFLAGS="$CFLAGS $PIC_FLAG"
  CXXFLAGS="$CXXFLAGS $PIC_FLAG"
else
  PIC_FLAG=""
fi

##
## what compiler options work
##
if test "$FC" = "g95"; then
    FFLAGS="-ffast-math -fno-second-underscore $FFLAGS"
    FCFLAGS="-ffast-math -fno-second-underscore $FCFLAGS"
fi

# How to unroll loops?
AC_MSG_CHECKING(["Checking for -funroll-loops"])
UNROLL_LOOPS=""
OLD_FFLAGS="$FFLAGS"
FFLAGS="-funroll-loops"
AC_LANG_PUSH([Fortran 77])
AC_COMPILE_IFELSE(
    [AC_LANG_PROGRAM(,[[
                    PRINT*, "hello world"
                    ]])],
    [
        AC_MSG_RESULT(-funroll-loops works)
        UNROLL_LOOPS="-funroll-loops"
    ])
FFLAGS="$OLD_FFLAGS"
AC_SUBST(UNROLL_LOOPS)
AC_LANG_POP()

if test "$USING_GFORTRAN" = "yes"; then
    if test "$enable_debugging" = "yes" ; then
	FFLAGS="-frecord-marker=4 $FFLAGS"
	FCFLAGS="-frecord-marker=4 $FCFLAGS"
    else
	FFLAGS="-ffast-math -frecord-marker=4 $FFLAGS"
	FCFLAGS="-ffast-math -frecord-marker=4 $FCFLAGS"
    fi
    cat >> confdefs.h << EOF
#define USING_GFORTRAN 1
EOF
fi
AC_LANG_POP([C])

AC_LANG_PUSH(Fortran 77)
AC_MSG_CHECKING([how do we get fortran 77 to allow long lines])
old_FLAGS="$FFLAGS"
extended_source_flag=none
AC_COMPILE_IFELSE(
    [AC_LANG_PROGRAM(,[[
      PRINT*, "hello world                                                                                 "
                    ]])],
    [
        AC_MSG_RESULT(no extra flags required)
        extended_source_flag=happy
    ])

if test "$extended_source_flag" != happy ; then
    if test "$extended_source_flag" = none ; then
        FFLAGS="-extend_source"
        AC_COMPILE_IFELSE(
            [AC_LANG_PROGRAM(,[[
      PRINT*, "hello world                                                                                 "
                            ]])],
            [
                extended_source_flag=$FFLAGS
                AC_MSG_RESULT([$FFLAGS])
                FFLAGS="$old_FLAGS $FFLAGS"
            ])
    fi
    if test "$extended_source_flag" = none ; then
        FFLAGS="-extend-source"
        AC_COMPILE_IFELSE(
            [AC_LANG_PROGRAM(,[[
      PRINT*, "hello world                                                                                 "
                            ]])],
            [
                extended_source_flag=$FFLAGS
                AC_MSG_RESULT([$FFLAGS])
                FFLAGS="$old_FLAGS $FFLAGS"
            ])
    fi
    if test "$extended_source_flag" = none ; then
        FFLAGS="-132"
        AC_COMPILE_IFELSE(
            [AC_LANG_PROGRAM(,[[
      PRINT*, "hello world                                                                                 "
                            ]])],
            [
                extended_source_flag=$FFLAGS
                AC_MSG_RESULT([$FFLAGS])
                FFLAGS="$old_FLAGS $FFLAGS"
            ])
    fi
    if test "$extended_source_flag" = none ; then
        FFLAGS="-ffree-line-length-none -ffixed-line-length-none"
        AC_COMPILE_IFELSE(
            [AC_LANG_PROGRAM(,[[
      PRINT*, "hello world                                                                                 "
                            ]])],
            [
                extended_source_flag=$FFLAGS
                AC_MSG_RESULT([$FFLAGS])
                FFLAGS="$old_FLAGS $FFLAGS"
            ])
    fi
    if test "$extended_source_flag" = none ; then
        FFLAGS="-ffixed-line-length-huge -ffree-line-length-huge"
        AC_COMPILE_IFELSE(
            [AC_LANG_PROGRAM(,[[
      PRINT*, "hello world                                                                                 "
                            ]])],
            [
                extended_source_flag=$FFLAGS
                AC_MSG_RESULT([$FFLAGS])
                FFLAGS="$old_FLAGS $FFLAGS"
            ])
    fi
    if test "$extended_source_flag" = none ; then
        FFLAGS="-ffixed-line-length-132 -ffree-line-length-huge"
        AC_COMPILE_IFELSE(
            [AC_LANG_PROGRAM(,[[   
      PRINT*, "hello world                                                                                 "
                            ]])],
            [
                extended_source_flag=$FFLAGS
                AC_MSG_RESULT([$FFLAGS])
                FFLAGS="$old_FLAGS $FFLAGS"
            ])
    fi
    if test "$extended_source_flag" = none ; then
        FFLAGS="-ffixed-line-length-132"
        AC_COMPILE_IFELSE(
            [AC_LANG_PROGRAM(,[[
      PRINT*, "hello world                                                                                 "
                            ]])],
            [
                extended_source_flag=$FFLAGS
                AC_MSG_RESULT([$FFLAGS])
                FFLAGS="$old_FLAGS $FFLAGS"
            ])
    fi
    if test "$extended_source_flag" = none ; then
        FFLAGS="-Mextend"
        AC_COMPILE_IFELSE(
            [AC_LANG_PROGRAM(,[[
      PRINT*, "hello world                                                                                 "
                            ]])],
            [
                extended_source_flag=$FFLAGS
                AC_MSG_RESULT([$FFLAGS])
                FFLAGS="$old_FLAGS $FFLAGS"
            ])
    fi
    if test "$extended_source_flag" = none ; then
        FFLAGS="-qfixed=256"
        AC_COMPILE_IFELSE(
            [AC_LANG_PROGRAM(,[[
      PRINT*, "hello world                                                                                 "
                            ]])],
            [
                extended_source_flag=$FFLAGS
                AC_MSG_RESULT([$FFLAGS])
                FFLAGS="$old_FLAGS $FFLAGS"
            ])
    fi
    if test "$extended_source_flag" = none ; then
        FFLAGS="-e"
        AC_COMPILE_IFELSE(
            [AC_LANG_PROGRAM(,[[
      PRINT*, "hello world                                                                                 "
                            ]])],
            [
                extended_source_flag=$FFLAGS
                AC_MSG_RESULT([$FFLAGS])
                FFLAGS="$old_FLAGS $FFLAGS"
            ])
    fi
    if test "$extended_source_flag" = none ; then
        AC_MSG_RESULT([we cannot])
    else
        FCFLAGS="$FCFLAGS $extended_source_flag"
    fi
fi

AC_LANG_POP([Fortran 77])

AC_PROG_INSTALL
AC_CHECK_PROG(MAKE, gmake, gmake, make, $PATH)


# Set default for ARFLAGS, since autoconf does not have a macro for
# it. This allows people to set it when running configure or make.
AC_CHECK_PROG(AR, ar, ar, ,$PATH)
test -n "$ARFLAGS" || ARFLAGS="cr"

AC_PROG_RANLIB

AC_ARG_ENABLE(verbose,
[AC_HELP_STRING([--enable-verbose],
[turns on super verbosity])])

if test "$enable_verbose" = "yes" ; then
cat >> confdefs.h << EOF
#define VERBOSE_MESSAGES 1
EOF
fi

if test "$enable_debugging" = "yes" ; then
  CFLAGS="-g -O0 `echo $CFLAGS | sed 's/-O2//g'`"
  CXXFLAGS="-g -O0 `echo $CXXFLAGS | sed 's/-O2//g'`"
  FFLAGS="-g -O0 `echo $FFLAGS | sed 's/-O2//g'`"
  FCFLAGS="-g -O0 `echo $FCFLAGS | sed 's/-O2//g'`"
cat >> confdefs.h << EOF
#define DDEBUG 1
EOF

  if test "$fcompiler" = "ifort" ; then
    FFLAGS="-C -traceback -check nooutput_conversion -check noarg_temp_created ${FFLAGS}"
    FCFLAGS="-C -traceback -check nooutput_conversion -check noarg_temp_created  ${FCFLAGS}"
    CFLAGS="-fno-omit-frame-pointer ${CFLAGS}"
    CXXFLAGS="-fno-omit-frame-pointer ${CXXFLAGS}"
  elif test "$USING_GFORTRAN" = "yes" ; then
    old_fflags="$FFLAGS"
    old_fcflags="$FCFLAGS"
    FFLAGS="$FFLAGS -finit-integer=-66666 -finit-real=nan"
    FCFLAGS="$FCFLAGS -finit-integer=-66666 -finit-real=nan"
    AC_LANG_PUSH([Fortran])
    AC_COMPILE_IFELSE(
        [AC_LANG_PROGRAM(,[[
                        PRINT*, "hello world"
                        ]])],
        [
            AC_MSG_RESULT(can initialise integers and reals)
            old_fflags="$FFLAGS"
            old_fcflags="$FCFLAGS"
            ], [
            AC_MSG_RESULT(cannot initialise integers and reals)
        ])
    AC_LANG_POP()
    FFLAGS="$old_fflags"
    FCFLAGS="$old_fcflags"

    FFLAGS="-fbounds-check -Wall ${FFLAGS}"
    FCFLAGS="-fbounds-check -Wall -Wimplicit-interface -Wno-surprising ${FCFLAGS}"
    CFLAGS="-fbounds-check -Wall ${CFLAGS}"
    CXXFLAGS="-fbounds-check -Wall ${CXXFLAGS}"
    LDFLAGS="-rdynamic ${LDFLAGS}"
  elif test "$fcompiler" = "g95" ; then
    FFLAGS="-fbounds-check -ftrace=full ${FFLAGS}"
    FCFLAGS="-fbounds-check -ftrace=full ${FCFLAGS}"
  elif test "$fcompiler" = "sunf95" ; then
    FFLAGS="-C -ftrap=invalid -fpover ${FFLAGS}"
    FCFLAGS="-C -ftrap=invalid -fpover ${FCFLAGS}"
    CFLAGS="-ftrap=invalid ${CFLAGS}"
    CXXFLAGS="-ftrap=invalid ${CXXFLAGS}"
  fi

else
    AC_MSG_NOTICE([Setting optimisation flags for $F77])
    cat >> confdefs.h << EOF
#define NDEBUG 1
EOF
    OPTIMIZATION_FFLAGS="$OPTIMIZATION_FFLAGS -O3"
fi

FFLAGS="$FFLAGS $OPTIMIZATION_FFLAGS"
FCFLAGS="$FCFLAGS $OPTIMIZATION_FFLAGS"

if test "$FC" = "ifc" ; then
  FFLAGS="-implicitnone -132 -w95 $FFLAGS"
  FCFLAGS="-implicitnone -w95 $FCFLAGS"
fi

##########################################
# Are we using FEMDEM
##########################################
AC_ARG_WITH(femdem,
    [AC_HELP_STRING([--with-femdem@<:@=femdem_library@:>@],
        [specify the femdem path])])
if test -n "$with_femdem" ; then
  FLFEMDEM_PATH="${with_femdem}"
  LIB_FEMDEM="${with_femdem}""/lib/libd$FLFEMDEM.a"
  FEMDEM="yes"
  cat >> confdefs.h << EOF
#define USING_FEMDEM 1
EOF
else
  FLFEMDEM_PATH=""
  LIB_FEMDEM=""
  FEMDEM=""
fi
AC_SUBST(FLFEMDEM_PATH)
AC_SUBST(LIB_FEMDEM)
AC_SUBST(FEMDEM)

##########################################
# Are we using OASIS
##########################################
 
AC_ARG_WITH(psmile,
    [AC_HELP_STRING([--with-psmile@<:@=psmile_library@:>@],
    [specify the oasis4 path])])
if test -n "$with_psmile" ; then
  FLPSMILE_PATH="${with_psmile}"
  ENABLE_PSMILE="yes"
  cat >> confdefs.h << EOF
#define USING_PSMILE 1
EOF
else
  FLPSMILE_PATH=""
  ENABLE_PSMILE=""
fi
AC_SUBST(FLPSMILE_PATH)
AC_SUBST(ENABLE_PSMILE)

# save compiler name for libadapt before it's changed by MPI stuff
saved_FC="${FC}"
saved_CC="${CC}"
saved_F77="${F77}"

##########################################
# MPI
##########################################
check_for_mpich=""
check_for_lmpi=""

AC_LANG(C)

AC_ARG_VAR(MPICC, C compiler command for MPI programs)
AC_ARG_VAR(MPIF90, Fortran 90 compiler command for MPI programs)
AC_ARG_VAR(MPIF77, Fortran 77 compiler command for MPI programs)
AC_ARG_VAR(MPICXX, C++ compiler command for MPI programs)

AC_CHECK_PROGS(MPIF90, mpif90 mpf90, $FC, $PATH)
if test "$smart_fortran" = "yes" ; then
  MPIF77=$MPIF90
else
  AC_CHECK_PROGS(MPIF77, mpif77 mpf77,       $F77, $PATH)
fi
AC_CHECK_PROGS(MPICC,  mpicc mpcc,        $CC,  $PATH)
AC_CHECK_PROGS(MPICXX, mpicxx mpiCC mpCC, $CXX, $PATH)

F77=$MPIF77
FC=$MPIF90
CC=$MPICC
CXX=$MPICXX

AC_MSG_CHECKING([if we can compile and link without using -lmpi])
LIBS_bck="$LIBS"
LIBS=""
AC_TRY_LINK([
#include <mpi.h>
],[
int flag;
MPI_Initialized(&flag);
],[
AC_MSG_RESULT([yes])
LIBS="$LIBS_bck"
mpi="yes"
],[
AC_MSG_RESULT([no])
LIBS="$LIBS_bck"
check_for_lmpi="yes"
])

if test "$check_for_lmpi" = "yes" ; then
  AC_MSG_CHECKING([if we can compile and link using -lmpi])
  LIBS_bck="$LIBS"
  LIBS="-lmpi"
  AC_TRY_LINK([
  #include <mpi.h>
  ],[
  int flag;
  MPI_Initialized(&flag);
  ],[
  AC_MSG_RESULT([yes])
  LIBS="$LIBS $LIBS_bck"
  mpi="yes"
  ],[
  AC_MSG_RESULT([no])
  LIBS="$LIBS_bck"
  check_for_mpich="yes"
  ])
fi

if test "$check_for_mpich" = "yes" ; then
  AC_MSG_CHECKING([if we can compile and link using mpich libs])
  LIBS_bck="$LIBS"
  LIBS="$MPICH_LIBS"

  CPPFLAGS_bck="$CPPFLAGS"
  CPPFLAGS="$CPPFLAGS $MPICH_INCLUDES"

  AC_TRY_LINK([
  #include <mpi.h>
  ],[
  int flag;
  MPI_Initialized(&flag);
  ],[
  AC_MSG_RESULT([yes])
  LIBS="$LIBS $LIBS_bck"
  mpi="yes"
  ],[
  AC_MSG_RESULT([no])
  LIBS="$LIBS_bck"
  CPPFLAGS="$CPPFLAGS_bck"
  ])
fi

# should this go inside the "$mpi" = "yes" test below?
# i.e. only bother looking for pmpich++ if mpi is enabled...?
# shouldn't really do this, since it assumes we know the name
# of the mpich C++ library (but it can be different to below)
# Also, we only needed it when trying to link C++ with Fortran
# main -but that won't work reliably across compilers (gcc is ok)
#AC_CHECK_LIB(pmpich++,main,,)

if test "$mpi" = "yes" ; then
cat >> confdefs.h << EOF
#define HAVE_MPI 1
#define HAVE_MPI_CXX 1
#define _MPI_CPP_BINDINGS 1
EOF
  enable_mpi="yes"
else
  AC_MSG_ERROR([no MPI support found on system])
fi

# netCDF support
AC_LANG_PUSH([C])
AC_ARG_WITH(netcdf,
[AC_HELP_STRING([--with-netcdf@<:@=netcdf_ROOT@:>@],
[specify where to find lib/ and include/ for netCDF])])

# allow various synonyms to disable NetCDF
if test -z "$with_netcdf" ; then
  if test "$enable_netcdf" = no; then
    with_netcdf=no
  elif test "$enable_NetCDF" = no; then
    with_netcdf=no
  elif test "$with_NetCDF" != "yes" ; then
    if test -n "$with_NetCDF" ; then
      with_netcdf="$with_NetCDF"
    fi
  fi
fi
if test "$with_netcdf" != "no" ; then
  if test -n "$with_netcdf" ; then
    if test "$with_netcdf" != "yes" ; then
      LIBS="$LIBS -L$with_netcdf"
    fi
  fi
  AC_CHECK_LIB(netcdf, nc_create)
  if test $ac_cv_lib_netcdf_nc_create = yes; then
cat >> confdefs.h << EOF
#define HAVE_NETCDF 1
EOF
    LIBS="$LIBS -lnetcdf"
  fi
  # Check for separate fortran lib.
  AC_CHECK_LIB(netcdff, ncopn_)
  if test $ac_cv_lib_netcdff_ncopn_ = yes; then
    LIBS="$LIBS -lnetcdff"
  fi
fi

# Parmetis and zoltan
ACX_ParMetis([AC_MSG_NOTICE(["ParMetis found"])], [AC_MSG_WARN(["ParMetis not found"])])

AC_ARG_ENABLE(sam,
    [AC_HELP_STRING([--enable-sam],
	    [use sam rather than zoltan for adaptive load rebalancing])])
if test "$enable_sam" = "yes"; then
    HAVE_ZOLTAN=no
else
    if test "$with_zoltan" = no; then
        HAVE_ZOLTAN=no
        echo "Warning: zoltan disabled, using libsam instead"
    fi
    HAVE_ZOLTAN=yes
    zoltan=yes
    ACX_zoltan([AC_MSG_NOTICE(["Zoltan found"])], [AC_MSG_WARN(["Zoltan not found"])])
fi
AC_SUBST(HAVE_ZOLTAN)



HAVE_ADJOINT=no
CAN_USE_ADJOINT=yes
WANTS_ADJOINT=yes
if test "$USING_GFORTRAN" = "yes"; then # check gfortran version >= 4.5
  # test really is so retarded that it can't lexicographically compare strings
  if test "$GFORTRAN_4_5_OR_NEWER" != "yes"; then
    CAN_USE_ADJOINT=no
  fi
fi

if test "$with_adjoint" = no || test -z "$with_adjoint"; then
  WANTS_ADJOINT=no
fi

if test "$CAN_USE_ADJOINT" = "no" && test "$WANTS_ADJOINT" = "yes"; then
  echo "Wanted adjoint, but you need gcc > 4.5"
  exit 1
fi

if test "$with_adjoint" != "no"; then
  if test "$CAN_USE_ADJOINT" != "no"; then
    ACX_adjoint([AC_MSG_NOTICE(["libadjoint found"])], [AC_MSG_WARN(["libadjoint not found"])])
  fi
  if test "$HAVE_ADJOINT" = "no" && test "$WANTS_ADJOINT" = "yes"; then
    echo "Wanted adjoint, but couldn't find it"
    exit 1
  fi
fi
AC_SUBST(HAVE_ADJOINT)

AC_ARG_ENABLE(petsc-fortran-modules,
    [AC_HELP_STRING([--disable-petsc-fortran-modules],
    [By default fluidity tries to use fortran modules provided with petsc. Use --disable-petsc-fortran-modules if these are known to be not functional (e.g. compiled with different compiler version)])])
ACX_PETSc([AC_MSG_NOTICE(["PETSc found, enabling scalable solver"])], [AC_MSG_ERROR(["PETSc not found"])])
ACX_hypre([AC_MSG_NOTICE(["hypre found, enabling hypre preconditioners"])], [AC_MSG_WARN(["hypre not found"])])
CPPFLAGS="$CPPFLAGS -DHAVE_PETSC"
if test "$HAVE_PETSC_MODULES" == "1"; then
  CPPFLAGS="$CPPFLAGS -DHAVE_PETSC_MODULES"
fi
if test "$HAVE_HYPRE" == "1"; then
  CPPFLAGS="$CPPFLAGS -DHAVE_HYPRE"
fi

# Double precision.
AC_MSG_CHECKING(what voodoo is required to get 64 bit reals....)

AC_LANG_PUSH([Fortran])
old_fcflags="$FCFLAGS"
if test -z "$FORTRAN_REAL_8" ; then
   # gfortran
    FORTRAN_REAL_8="-fdefault-real-8 -fdefault-double-8"
    FCFLAGS="$FCFLAGS $FORTRAN_REAL_8"
    AC_RUN_IFELSE([AC_LANG_PROGRAM([], [
       implicit none
       real::a
       real*8::b

       if(kind(a).ne.kind(b)) then
          call exit(-1)
       end if
])],
        [AC_MSG_RESULT($FORTRAN_REAL_8)],
        [FCFLAGS="$old_fc_flags" ; FORTRAN_REAL_8=""])
    FCFLAGS="$old_fcflags"
fi
if test -z "$FORTRAN_REAL_8" ; then
   # Intel compiler suite
    FORTRAN_REAL_8="-r8"
    FCFLAGS="$FCFLAGS $FORTRAN_REAL_8"
    AC_RUN_IFELSE([AC_LANG_PROGRAM([], [
       implicit none
       real::a
       real*8::b

       if(kind(a).ne.kind(b)) then
          call exit(-1)
       end if
])],
        [AC_MSG_RESULT($FORTRAN_REAL_8)],
        [FCFLAGS="$old_fc_flags" ; FORTRAN_REAL_8=""])
    FCFLAGS="$old_fcflags"
fi
if test -z "$FORTRAN_REAL_8" ; then
   # SUN compiler suite
    FORTRAN_REAL_8="-xtypemap=real:64,double:64"
    FCFLAGS="$FCFLAGS $FORTRAN_REAL_8"
    AC_RUN_IFELSE([AC_LANG_PROGRAM([], [
       implicit none
       real::a
       real*8::b

       if(kind(a).ne.kind(b)) then
          call exit(-1)
       end if
])],
        [AC_MSG_RESULT($FORTRAN_REAL_8)],
        [FCFLAGS="$old_fc_flags" ; FORTRAN_REAL_8=""])
    FCFLAGS="$old_fcflags"
fi
if test -z "$FORTRAN_REAL_8" ; then
   # PGI compiler suite
    old_fcflags="$FCFLAGS"

    FORTRAN_REAL_8="-Mr8"
    FCFLAGS="$FCFLAGS $FORTRAN_REAL_8"
    AC_RUN_IFELSE([AC_LANG_PROGRAM([], [
       implicit none
       real::a
       real*8::b

       if(kind(a).ne.kind(b)) then
          call exit(-1)
       end if
])],
        [AC_MSG_RESULT($FORTRAN_REAL_8)],
        [FCFLAGS="$old_fc_flags" ; FORTRAN_REAL_8=""])
fi
if test -z "$FORTRAN_REAL_8" ; then
   AC_MSG_ERROR(none found)
fi

AC_LANG_POP([Fortran])

AC_ARG_ENABLE(dp,
[AC_HELP_STRING([--enable-dp[=flag]],
[compile with 64 bit floating point numbers (default)])])

if test "$enable_dp" = "no"
  then
  FORTRAN_REAL_8=""
  AC_MSG_NOTICE([Selecting 4 byte floating point numbers])
else
  AC_MSG_NOTICE([Turning on double 8 byte floating point numbers])
  if test -n "$enable_dp" ; then
    if test "$enable_dp" != "yes" ; then
      FORTRAN_REAL_8="$enable_dp"
    fi
  fi
  enable_dp="yes"

cat >> confdefs.h << EOF
#define DOUBLEP 1
EOF
  FFLAGS="$FFLAGS $FORTRAN_REAL_8"
  FCFLAGS="$FCFLAGS $FORTRAN_REAL_8"
fi

#####
#
LIBS="$LIBS -L./lib"

##############################################################
# Stream I/O
#
AC_LANG_PUSH([Fortran])

AC_MSG_CHECKING([for compiler stream I/O support.])

# Attempt to autodetect stream support.
AC_LINK_IFELSE(
  [
      program teststream

      open(unit = 0, access = "stream")

      end program teststream
  ],
  [
  stream_support=yes
  AC_MSG_RESULT([yes])
cat >> confdefs.h << EOF
#define STREAM_IO
EOF
  ],
  stream_support=no
  AC_MSG_RESULT([no])
cat >> confdefs.h << EOF
#undef STREAM_IO
EOF
  [
])

AC_LANG_POP(Fortran)

##############################################################
# Signal handling.
#
AC_LANG_PUSH([Fortran])

AC_MSG_CHECKING([for compiler signal handling support.])

# Attempt to autodetect signal support.
AC_LINK_IFELSE(
  [
      program testsignal

      integer :: result

      interface
       function handle_sigint(signum)
         integer :: handle_sigint
         integer, intent(in) :: signum
       end function handle_sigint
      end interface

      result=signal(1, handle_sigint, -1)
      end program testsignal

      function handle_sigint(signal)

      implicit none
      integer :: handle_sigint
      integer, intent(in) :: signal

      handle_sigint=0

      end function handle_sigint
  ],
  [
  signal_support=yes
  AC_MSG_RESULT([yes])
cat >> confdefs.h << EOF
#define SIGNAL
#define SIGNAL_HAVE_FLAG
EOF
  ],
  [
  AC_LINK_IFELSE(
  [
      program testsignal

      integer :: result

      interface
       function handle_sigint(signum)
         integer :: handle_sigint
         integer, intent(in) :: signum
       end function handle_sigint
      end interface

      result=signal(1, handle_sigint)
      end program testsignal

      function handle_sigint(signal)

      implicit none
      integer :: handle_sigint
      integer, intent(in) :: signal

      handle_sigint=0

      end function handle_sigint
  ],
  [
  signal_support=yes
  AC_MSG_RESULT([yes])
cat >> confdefs.h << EOF
#define SIGNAL
EOF
  ],
  signal_support=no
  AC_MSG_RESULT([no])
cat >> confdefs.h << EOF
#undef SIGNAL
#define SIGNAL_HAVE_FLAG
EOF
  [
])
])

AC_LANG_POP(Fortran)

##############################################################
# enable gprof profiling

AC_ARG_ENABLE(profiling,
[AC_HELP_STRING([--enable-profiling],
[enable gprof profiling])])

if test "$enable_profiling" = "yes" ; then
  PROFILING_FLAG="-pg"
  CPPFLAGS="-pg $CPPFLAGS"
  FFLAGS="-pg $FFLAGS"
  FCFLAGS="-pg $FCFLAGS"

  LINKER="$LINKER -pg"
  LIBS="$LIBS -pg"
else
  PROFILING_FLAG=""
fi
AC_SUBST(PROFILING_FLAG)

dnl Checks for typedefs, structures, and compiler characteristics.
# These tests were just giving too much trouble. Need to investigate further.
#AC_C_CONST
#AC_C_INLINE

AC_SUBST(FORTRAN_REAL_8)
AC_SUBST(OPTIMIZATION_FFLAGS)
AC_SUBST(LINKER)
AC_SUBST(FLLINKER)

dnl Specific f90 options
AC_SUBST(USE_CPP)

dnl Specific -D options
AC_SUBST(DEFINE_MPI)

dnl Checks for library functions.
if test "$smart_fortran" = "yes" ; then
  F77=$MPIF90
else
  F77=$MPIF77
fi
FC=$MPIF90
CC=$MPICC
CXX=$MPICXX
LINKER=$CXX

# Configure adaptivity
if test -d libadaptivity ; then
    AC_MSG_NOTICE([%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%])
    AC_MSG_NOTICE([Configuring libadaptivity])
    AC_MSG_NOTICE([%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%])

    pushd libadaptivity
    # We don't really want to use the same FFLAGS and LIBS as fluidity has
    # worked out, because they contain all sorts of fluidity-specific junk,
    # so we let libadapt's configure work out everything for itself
    # * EXCEPT * for the compiler, which we MUST make sure is the same as
    # fluidity's (except for MPI)
    if test "$enable_dp" = "yes" ; then     
        FC="${saved_FC}" F77="${saved_F77}" F90="${saved_F90}" LIBS="${env_libs}" \
            FFLAGS="${env_fflags} $PIC_FLAG $PROFILING_FLAG" FCFLAGS="${env_fcflags} $PIC_FLAG $PROFILING_FLAG" ./configure
        if test "$?" -ne "0"; then
          AC_MSG_ERROR([Configuration of libadaptivity has failed.])
          exit -1
        fi
    else
        FC="${saved_FC}" F77="${saved_F77}" F90="${saved_F90}" LIBS="${env_libs}" \
            FFLAGS="${env_fflags} $PIC_FLAG $PROFILING_FLAG" FCFLAGS="${env_fcflags} $PIC_FLAG $PROFILING_FLAG" ./configure --enable-dp=no
        if test "$?" -ne "0"; then
          AC_MSG_ERROR([Configuration of libadaptivity has failed.])
          exit -1
        fi
    fi
    popd
    BUILD_LIBADAPT="@cd libadaptivity; echo '    MAKE libadaptivity'; \$(MAKE) -s ; cp lib/libadaptivity.a ../lib/; cd .."
    CLEAN_LIBADAPT="@cd libadaptivity; echo '    CLEAN libadaptivity'; \$(MAKE) -s clean;cd .."
    AC_SUBST(BUILD_LIBADAPT)
    AC_SUBST(CLEAN_LIBADAPT)

cat >> confdefs.h << EOF
#define HAVE_ADAPTIVITY 1
EOF
else
    AC_MSG_ERROR("libadaptivity directory missing!!")
fi

# Configure libjudy
if test -d libjudy ; then
    AC_MSG_NOTICE([%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%])
    AC_MSG_NOTICE([Configuring libjudy])
    AC_MSG_NOTICE([%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%])

    cd libjudy
    FC="${saved_FC}" F77="${saved_F77}" F90="${saved_F90}" LIBS="${env_libs}" FCFLAGS="${env_fcflags}" FFLAGS="${env_fflags} $PIC_FLAG $PROFILING_FLAG" CC="${saved_CC}" ./configure --prefix=${PWD}/..
    if test "$?" -ne "0"; then
      AC_MSG_ERROR([Configuration of libjudy has failed.])
      exit -1
    fi
    cd ..
    AC_CHECK_SIZEOF(void *)
    if test "$ac_cv_sizeof_void_p" = 8; then
        JUDY_CFLAGS="-DJU_64BIT"
    else
        JUDY_CFLAGS="-UJU_64BIT"
    fi
    AC_SUBST(JUDY_CFLAGS)

    
cat >> confdefs.h << EOF
#define HAVE_JUDY 1
EOF
else
    AC_MSG_ERROR("libjudy directory missing!!")
fi

# Configure libspud
if test -d libspud ; then
    AC_MSG_NOTICE([%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%])
    AC_MSG_NOTICE([Configuring libspud])
    AC_MSG_NOTICE([%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%])

    # Check if we're on hector xe6
    if echo $(hostname) | grep -q "^hector-xe6"; then
        AC_MSG_NOTICE([Building on hector xe6; disabling shared libraries])
        SHFLAG=--disable-shared
        SPUD_ONLY="yes"
        FLLINKER=$CXX
    else
        FLLINKER=$FC
        SHFLAG=--enable-shared
    fi
    AC_SUBST(SPUD_ONLY)

    cd libspud
    # We don't really want to use the same FFLAGS and LIBS as fluidity has
    # worked out, because they contain all sorts of fluidity-specific junk,
    # so we let libadapt's configure work out everything for itself
    # * EXCEPT * for the compiler, which we MUST make sure is the same as
    # fluidity's (except for MPI)
    echo "${env_fcflags}"
    echo "${env_fflags}"
    FC="${saved_FC}" F77="${saved_F77}" F90="${saved_F90}" LIBS="${env_libs}" FCFLAGS="${env_fcflags}" FFLAGS="${env_fflags} $PIC_FLAG $PROFILING_FLAG" CFLAGS="${env_cflags} $PIC_FLAG $PROFILING_FLAG" CXXFLAGS="${env_cxxflags} $PIC_FLAG $PROFILING_FLAG" CPPFLAGS="${env_cppflags}" ./configure --prefix=${PWD}/.. ${SHFLAG}
    if test "$?" -ne "0"; then
      AC_MSG_ERROR([Configuration of libspud has failed.])
      exit -1
    fi
    cd ..
    
cat >> confdefs.h << EOF
#define HAVE_SPUD 1
EOF
else
    AC_MSG_ERROR("libspud directory missing!!")
fi

#*************SpatialIndex******
AC_ARG_ENABLE(spatialindex-version, 
[AC_HELP_STRING([--enable-spatialindex-version],
[Select required version of spatialindex library: 1.5])])

if test "x$enable_spatialindex_version" != "x"
then
  SPATIALINDEXDIR="spatialindex-$enable_spatialindex_version"
else
  enable_spatialindex_version="1.5"
  SPATIALINDEXDIR="spatialindex-1.5"
fi
AC_SUBST(SPATIALINDEXDIR)

AC_MSG_NOTICE([%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%])
AC_MSG_NOTICE([Configuring spatialindex])
AC_MSG_NOTICE([%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%])
cd $SPATIALINDEXDIR
if test "$enable_debugging" = "yes" ; then
   SPATIALINDEX_CONFIGURE_DEBUG_OPTION=--enable-debug=yes
fi
if test "$enable_profiling" = "yes" ; then
   SPATIALINDEX_CONFIGURE_PROF_OPTION=--enable-profiling=yes
fi
CC="${CC}" CXX="${CXX}" CFLAGS="${env_cflags}" CXXFLAGS="${env_cxxflags}" CPPFLAGS="-D_GNU_SOURCE" \
    LIBS="${env_lib}" ./configure --prefix=${PWD}/../ --disable-shared --without-pic \
    ${SPATIALINDEX_CONFIGURE_DEBUG_OPTION} ${SPATIALINDEX_CONFIGURE_PROF_OPTION}
if test "$?" -ne "0"; then
  AC_MSG_ERROR([Configuration of spatialindex has failed.])
  exit -1
fi
cd ../

#*************ARPACK*********
AC_LANG_PUSH([Fortran])
AC_ARG_WITH(arpack-lib,
[AC_HELP_STRING([--with-arpack-lib@<:@=<lib>@:>@],
[specify arpack library])])

if test -n "$with_arpack_lib" ; then
    AC_MSG_NOTICE([Linking against $with_arpack_lib])
    CPPFLAGS="-DHAVE_ARPACK $CPPFLAGS"
    LIBS="$with_arpack_lib $LIBS"
else
    AC_CHECK_LIB(arpack, dsaupd,,)
fi

vtk_header_relative_path=""
AC_ARG_ENABLE(vtk,[AC_HELP_STRING([--enable-vtk], [Only use to disable vtk])])
# various synonyms accepted for disabling VTK
if test "$with_vtk" = no ; then enable_vtk=no; fi
if test "$with_VTK" = no ; then enable_vtk=no; fi
if test "$enable_VTK" = no ; then enable_vtk=no; fi
if test "$enable_vtk" != "no" ; then
    AC_MSG_NOTICE([Checking for VTK automagic.])
    AC_LANG_PUSH([C++])
    AC_LINK_IFELSE(
	[AC_LANG_PROGRAM([[
#include <vtkVersion.h>
#include <vtkUnstructuredGrid.h>
                        ]],
		[[
                        vtkVersion::GetVTKMajorVersion();
                        vtkUnstructuredGrid *ug=vtkUnstructuredGrid::New();
                        ]])
            ],
	[
            AC_MSG_NOTICE([VTK automagic works.])
	    CPPFLAGS="$CPPFLAGS -DHAVE_VTK"
            VTK=yes
            search_for_vtk=no
            ],
	[
            AC_MSG_NOTICE([No VTK automagic])
	    search_for_vtk=yes	    
	])
    
    if test "x$search_for_vtk" == "xyes" ; then
        # Usually the location of the libraries is not a mystery. The
        # header files are another matter.
        AC_CHECK_LIB(dl, main)
        AC_CHECK_LIB(vtksys, main)
        AC_CHECK_LIB(vtkCommon, main, [], 
            [if test "x$VTK_LIBS" != "x" ; then
                LIBS="$LIBS -L$VTK_LIBS"
                unset ac_cv_lib_vtkCommon_main
                AC_CHECK_LIB(vtkCommon, main, [], 
                   [
                      AC_MSG_ERROR([Cannot find vtk installation.])
                      exit -1
                   ])
             else
                AC_MSG_ERROR([Cannot find vtk installation.])
                exit -1
             fi
            ])
        AC_CHECK_LIB(vtkzlib, main)
        AC_CHECK_LIB(vtkexpat, main)
        AC_CHECK_LIB(vtkFiltering, main)
        AC_CHECK_LIB(vtkGraphics, main)
        AC_CHECK_LIB(vtkIO, main)
        
        # check at the usual places:
        for i in $(ls -d /usr/include/vtk*) $VTK_INCLUDE; do
            if test -r $i/vtkCellData.h; then
                CPPFLAGS="-I$i $CPPFLAGS"
            fi
        done
        AC_CHECK_HEADER(vtkCellData.h,
            [CPPFLAGS="$CPPFLAGS -DHAVE_VTK=1"
                VTK=yes
                ],
            [AC_CHECK_HEADER(vtk-5.0/vtkCellData.h,
                    [CPPFLAGS="$CPPFLAGS -DHAVE_VTK=1"
                        VTK=yes
                        vtk_header_relative_path="vtk-5.0/"
                        ],
                    [       
                        AC_MSG_ERROR([Cannot find vtk installation.])
                        exit -1
                    ])
          ])
    fi
fi
cat > include/vtk.h <<EOF
#ifndef VTK_H
#define VTK_H

#ifdef HAVE_VTK
#include <${vtk_header_relative_path}vtkBMPWriter.h>
#include <${vtk_header_relative_path}vtkCellData.h>
#include <${vtk_header_relative_path}vtkCellDataToPointData.h>
#include <${vtk_header_relative_path}vtkCellDerivatives.h>
#include <${vtk_header_relative_path}vtkCell.h>
#include <${vtk_header_relative_path}vtkCellType.h>
#include <${vtk_header_relative_path}vtkClipDataSet.h>
#include <${vtk_header_relative_path}vtkContourGrid.h>
#include <${vtk_header_relative_path}vtkDataArray.h>
#include <${vtk_header_relative_path}vtkDataObject.h>
#include <${vtk_header_relative_path}vtkDataSet.h>
#include <${vtk_header_relative_path}vtkDataSetReader.h>
#include <${vtk_header_relative_path}vtkDoubleArray.h>
#include <${vtk_header_relative_path}vtkFloatArray.h>
#include <${vtk_header_relative_path}vtkGenericCell.h>
#include <${vtk_header_relative_path}vtkHexahedron.h>
#include <${vtk_header_relative_path}vtkIdList.h>
#include <${vtk_header_relative_path}vtkImageData.h>
#include <${vtk_header_relative_path}vtkIntArray.h>
#include <${vtk_header_relative_path}vtkPointData.h>
#include <${vtk_header_relative_path}vtkPointLocator.h>
#include <${vtk_header_relative_path}vtkPolyData.h>
#include <${vtk_header_relative_path}vtkShortArray.h>
#include <${vtk_header_relative_path}vtkStructuredGrid.h>
#include <${vtk_header_relative_path}vtkTetra.h>
#include <${vtk_header_relative_path}vtkUnsignedCharArray.h>
#include <${vtk_header_relative_path}vtkUnsignedIntArray.h>
#include <${vtk_header_relative_path}vtkUnstructuredGrid.h>
#include <${vtk_header_relative_path}vtkUnstructuredGridReader.h>
#include <${vtk_header_relative_path}vtkXMLImageDataWriter.h>
#include <${vtk_header_relative_path}vtkXMLPolyDataWriter.h>
#include <${vtk_header_relative_path}vtkXMLPUnstructuredGridReader.h>
#include <${vtk_header_relative_path}vtkXMLPUnstructuredGridWriter.h>
#include <${vtk_header_relative_path}vtkXMLStructuredGridWriter.h>
#include <${vtk_header_relative_path}vtkXMLUnstructuredGridReader.h>
#include <${vtk_header_relative_path}vtkXMLUnstructuredGridWriter.h>
#include <${vtk_header_relative_path}vtkZLibDataCompressor.h>

#ifndef vtkFloatingPointType
#define vtkFloatingPointType vtkFloatingPointType
typedef float vtkFloatingPointType;
#endif

#endif
#endif
EOF
cp include/vtk.h libvtkfortran/include/

AC_SUBST(ARFLAGS)

AC_SUBST(MODINC_FLAG)

# It appears this is not good practice but...go sue me
#cat confdefs.h | grep -v std > include/confdefs.h    <-- see below...
cat confdefs.h | grep DOUBLEP > libvtkfortran/include/confdefs.h
cat confdefs.h | grep F77_FUNC >> libvtkfortran/include/confdefs.h
cat confdefs.h | grep VTK >> libvtkfortran/include/confdefs.h
cat confdefs.h | grep MPI >> libvtkfortran/include/confdefs.h
cat confdefs.h | grep "^#[dua][enl][fdl][ieo][nfw]" > include/confdefs.h

AC_ARG_ENABLE(2d-adaptivity,
[AC_HELP_STRING([--enable-2d-adaptivity],
[Link against 2D adaptivity library (GPL license)])])

if test "$enable_2d_adaptivity" = "yes"; then
  echo "#define HAVE_MBA_2D 1" >> include/confdefs.h
  LIBS="-lmba2d $LIBS"
  MBA2D="yes"
  AC_SUBST(MBA2D)
fi

AC_ARG_ENABLE(mba3d,
[AC_HELP_STRING([--enable-mba3d],
[Enabled libmba3d 3D adaptivity library])])

if test "$enable_mba3d" = "yes"; then
  echo "#define HAVE_MBA_3D 1" >> include/confdefs.h
  LIBS="$LIBS -lmba3d"
  MBA3D="yes"
  AC_SUBST(MBA3D)
fi

AC_ARG_ENABLE(algencan,
[AC_HELP_STRING([--enable-algencan],
[Enabled algencan optimisation library])])

if test "$enable_algencan" = "yes"; then
  echo "#define HAVE_ALGENCAN 1" >> include/confdefs.h
  LIBS="$LIBS -lalgencan"
  ALGENCAN="yes"
  AC_SUBST(ALGENCAN)
fi

AC_ARG_ENABLE(memory_stats,
[AC_HELP_STRING([--enable-memory-stats],
[Enable memory statistics])])

if test "$enable_debugging" = "yes" ; then
  if test "$enable_memory_stats" != "no"; then
    echo "#define HAVE_MEMORY_STATS 1" >> include/confdefs.h
    MEMORY_STATS="yes"
    AC_SUBST(MEMORY_STATS)
  fi
else
  if test "$enable_memory_stats" = "yes"; then
    echo "#define HAVE_MEMORY_STATS 1" >> include/confdefs.h
    MEMORY_STATS="yes"
    AC_SUBST(MEMORY_STATS)
  fi
fi

# Hack for CX1. The zoltan libs (scotch, parmetis, etc) need to apepar on the end of the compile
# command or all sorts of badness happens (libraries not being found, despite being in the path).
# ZOLTAN_DEPS should be empty on other machine and will be set in the cx1-module file. See wiki.
LIBS="$LIBS $ZOLTAN_DEPS"

AC_ARG_ENABLE(hyperlight,
[AC_HELP_STRING([--enable-hyperlight],
[Enable Hyperlight solar irradiance model])])

if test "$enable_hyperlight" = "yes"; then
  AC_CHECK_FILES([hyperlight/Hyperlight.h hyperlight/Hyperlight.cpp hyperlight/Sky.h hyperlight/Sky.cpp hyperlight/Iop.h hyperlight/Iop.cpp],[
    echo "#define HAVE_HYPERLIGHT 1" >> include/confdefs.h
    HYPERLIGHT="yes"
    AC_SUBST(HYPERLIGHT)
  ],[
    AC_MSG_ERROR([Hyperlight was enabled, but no source files found. Please contact Michael Lange (michael.lange@imperial.ac.uk) to get the necessary files for this module.])
    exit -1
  ])
fi

AC_OUTPUT(Makefile
          debug/Makefile
          bathymetry/Makefile
          ocean_forcing/Makefile ocean_forcing/tests/Makefile
          sediments/Makefile
          hyperlight/Makefile
          femtools/Makefile femtools/tests/Makefile
          forward_interfaces/Makefile
          horizontal_adaptivity/Makefile horizontal_adaptivity/tests/Makefile
          preprocessor/Makefile
          error_measures/Makefile error_measures/tests/Makefile
          parameterisation/Makefile parameterisation/tests/Makefile
	  fldecomp/Makefile
          assemble/Makefile assemble/tests/Makefile
          diagnostics/Makefile
          main/Makefile
          tools/Makefile
          python/setup.py
          adjoint/Makefile
          adjoint/tests/Makefile
          climatology/Makefile
          libmba2d/Makefile
      	  libmba3d/Makefile
          libjudy/Makefile
          libjudy/src/Makefile
          libjudy/src/JudyCommon/Makefile
          libjudy/src/Judy1/Makefile
          libjudy/src/JudyL/Makefile
          libjudy/src/JudySL/Makefile
          libjudy/src/JudyHS/Makefile
      	  libalgencan/Makefile
          libwm/Makefile
          libvtkfortran/Makefile
          schemas/flml
	  reduced_modelling/Makefile)