[r-cran-matching] 01/02: New upstream version 4.9-2

Andreas Tille tille at debian.org
Mon Nov 27 16:53:39 UTC 2017


This is an automated email from the git hooks/post-receive script.

tille pushed a commit to branch master
in repository r-cran-matching.

commit e8f053b68f499fe9bff31bc8e368d85a3af66ea5
Author: Andreas Tille <tille at debian.org>
Date:   Mon Nov 27 17:53:07 2017 +0100

    New upstream version 4.9-2
---
 ChangeLog                     |  303 +++
 DESCRIPTION                   |   19 +
 MD5                           |   66 +
 NAMESPACE                     |   15 +
 R/AI.R                        |   53 +
 R/GenBalance.R                |  332 +++
 R/GenMatching.R               | 1030 +++++++++
 R/Matchby.R                   |  265 +++
 R/Matching.R                  | 3051 +++++++++++++++++++++++++
 cleanup                       |   22 +
 configure                     | 4188 ++++++++++++++++++++++++++++++++++
 configure.ac                  |  195 ++
 data/GerberGreenImai.rda      |  Bin 0 -> 96408 bytes
 data/lalonde.rda              |  Bin 0 -> 5853 bytes
 demo/00Index                  |    6 +
 demo/AbadieImbens.R           |  118 +
 demo/DehejiaWahba.R           |   37 +
 demo/GerberGreenImai.R        |   31 +
 inst/CITATION                 |   55 +
 inst/extras/ICC               |    6 +
 inst/extras/Makevars.win.gcc3 |    3 +
 inst/extras/Makevars.win.gcc4 |    3 +
 inst/extras/cblas.h           |   16 +
 inst/extras/cblas_dasum.c     |   26 +
 inst/extras/cblas_dgemm.c     |  123 +
 inst/extras/cblas_dscal.c     |   24 +
 inst/extras/cblas_dsymm.c     |  116 +
 inst/extras/cblas_dtrmm.c     |  161 ++
 inst/extras/configure.old     |   56 +
 inst/extras/configure.win     |    7 +
 inst/extras/makefile.cblas    |   36 +
 inst/extras/makefile.icc      |   44 +
 inst/extras/makefile.in       |   36 +
 inst/extras/makefile.osx.in   |   36 +
 inst/extras/makefile.sun      |   44 +
 inst/extras/malloc.c          | 5061 +++++++++++++++++++++++++++++++++++++++++
 man/GenMatch.Rd               |  438 ++++
 man/GerberGreenImai.Rd        |   83 +
 man/Match.Rd                  |  379 +++
 man/MatchBalance.Rd           |  207 ++
 man/Matchby.Rd                |  277 +++
 man/balanceUV.Rd              |  116 +
 man/ks.boot.Rd                |  101 +
 man/lalonde.Rd                |   52 +
 man/qqstats.Rd                |  104 +
 man/summary.Match.Rd          |   32 +
 man/summary.Matchby.Rd        |   30 +
 man/summary.balanceUV.Rd      |   31 +
 man/summary.ks.boot.Rd        |   31 +
 src/Makevars.in               |    3 +
 src/Makevars.win              |    3 +
 src/cblas.h                   |   38 +
 src/cblas_dasum.c             |   48 +
 src/cblas_dgemm.c             |  144 ++
 src/cblas_dscal.c             |   45 +
 src/matching.cc               | 2898 +++++++++++++++++++++++
 src/matching.h                |   27 +
 src/scythematrix.cc           | 2639 +++++++++++++++++++++
 src/scythematrix.h            | 1231 ++++++++++
 tests/AbadieImbens.R          |  119 +
 tests/AbadieImbens.Rout.save  |  351 +++
 tests/DehejiaWahba.R          |   47 +
 tests/DehejiaWahba.Rout.save  |  354 +++
 tests/GenMatch.R              |   46 +
 tests/GenMatch.Rout.save      |  945 ++++++++
 tests/Matchby.R               |   18 +
 tests/Matchby.Rout.save       |   80 +
 67 files changed, 26501 insertions(+)

diff --git a/ChangeLog b/ChangeLog
new file mode 100644
index 0000000..d38d70b
--- /dev/null
+++ b/ChangeLog
@@ -0,0 +1,303 @@
+Change Log for public releases:
+
+2015-12-25 Version: 4.9-2
+	* Minor version number increased because of duplicate posting on
+	CRAN.
+
+2015-12-25 Version: 4.9-1
+	* NAMESPACES: Improve imports
+
+2015-07-18 Version: 4.9-0
+	* Matching.R: balance(): the standardized pooled difference now
+	uses the pooled variance as in Rosenbaum and Rubin (1985), instead
+	of the total variance. This is not printed by default by
+	MatchBalance(). One can obtain this statistic from directly
+	calling balanceUV().
+
+2013-06-28 Version: 4.8-3.4
+	* configure: Check for compilers before AC_PROG_CC
+	* configure.ac: Check for compilers before AC_PROG_CC
+	* matching.cc: Switch to using internal blas headers on OS X
+	* DESCRIPTION: Updated usage of 'Depends' and 'Suggests'
+	* GenMatching.R: Include require("rgenoud") as the package is now suggested, but not required.
+
+2013-06-28 Version: 4.8-3.1
+	* tests: suppress message on load in the test .R files
+
+2013-06-28 Version: 4.8-3
+	* GenMatching.R: now uses the 'parallel' package instead of the
+	deprecated package 'snow'
+
+2013-04-26 Version: 4.8-2
+	* Makevars.win: removes the -ffriend-injection option
+	* configure.ac: removes the -ffriend-injection option
+	* matching.cc: fully resolves calls to seqa, ones, zeros, and
+	* scythematrix.cc: fully resolves calls to seqa, ones, zeros
+	* scythematrix.h: makes seqa, ones, zeros static parentheses
+	around evalution to move ambiguity
+
+2013-02-16 Version: 4.8-1.2
+	* GenMatching.R: removes assignment to .GlobalEnv in GENclusterExport.
+
+2013-02-15 Version: 4.8-1.1
+	Only trivial internal code changes. Changed all as.real() to as.double(), as as.real() no longer work
+	in R-devel.
+
+2012-09-27 Version: 4.8-1
+	Minor update to resolve issues with API changes in R-devel
+
+	* Matching.R: EISPACK = TRUE now depracated for eigen(). See we
+	only look at the values anyways, we now revert to the R default,
+	which is EISPACK=FALSE.
+	Changed Mks.test() to handle warnings for ties in
+	the ks.test. Removes call to .C in the base 'stat' package.
+	* GenMatching.R: EISPACK = FALSE now for eigen().  Internal
+	function Mks.test no longer takes the MC argument
+	* GenBalance.R: Internal function Mks.test no longer takes the MC argument
+
+2012-01-19 Version: 4.8-0
+
+	* Makevars.win.gcc4: no more --ffast-math because it conflicts with -pedantic on some platforms
+	* Makevars.win: no more --ffast-math
+	* configure.ac: no more -ffast-math, and update test code to #include <cmath> and RC(XX)FLAGS
+	* configure: updated as above
+	* matching.cc: switch exit() to error() and fprintf to Rpintf, now using packageStartupMessage .onAttach
+	* scythematrix.cc: switch exit() to error() and fprintf to Rpintf
+	* scythematrix.h: switch exit() to error() and fprintf to Rpintf
+
+Version 4.7-14
+
+Minor update. Corrected citation information in .onAttach.
+
+Version 4.7-13
+
+Minor update. Updated references in CITATIONS an in *Rd files.
+
+Version 4.7-12
+
+Minor update. CITATION file for Journal of Statistical Software
+
+Version 4.7-11
+
+Minor update. ks.boot() now conducts alternative tests like ks.test()
+
+Version 4.7-10
+
+Minor update. GenMatch() now checks to make sure that the treatment
+indicator (the 'Tr' object) contains both treated and control
+observations. If not, GenMatch() stops and returns an error message.
+
+Version 4.7-9
+
+Minor update. Made calls to functions in the standard C++ library
+explicit. The Sun Studio C++ compiler required this change.
+
+Version 4.7-8
+
+Minor update. The Sun Studio C++ compiler on Solaris required adding #include <stdlib.h>.
+
+Version 4.7-7
+
+Minor update. Changed print format to conform to ISO C++ in the display() function in 
+matching.cc:2883.
+
+Removed the empty \details{} section in GenMatch.Rd.
+
+Version 4.7-6
+
+Added suggested package "rbounds: Perform Rosenbaum bounds sensitivity tests for matched data"
+
+Corrected overloading ambiguity between "sqrt(double)" and "std::sqrt(float)"
+that prevented building on Solaris.
+
+Version 4.7-5
+
+Minor update.  Released in order to be compatible with R-devel
+(Windows).
+
+Version 4.7-3
+
+Released in order to be compatible with R-2.8.  Also removed the
+balanceMV() function.
+
+Version 4.6-2
+
+Minor release. Explicitly declares header files as required by gcc
+4.3. Improves warning message when Y==NULL and BiasAdjust==TRUE.
+
+Version 4.6-1
+
+Minor release. Corrected documentation, functionality and error
+handling for user provided fitness function ('fit.func') in the
+GenMatch function.  Provided S3 methods for printing summary functions
+to improving printing.
+
+Version 4.5-3
+
+Minor release.  Improved debugging for input parameters for Match(),
+GenMatch() and Matchby().  Improves checking for if
+length(Tr)!=length(Y) etc.  And coerces Tr and Y by as.real instead of
+as.matrix.
+
+Version 4.5-2
+
+MAJOR RELEASE with new features.  
+
+Matchby() is now much faster and can now calculate Abadie-Imbens SEs
+(via the AI=TRUE option) and the function returns "index.treated" and
+"index.control", and it can be used with MatchBalance().
+
+Var.calc estimates are now an order of magnitude faster in Match()
+because they have been moved to C++. And they can now be estimated via
+Matchby() which makes them even faster.
+
+We now have a configure.win to deal with gcc4 (R-develop) and gcc3
+(R-release) as of R-2.5x.
+
+4.4-14
+
+Version for the Journal of Statistical Software article.  Improved
+documentation, comments in the C++ code, added test cases to so
+regression tests are now done in the package itself (via R CMD check),
+and included makefiles in "extras" for icc and Sun Studio.  Code now
+works with Sun Studio.
+
+4.4.10, 4.4.7
+
+Improvements in warning messsages and documentation
+
+4.4.6
+
+Major speed improvements.  We no longer do any calculations for
+observations in the same treatment group.  No longer using BLAS if the
+weight matrix is diagonal.  BLAS, in this case, were slower than
+carefully written loops which gcc (and icc) can optimize.
+
+
+4.4-1
+
+MatchBalance now actually returns all of its results as a list so
+there is no need to call balanceUV() directly.
+
+4.4.0
+
+Major speed improvements on all plaforms for both Match() and
+GenMatch().  BLAS are now more selectively used: level 1 blas instead
+of dgemm and no use of BLAS on OS X for many operations (OS X BLAS
+were slower because of the OS X malloc problem).
+
+4.3-1
+
+GenMatch() now prints warnings when there are no valid matches, just like Match() 
+
+4.2-6
+
+Corrects minor warning messages generated by R CMD check with R-rc_2007-04-19_r41248.
+
+4.2-5
+
+Warning that Bias Adjustment cannot be done if replace=FALSE or ties=FALSE
+
+4.2-4
+
+Minor change.  In MatchBalance: check if options("na.action") is equal
+to na.omit, na.exclude or na.fail moved to after we know that there
+are NAs.
+
+4.2-3
+
+MatchBalance prints loud warning messages when missing values are
+inputed, but it will not, by default, stop.  IT IS HIGHLY RECOMMENDED
+THAT YOU TEST IF THE MISSING VALUES ARE BALANCED INSTEAD OF JUST
+DELETING THEM.
+
+ks.boot is now faster (uses a fast version of ks.test).  And the cut
+point for the test is now the length of treated category.
+
+Version 4.1-7
+
+Documentation has been updated to be consistent with the paper
+introducing the package: "Multivariate and Propensity Score Matching
+Software with Automated Balance Optimization: The Matching package for
+R".  See http://sekhon.berkeley.edu/papers/MatchingJSS.pdf
+
+Version 4.1-3
+
+Added the "CommonSupport" option to Match and GenMatch.  Made sure to
+note in documentation that people should use the caliper option
+instead.
+
+GenMatch now defaults to using floating point weights instead of
+integers---data.type.integer=FALSE in GenMatch is now the default!
+
+Removed #include <sstream> in sycthmatrix.h. Not needed and causes
+problem in pre 3.3 gcc 
+
+Version 4.0-9
+
+
+The Match() function is *vastly* faster for large datasets with many
+ties.  At the expense of slightly more memory, the Match() function is
+now several orders of magnitude faster for such problems.  For
+example, one dataset with 30,000 observations results in 6 million
+matches due to ties.  For this problem, Match() now takes 60 seconds
+instead of an hour (on an Opteron 254).  The speedup occurs because
+rbind usage has been all but eliminated. And memcpy is now effectively
+used to copy memory objects instead of loops (the former is better
+optimized by compilers).
+
+updated help on nboots in GenMatch
+
+Version 4.0-6
+
+Match() and GenMatch now support the "ties" option.  The default
+behavior of the "replace" option has also been changed.
+
+If the dataset is large and there are many ties between potential
+matches, setting ties=FALSE often results in a large speedup with
+negligible bias.  
+
+Specifically, the ties option controls whether ties should be handled
+deterministically.  By default ties==TRUE. If, for example, one
+treated observation matches more than one control observation, the
+matched dataset will include the multiple matched control observations
+and the matched data will be weighted to reflect the multiple matches.
+The sum of the weighted observations will still equal the original
+number of observations. If ties==FALSE, ties will be randomly broken.
+This in general is not a good idea because the variance of Y will be
+underestimated (Abadie and Imbens 2005).  But if the dataset is large
+and there are many ties between potential matches, setting ties=FALSE
+often results in a large speedup with negligible bias. Whether two
+potential matches are close enough to be considered tied, is
+controlled by the distance.tolerance option.
+
+NOTE ties=FALSE in Matchby by default while ties=TRUE in Match and GenMatch.
+
+added warnings if nrow(BalanceMatrix) != length(Tr), or nrow(X) !=
+length(Tr).  Also checks for the dimensionality of V and Z.
+
+3.8-2: 
+
+Added index.dropped to the return object list for Match().  This is a
+vector containing the observation numbers from the original data which
+were dropped (if any) in the matched dataset because of various
+options such as caliper and exact.  If no observations
+were dropped, this index will be NULL.
+
+3.7-3:
+Fixed some typos in help pages.
+add standard packages to DESCRIPTION
+
+3.7-1:
+
+The intelligence of the install script generated by configure.ac has
+been improved.  In now checks if the compiler supports the following
+group of arguments separately:
+
+MYCXXFLAGS0="-O3"
+MYCXXFLAGS1="-finline-functions -ffast-math -funroll-loops -fexpensive-optimizations"
+MYCXXFLAGS2="-funswitch-loops -fgcse-after-reload -fstrict-aliasing -freorder-blocks -fsched-interblock"
+
+The last set are not supported on pre 4.0 gcc compilers (unless they
+have been backported).
+
diff --git a/DESCRIPTION b/DESCRIPTION
new file mode 100644
index 0000000..ab00420
--- /dev/null
+++ b/DESCRIPTION
@@ -0,0 +1,19 @@
+Package: Matching
+Version: 4.9-2
+Date: 2015-12-25
+Title: Multivariate and Propensity Score Matching with Balance
+        Optimization
+Author: Jasjeet Singh Sekhon <sekhon at berkeley.edu>
+Maintainer: Jasjeet Singh Sekhon <sekhon at berkeley.edu>
+Description: Provides functions for multivariate and propensity score matching 
+             and for finding optimal balance based on a genetic search algorithm. 
+             A variety of univariate and multivariate metrics to
+             determine if balance has been obtained are also provided.
+Depends: R (>= 2.6.0), MASS (>= 7.2-1), graphics, grDevices, stats
+Suggests: parallel, rgenoud (>= 2.12), rbounds
+License: GPL-3
+URL: http://sekhon.berkeley.edu/matching
+NeedsCompilation: yes
+Packaged: 2015-12-25 09:29:41 UTC; sekhon
+Repository: CRAN
+Date/Publication: 2015-12-25 14:31:37
diff --git a/MD5 b/MD5
new file mode 100644
index 0000000..bf76392
--- /dev/null
+++ b/MD5
@@ -0,0 +1,66 @@
+ec6b5829dd4e7882beaba7c47b0d4796 *ChangeLog
+69e896f1333dba86833f94389158ffd6 *DESCRIPTION
+24cb9de2a7b3dc9e871158fe0a821482 *NAMESPACE
+1f2509f5a21b31e54aaae8e306e0c223 *R/AI.R
+3258819f0958393d804c697806f63597 *R/GenBalance.R
+296198264207d0a8d1121d03a351fc99 *R/GenMatching.R
+afefd28590c34bfd9a79e4911946dcdd *R/Matchby.R
+13aa4e0aa2aa52009ddbc177cfd605e4 *R/Matching.R
+cc252abeaa229f4a7383795668edaefa *cleanup
+cdbd4293f5310cb1fdcb9562d92a70ff *configure
+f0eb37f10acce35525dde0f0f77cdaae *configure.ac
+e9c387ae58b8769a9227428e79d429d3 *data/GerberGreenImai.rda
+a828d7c18cd6973954a10765fa448185 *data/lalonde.rda
+649a1baa0133c3c29e17832bc9006b30 *demo/00Index
+d884e68217519144b6f45e0bbe39f1cf *demo/AbadieImbens.R
+611fc9c09770b3883fda2899fdb48f22 *demo/DehejiaWahba.R
+a80aed093ad9f83a31eef7cf0d98042f *demo/GerberGreenImai.R
+f6a6beada2fecf03010759fd3188012c *inst/CITATION
+89787966f25136da01087cfd235e0fcc *inst/extras/ICC
+ef61b9e05d4127d1686ef30fd42d7d1e *inst/extras/Makevars.win.gcc3
+33d513feaa81a98ec9df542141eca8ac *inst/extras/Makevars.win.gcc4
+2f51b4557184c8f9f7a4e7a4975debbe *inst/extras/cblas.h
+a8a179422cf085fe3634340c38289ef0 *inst/extras/cblas_dasum.c
+c11351715f346ab824c44b68c2d61db0 *inst/extras/cblas_dgemm.c
+54bd920a942adba3f8b943487c15be0e *inst/extras/cblas_dscal.c
+2e6a0e8165644e8f6f417c56a65a4441 *inst/extras/cblas_dsymm.c
+93a40cf07ffa7b69401380d401503582 *inst/extras/cblas_dtrmm.c
+8cdedc289281375fdef3737b7a83708c *inst/extras/configure.old
+fdc935add54b06512b586419bd9d6c98 *inst/extras/configure.win
+c4a8643c9101538f50a63c05014de2a0 *inst/extras/makefile.cblas
+c3c3703a877c4f33bee259a92c9b18e8 *inst/extras/makefile.icc
+36af70bb62a71517a3af88de183531ca *inst/extras/makefile.in
+387d63291ef9f32e63ee3fecdfae3885 *inst/extras/makefile.osx.in
+6d92c6dd98b5b21fe18ea05344cdd19f *inst/extras/makefile.sun
+9166b6b448695e22da52fd8ec3121d6f *inst/extras/malloc.c
+a47294bbd8e885fa754e72ea4dc096c9 *man/GenMatch.Rd
+d3481e32ea95bb214412ded663cc6c77 *man/GerberGreenImai.Rd
+062b58325c67a8eee02d4906c5b2d443 *man/Match.Rd
+db9f332fb98cfdf54b1ed0fcbf6d0f9e *man/MatchBalance.Rd
+0128d7b3324258e7fecdcc834656a065 *man/Matchby.Rd
+b018e6e4a5c45637af979c2a0efacd32 *man/balanceUV.Rd
+9961469a9f66f782b30a366f286189e8 *man/ks.boot.Rd
+369f9a6c97c7d29f7d62afae11c932cf *man/lalonde.Rd
+d0f58d24f8c19215051b4ad861e4df41 *man/qqstats.Rd
+33671f2b88627bb8190ad73e8928173c *man/summary.Match.Rd
+fca6afc7bb6a3ee81db3337ed7940c8c *man/summary.Matchby.Rd
+a7b537fbd89ff83d66f273fb39a8077c *man/summary.balanceUV.Rd
+1b330b24e5c23e6a0a86418d2d3db191 *man/summary.ks.boot.Rd
+d30deeabb02e67f1259becc33bc4bebb *src/Makevars.in
+add4afc432903b0b1af9c8a67e1fd6a9 *src/Makevars.win
+88f94cce41e981baa6d9012b27de4745 *src/cblas.h
+23412ef7cadbc99d334bccb681475c22 *src/cblas_dasum.c
+5144f435129eeaa64ba77a2e6df79e9b *src/cblas_dgemm.c
+ff53079d13f29acecc79eae9f0c60c66 *src/cblas_dscal.c
+db94d449957d9ba946d5982c9383f0c5 *src/matching.cc
+7151f4226f9af6c3194b3cfe2f7711df *src/matching.h
+8a602fa692a839b4c4911709a2d5d82a *src/scythematrix.cc
+d87a64aece7c9f3d29ef9abfff89caf5 *src/scythematrix.h
+285d577d455850cc6629f4be93b2b86b *tests/AbadieImbens.R
+03375e3425adc5c43ee6bd932311b77b *tests/AbadieImbens.Rout.save
+c5f80f1f6362f122bac3c3567c5a63d7 *tests/DehejiaWahba.R
+5d3a8c271f87bdbbf03969c392385c1a *tests/DehejiaWahba.Rout.save
+f590b354b221d87af5d99a5ad5efcda3 *tests/GenMatch.R
+cbed33f3da57ab0c81399c750c36cd2b *tests/GenMatch.Rout.save
+197eae32e8bb3ada8fca780bc56da52e *tests/Matchby.R
+88dcb4e30893166439b110bb231ad4c7 *tests/Matchby.Rout.save
diff --git a/NAMESPACE b/NAMESPACE
new file mode 100644
index 0000000..05d3007
--- /dev/null
+++ b/NAMESPACE
@@ -0,0 +1,15 @@
+import(MASS)
+importFrom("stats", "approx", "complete.cases", "ecdf", "ks.test",
+           "median", "model.frame", "model.matrix", "model.response",
+           "na.pass", "pchisq", "pnorm", "pt", "sd", "terms", "var")
+importFrom("utils", "packageDescription")
+useDynLib(Matching)
+export(balanceUV, ks.boot, Match, Matchby, MatchBalance, qqstats, summary.ks.boot, summary.Match, GenMatch, print.summary.Match, print.summary.ks.boot, print.summary.Matchby)
+S3method(summary, balanceUV)
+S3method(summary, ks.boot)
+S3method(summary, Match)
+S3method(summary, Matchby)
+
+S3method(print, summary.Match)
+S3method(print, summary.ks.boot)
+S3method(print, summary.Matchby)
diff --git a/R/AI.R b/R/AI.R
new file mode 100644
index 0000000..f1fa721
--- /dev/null
+++ b/R/AI.R
@@ -0,0 +1,53 @@
+#This function returns the homogeneous AI SE.
+#This standalone function only works for ATT, and no weights
+#The Match() function includes the version which works for everything
+#  and which calculates heterogeneous variance estimates
+
+AIse <- function(Y, Tr, index.treated, index.control, weights, est=NULL)
+  {
+    N <- length(Y)
+
+    if(is.null(est))
+      {
+        est <- sum(Y[index.treated]*weights)/sum(weights)-
+          sum(Y[index.control]*weights)/sum(weights)
+      } else{
+        est <- as.double(est)
+      }
+
+#    ret <- est.func(N=N, All=0, Tr=Tr,
+#                    indx=cbind(index.treated,index.control,weights),
+#                    weight=rep(1,N),
+#                    BiasAdj=FALSE, Kz=NULL)
+
+    ret <- .Call("EstFuncC", as.integer(N), as.integer(0), as.integer(length(index.treated)),
+                 as.double(Y), as.double(Tr),
+                 as.double(rep(1,N)), as.double(cbind(index.treated,index.control,weights)),
+                 PACKAGE="Matching")
+
+#    YCAUS <- ret$YCAUS
+#    Kcount <- ret$Kcount
+#    KKcount <- ret$KKcount
+
+    YCAUS <- ret[,1]
+    Kcount <- ret[,2]
+    KKcount <- ret[,3]    
+
+    Yt <- Y[index.treated]
+    Yc <- Y[index.control]
+    Tau <- Yt - Yc
+
+    eps <- Tau - est
+    eps.sq <- eps*eps
+    Sigs <- 0.5 * matrix(1, N, 1) %*% (t(eps.sq) %*% weights)/sum(weights)
+
+    SN <- sum(Tr)
+    var.pop=sum((Sigs*((1-Tr)*Kcount*Kcount-(1-Tr)*KKcount))/(SN*SN))
+    
+    dvar.pop <- sum(Tr*(YCAUS-est)*(YCAUS-est))/(SN*SN)
+    
+    var <- var.pop + dvar.pop
+    
+    se <- sqrt(var)
+    return(se)
+  }
diff --git a/R/GenBalance.R b/R/GenBalance.R
new file mode 100644
index 0000000..9274a47
--- /dev/null
+++ b/R/GenBalance.R
@@ -0,0 +1,332 @@
+MATCHpt <- function(q, df, ...)
+  {
+    #work around for strange windows-R bug found by example(GenMatch) when MatchBalance is hit.
+    #don't know how general it is so let's try to work around it
+    ret = suppressWarnings(pt(q,df, ...))
+    
+    if (is.na(ret)) {
+      ret   <- pt(q, df, ...)
+      if(is.na(ret))
+        warning("pt() generated NaN. q:",q," df:",df,"\n")
+    }
+    
+    return(ret)
+  } #end of MATCHpt
+
+Mt.test.pvalue  <- function(Tr, Co, weights)
+  {
+    v1  <- Tr-Co
+    estimate  <- sum(v1*weights)/sum(weights)
+    var1  <- sum( ((v1-estimate)^2)*weights )/( sum(weights)*sum(weights) )
+
+    if (estimate==0 & var1==0)
+      {
+        return(1)
+      }
+    
+    statistic  <- estimate/sqrt(var1)
+#    p.value    <- (1-pnorm(abs(statistic)))*2
+    p.value    <- (1-MATCHpt(abs(statistic), df=sum(weights)-1))*2
+
+    return(p.value)
+  } #end of Mt.test.pvalue
+
+Mt.test.unpaired.pvalue  <- function(Tr, Co, weights)
+  {
+    obs <- sum(weights)
+    
+    mean.Tr <- sum(Tr*weights)/obs
+    mean.Co <- sum(Co*weights)/obs
+    estimate <- mean.Tr-mean.Co
+    var.Tr  <- sum( ( (Tr - mean.Tr)^2 )*weights)/(obs-1)
+    var.Co  <- sum( ( (Co - mean.Co)^2 )*weights)/(obs-1)
+    dim <- sqrt(var.Tr/obs + var.Co/obs)
+
+    if (estimate==0 & dim==0)
+      {
+        return(1)
+      }
+    
+    statistic  <- estimate/dim
+
+    a1 <- var.Tr/obs
+    a2 <- var.Co/obs
+    dof <- ((a1 + a2)^2)/( (a1^2)/(obs - 1) + (a2^2)/(obs - 1) )    
+    p.value    <- (1-MATCHpt(abs(statistic), df=dof))*2    
+
+    return(p.value)
+  } #end of Mt.test.unpaired.pvalue
+
+ks.fast <- function(x, y, n.x, n.y, n)
+  {
+    w <- c(x, y)
+    z <- cumsum(ifelse(order(w) <= n.x, 1/n.x, -1/n.y))
+    z <- z[c(which(diff(sort(w)) != 0), n.x + n.y)]        
+    
+    return( max(abs(z)) )
+  } #ks.fast
+
+qqstats <- function (x, y, standardize = TRUE, summary.func=NULL)
+{
+  if (standardize) {
+    vals <- sort(unique(c(x, y)))
+    x <- ecdf(x)
+    sx <- x(vals)
+    y <- ecdf(y)
+    sy <- y(vals)
+  }  else {
+    sx <- sort(x)
+    sy <- sort(y)
+    lenx <- length(sx)
+    leny <- length(sy)
+    
+    if (leny < lenx) 
+      sx <- approx(1:lenx, sx, n = leny, method = "constant")$y
+    if (leny > lenx) 
+      sy <- approx(1:leny, sy, n = lenx, method = "constant")$y
+  }
+  diffxy <- abs(sx-sy)
+  meandiff <- mean(diffxy)
+  maxdiff <- max(diffxy)  
+  mediandiff <- median(diffxy)
+  if(!is.null(summary.func))
+    {
+      summarydiff <- summary.func(diffxy)
+      
+      return(list(meandiff=meandiff, mediandiff=mediandiff, maxdiff=maxdiff,
+                  summarydiff=summarydiff, summary.func=summary.func))      
+    } else {
+      return(list(meandiff=meandiff, mediandiff=mediandiff, maxdiff=maxdiff))
+    }
+}#qqstats
+
+GenBalanceQQ <- function(rr, X, summarystat="mean", summaryfunc="mean")
+  {
+    index.treated <- rr[,1]
+    index.control <- rr[,2]
+    
+    nvars <- ncol(X)
+    qqsummary   <- c(rep(NA,nvars))
+    
+    for (i in 1:nvars)
+      {    
+        
+        qqfoo <- qqstats(X[,i][index.treated], X[,i][index.control], standardize=TRUE)
+        
+        if (summarystat=="median")
+          {
+            qqsummary[i] <- qqfoo$mediandiff
+          } else if (summarystat=="max") {
+            qqsummary[i] <- qqfoo$maxdiff    
+          } else {
+            qqsummary[i] <- qqfoo$meandiff
+          }
+        
+      } #end of for loop
+    
+    
+    if (summaryfunc=="median")
+      {
+        return(median(qqsummary))
+      } else if (summaryfunc=="max")  {
+        return(sort(qqsummary, decreasing=TRUE))
+      } else if (summaryfunc=="sort")  {
+        return(sort(qqsummary, decreasing=TRUE))
+      } else {
+        return(mean(qqsummary))
+      }    
+  } #end of GenBalanceQQ
+
+GenBalance <-
+  function(rr, X, nvars=ncol(X), nboots = 0, ks=TRUE, verbose = FALSE, paired=TRUE)
+  {
+    index.treated <- rr[,1]
+    index.control <- rr[,2]
+    weights <- rr[,3]
+
+    tol  <- sqrt(.Machine$double.eps)
+    storage.t <- c(rep(9,nvars))
+    storage.k <- c(rep(9,nvars))
+    fs.ks     <- matrix(nrow=nvars, ncol=1)
+    s.ks      <- matrix(nrow=nvars, ncol=1)  
+    bbcount   <- matrix(0, nrow=nvars, ncol=1)
+    dummy.indx  <- matrix(0, nrow=nvars, ncol=1)
+    
+    w  <- c(X[,1][index.treated], X[,1][index.control])
+    obs <- length(w)
+    n.x  <- length(X[,1][index.treated])
+    n.y  <- length(X[,1][index.control])
+    cutp <- n.x
+    w  <- matrix(nrow=obs, ncol=nvars)
+
+    for (i in 1:nvars)
+      {
+        w[,i] <- c(X[,i][index.treated], X[,i][index.control])
+
+        if(paired)
+          {
+            t.out <- Mt.test.pvalue(X[,i][index.treated],
+                                    X[,i][index.control],
+                                    weights = weights)
+          } else {
+            t.out <- Mt.test.unpaired.pvalue(X[,i][index.treated],
+                                             X[,i][index.control],
+                                             weights = weights)
+          }
+        
+        storage.t[i] <- t.out            
+        
+                                        #      print(length(unique(X[,i])) < 3)
+
+        
+        dummy.indx[i]  <- length(unique(X[,i])) < 3
+
+        if (!dummy.indx[i] & ks & nboots > 9)
+          {
+            fs.ks[i]  <- ks.fast(X[,i][index.treated], X[,i][index.control],
+                                 n.x=n.x, n.y=n.y, n=obs)
+          } else if(!dummy.indx[i] & ks)
+            {
+                                        #storage.k[i] <- ks.test(X[,i][index.treated], X[,i][index.control])$p.value
+              
+              storage.k[i] <- Mks.test(X[,i][index.treated], X[,i][index.control])$p.value
+
+            }
+      }#end of i loop
+
+    
+    if (ks & nboots > 9)
+      {
+        for (b in 1:nboots)
+          {
+            sindx  <- sample(1:obs, obs, replace = TRUE)
+            
+            for (i in 1:nvars)
+              {
+                
+                if (dummy.indx[i])
+                  next;
+                
+                X1tmp <- w[sindx[1:cutp],i ]
+                X2tmp <- w[sindx[(cutp + 1):obs], i]
+                s.ks[i] <- ks.fast(X1tmp, X2tmp, n.x=n.x, n.y=n.y, n=obs)
+                if (s.ks[i] >= (fs.ks[i] - tol) )
+                  bbcount[i]  <-  bbcount[i] + 1
+              }#end of i loop
+          } #end of b loop
+        
+        for (i in 1:nvars)
+          {
+            
+            if (dummy.indx[i])
+              {
+                storage.k[i]  <- 9
+                next;
+              }
+            
+            storage.k[i]  <- bbcount[i]/nboots
+            
+          }
+        storage.k[storage.k==9]=storage.t[storage.k==9]
+        output <- c(storage.t, storage.k)
+      } else if(ks){
+        storage.k[storage.k==9]=storage.t[storage.k==9]                
+        output <- c(storage.t, storage.k)
+      } else {
+        output <- storage.t
+      }
+
+    if(sum(is.na(output)) > 0) {
+      output[is.na(output)] = 2
+      warning("output has NaNs")
+    }
+    
+    if (verbose == TRUE)
+      {
+        cat("\n")
+        for (i in 1:nvars)
+          {
+            cat("\n", i, " t-test p-val  =", storage.t[i], "\n" )
+            if(ks)
+              cat(" ", i, "  ks-test p-val = ", storage.k[i], " \n",sep="")
+          }
+        cat("\nsorted return vector:\n", sort(output), "\n")
+        cat("number of return values:", length(output), "\n")
+      }
+
+    return(output)
+  } #end of GenBalance
+
+
+#
+# writing fast KS test
+#
+
+KSbootBalanceSummary <- function(index.treated, index.control, X, 
+                                 nboots = 1000)
+{
+  X <- as.matrix(X)
+  nvars <- ncol(X)
+
+  tol  <- sqrt(.Machine$double.eps)
+  storage.k <- c(rep(NA,nvars))
+  storage.k.naive <- c(rep(NA,nvars))  
+  fs.ks     <- matrix(nrow=nvars, ncol=1)
+  s.ks      <- matrix(nrow=nvars, ncol=1)  
+  bbcount   <- matrix(0, nrow=nvars, ncol=1)
+  dummy.indx  <- matrix(0, nrow=nvars, ncol=1)
+  
+  w  <- c(X[,1][index.treated], X[,1][index.control])
+  obs <- length(w)
+  n.x  <- length(X[,1][index.treated])
+  n.y  <- length(X[,1][index.control])
+  cutp <- n.x
+  w  <- matrix(nrow=obs, ncol=nvars)
+
+  for (i in 1:nvars)
+    {
+      w[,i] <- c(X[,i][index.treated], X[,i][index.control])
+      
+      dummy.indx[i]  <- length(unique(X[,i])) < 3
+
+      if (!dummy.indx[i])
+        {
+          foo <- Mks.test(X[,i][index.treated], X[,i][index.control])
+          fs.ks[i] <- foo$statistic
+          storage.k.naive[i] <- foo$p.value
+        } 
+    }#end of i loop
+
+  for (b in 1:nboots)
+    {
+      sindx  <- sample(1:obs, obs, replace = TRUE)
+      
+      for (i in 1:nvars)
+        {
+          
+          if (dummy.indx[i])
+            next;
+          
+          X1tmp <- w[sindx[1:cutp],i ]
+          X2tmp <- w[sindx[(cutp + 1):obs], i]
+          s.ks[i] <- ks.fast(X1tmp, X2tmp, n.x=n.x, n.y=n.y, n=obs)
+          if (s.ks[i] >= (fs.ks[i] - tol) )
+            bbcount[i]  <-  bbcount[i] + 1
+        }#end of i loop
+    } #end of b loop
+
+  for (i in 1:nvars)
+    {
+      if (dummy.indx[i])
+        {
+          storage.k[i]  <- NA
+          next;
+        }
+      
+      storage.k[i]  <- bbcount[i]/nboots
+    }
+
+  ret = list(ks.boot.pval=storage.k, ks.naive.pval=storage.k.naive, ks.stat=fs.ks)
+
+  return(ret)
+} #end of KSbootBalanceSummary
diff --git a/R/GenMatching.R b/R/GenMatching.R
new file mode 100644
index 0000000..a9507b9
--- /dev/null
+++ b/R/GenMatching.R
@@ -0,0 +1,1030 @@
+FastMatchC <- function(N, xvars, All, M, cdd, ww, Tr, Xmod, weights)
+  {
+    ret <- .Call("FastMatchC", as.integer(N), as.integer(xvars), as.integer(All), as.integer(M),
+                 as.double(cdd), as.double(ww), as.double(Tr),
+                 as.double(Xmod), as.double(weights),
+                 PACKAGE="Matching")
+    return(ret)
+  }
+
+MatchGenoudStage1 <- function(Tr=Tr, X=X, All=All, M=M, weights=weights,
+                              tolerance)
+  {
+    N  <- nrow(X)
+    xvars <- ncol(X)
+    
+# if SATC is to be estimated the treatment indicator is reversed    
+    if (All==2)
+      Tr <- 1-Tr
+
+# check on the number of matches, to make sure the number is within the limits
+# feasible given the number of observations in both groups.
+    if (All==1)
+      {
+        M <- min(M,min(sum(Tr),sum(1-Tr)));        
+      } else {
+        M <- min(M,sum(1-Tr));
+      }
+
+# I.c. normalize regressors to have mean zero and unit variance.
+# If the standard deviation of a variable is zero, its normalization
+# leads to a variable with all zeros.
+    Mu.X  <- matrix(0, xvars, 1)
+    Sig.X <- matrix(0, xvars, 1)
+
+    weights.sum <- sum(weights)
+
+    for (k in 1:xvars)
+      {
+        Mu.X[k,1] <- sum(X[,k]*weights)/weights.sum;
+        eps <- X[,k]-Mu.X[k,1]
+        Sig.X[k,1] <- sqrt(sum(X[,k]*X[,k]*weights)/weights.sum-Mu.X[k,1]^2)
+        Sig.X[k,1] <- Sig.X[k,1]*sqrt(N/(N-1))
+        if(Sig.X[k,1] < tolerance)
+          Sig.X[k,1] <- tolerance
+        X[,k]=eps/Sig.X[k,1]
+      } #end of k loop
+
+    ret <- list(Tr=Tr, X=X, All=All, M=M, N=N)
+    return(ret)
+  } #end of MatchGenoudStage1
+
+
+###############################################################################
+## For Caliper!
+##
+###############################################################################
+
+MatchGenoudStage1caliper <- function(Tr=Tr, X=X, All=All, M=M, weights=weights,
+                                     exact=exact, caliper=caliper,
+                                     distance.tolerance, tolerance)
+  {
+    N  <- nrow(X)
+    xvars <- ncol(X)
+    weights.orig  <- as.matrix(weights)
+
+    if (!is.null(exact))
+      {
+        exact = as.vector(exact)
+        nexacts = length(exact)
+        if ( (nexacts > 1) & (nexacts != xvars) )
+          {
+            warning("length of exact != ncol(X). Ignoring exact option")
+            exact <- NULL
+          } else if (nexacts==1 & (xvars > 1) ){
+            exact <- rep(exact, xvars)
+          }
+      }
+
+    if (!is.null(caliper))
+      {
+        caliper = as.vector(caliper)
+        ncalipers = length(caliper)
+        if ( (ncalipers > 1) & (ncalipers != xvars) )
+          {
+            warning("length of caliper != ncol(X). Ignoring caliper option")
+            caliper <- NULL
+          } else if (ncalipers==1 & (xvars > 1) ){
+            caliper <- rep(caliper, xvars)
+          }
+      }
+
+    if (!is.null(caliper))
+      {
+        ecaliper <- vector(mode="numeric", length=xvars)
+        sweights  <- sum(weights.orig)
+        for (i in 1:xvars)
+          {
+            meanX  <- sum( X[,i]*weights.orig )/sweights
+            sdX  <- sqrt(sum( (X[,i]-meanX)^2 )/sweights)
+            ecaliper[i]  <- caliper[i]*sdX
+          }
+      } else {
+        ecaliper <- NULL
+      }
+
+    if (!is.null(exact))
+      {
+        if(is.null(caliper))
+          {
+            max.diff <- abs(max(X)-min(X) + distance.tolerance * 100)
+            ecaliper <- matrix(max.diff, nrow=xvars, ncol=1)
+          }
+        
+        for (i in 1:xvars)
+          {
+            if (exact[i])
+              ecaliper[i] <- distance.tolerance;
+          }
+      }        
+    
+# if SATC is to be estimated the treatment indicator is reversed    
+    if (All==2)
+      Tr <- 1-Tr
+
+# check on the number of matches, to make sure the number is within the limits
+# feasible given the number of observations in both groups.
+    if (All==1)
+      {
+        M <- min(M,min(sum(Tr),sum(1-Tr)));        
+      } else {
+        M <- min(M,sum(1-Tr));
+      }
+
+# I.c. normalize regressors to have mean zero and unit variance.
+# If the standard deviation of a variable is zero, its normalization
+# leads to a variable with all zeros.
+    Mu.X  <- matrix(0, xvars, 1)
+    Sig.X <- matrix(0, xvars, 1)
+
+    weights.sum <- sum(weights)
+
+    for (k in 1:xvars)
+      {
+        Mu.X[k,1] <- sum(X[,k]*weights)/weights.sum;
+        eps <- X[,k]-Mu.X[k,1]
+        Sig.X[k,1] <- sqrt(sum(X[,k]*X[,k]*weights)/weights.sum-Mu.X[k,1]^2)
+        Sig.X[k,1] <- Sig.X[k,1]*sqrt(N/(N-1))
+        if(Sig.X[k,1] < tolerance)
+          Sig.X[k,1] <- tolerance        
+        X[,k]=eps/Sig.X[k,1]
+      } #end of k loop
+
+    ret <- list(Tr=Tr, X=X, All=All, M=M, N=N, ecaliper=ecaliper)
+    return(ret)
+  } #end of MatchGenoudStage1caliper
+
+
+###############################################################################
+## GenMatch
+##
+###############################################################################
+
+GenMatch <- function(Tr, X, BalanceMatrix=X, estimand="ATT", M=1,
+                     weights=NULL,
+                     pop.size = 100, max.generations=100,
+                     wait.generations=4, hard.generation.limit=FALSE,
+                     starting.values=rep(1,ncol(X)),
+                     fit.func="pvals",
+                     MemoryMatrix=TRUE,
+                     exact=NULL, caliper=NULL, replace=TRUE, ties=TRUE,
+                     CommonSupport=FALSE,nboots=0, ks=TRUE, verbose=FALSE,
+                     distance.tolerance=0.00001,
+                     tolerance=sqrt(.Machine$double.eps),
+                     min.weight=0,
+                     max.weight=1000,
+                     Domains=NULL,
+                     print.level=2,
+                     project.path=NULL,
+                     paired=TRUE,
+                     loss=1,
+                     data.type.integer=FALSE,
+                     restrict=NULL,
+                     cluster=FALSE,
+                     balance=TRUE, ...)
+  {
+
+    requireNamespace("rgenoud")
+
+    Tr <- as.double(Tr)
+    X  <- as.matrix(X)
+    BalanceMatrix  <- as.matrix(BalanceMatrix)
+
+    if(length(Tr) != nrow(X))
+      {
+        stop("length(Tr) != nrow(X)")
+      }
+    if(!is.function(fit.func))
+      {
+        if(nrow(BalanceMatrix) != length(Tr))
+          {
+            stop("nrow(BalanceMatrix) != length(Tr)")
+          }
+      }
+
+    if (is.null(weights))
+      {
+        weights <- rep(1,length(Tr))
+        weights.flag <- FALSE
+      } else {
+        weights.flag <- TRUE
+        weights <- as.double(weights)
+        if( length(Tr) != length(weights))
+          {
+            stop("length(Tr) != length(weights)")
+          }            
+      }
+
+    isna  <- sum(is.na(Tr)) + sum(is.na(X)) + sum(is.na(weights)) + sum(is.na(BalanceMatrix))
+    if (isna!=0)
+      {
+        stop("GenMatch(): input includes NAs")
+        return(invisible(NULL))
+      }    
+
+    #check inputs
+    if (sum(Tr !=1 & Tr !=0) > 0) {
+      stop("Treatment indicator must be a logical variable---i.e., TRUE (1) or FALSE (0)")
+    }
+    if (var(Tr)==0) {
+      stop("Treatment indicator ('Tr') must contain both treatment and control observations")
+    }    
+    if (distance.tolerance < 0)
+      {
+        warning("User set 'distance.tolerance' to less than 0.  Resetting to the default which is 0.00001.")
+        distance.tolerance <- 0.00001
+      }
+    #CommonSupport
+    if (CommonSupport !=1 & CommonSupport !=0) {
+      stop("'CommonSupport' must be a logical variable---i.e., TRUE (1) or FALSE (0)")
+    }    
+    if(CommonSupport==TRUE)
+      {
+        tr.min <- min(X[Tr==1,1])
+        tr.max <- max(X[Tr==1,1])
+
+        co.min <- min(X[Tr==0,1])
+        co.max <- max(X[Tr==0,1])
+
+        if(tr.min >= co.min)
+          {
+            indx1 <- X[,1] < (tr.min-distance.tolerance)
+          } else {
+            indx1 <- X[,1] < (co.min-distance.tolerance)            
+          }
+
+        if(co.max <= tr.max)
+          {        
+            indx2 <- X[,1] > (co.max+distance.tolerance)
+          } else {
+            indx2 <- X[,1] > (tr.max+distance.tolerance)            
+          }
+
+        indx3 <- indx1==0 & indx2==0
+        Tr <- as.double(Tr[indx3])
+        X  <- as.matrix(X[indx3,])
+        BalanceMatrix <- as.matrix(BalanceMatrix[indx3,])
+        weights <- as.double(weights[indx3])
+      }#end of CommonSupport
+    
+    if (pop.size < 0 | pop.size!=round(pop.size) )
+      {
+        warning("User set 'pop.size' to an illegal value.  Resetting to the default which is 100.")
+        pop.size <- 100
+      }
+    if (max.generations < 0 | max.generations!=round(max.generations) )
+      {
+        warning("User set 'max.generations' to an illegal value.  Resetting to the default which is 100.")
+        max.generations <-100
+      }
+    if (wait.generations < 0 | wait.generations!=round(wait.generations) )
+      {
+        warning("User set 'wait.generations' to an illegal value.  Resetting to the default which is 4.")
+        wait.generations <- 4
+      }
+    if (hard.generation.limit != 0 & hard.generation.limit !=1 )
+      {
+        warning("User set 'hard.generation.limit' to an illegal value.  Resetting to the default which is FALSE.")
+        hard.generation.limit <- FALSE
+      }
+    if (data.type.integer != 0 & data.type.integer !=1 )
+      {
+        warning("User set 'data.type.integer' to an illegal value.  Resetting to the default which is TRUE.")
+        data.type.integer <- TRUE
+      }
+    if (MemoryMatrix != 0 & MemoryMatrix !=1 )
+      {
+        warning("User set 'MemoryMatrix' to an illegal value.  Resetting to the default which is TRUE.")
+        MemoryMatrix <- TRUE
+      }                
+    if (nboots < 0 | nboots!=round(nboots) )
+      {
+        warning("User set 'nboots' to an illegal value.  Resetting to the default which is 0.")
+        nboots <- 0
+      }
+    if (ks != 0 & ks !=1 )
+      {
+        warning("User set 'ks' to an illegal value.  Resetting to the default which is TRUE.")
+        ks <- TRUE
+      }
+    if (verbose != 0 & verbose !=1 )
+      {
+        warning("User set 'verbose' to an illegal value.  Resetting to the default which is FALSE.")
+        verbose <- FALSE
+      }
+    if (min.weight < 0)
+      {
+        warning("User set 'min.weight' to an illegal value.  Resetting to the default which is 0.")
+        min.weight <- 0
+      }
+    if (max.weight < 0)
+      {
+        warning("User set 'max.weight' to an illegal value.  Resetting to the default which is 1000.")
+        max.weight <- 1000
+      }
+    if (print.level != 0 & print.level !=1 & print.level !=2 & print.level !=3)
+      {
+        warning("User set 'print.level' to an illegal value.  Resetting to the default which is 2.")
+        print.level <- 2
+      }    
+    if (paired != 0 & paired !=1 )
+      {
+        warning("User set 'paired' to an illegal value.  Resetting to the default which is TRUE.")
+        paired <- FALSE
+      }    
+    ##from Match()
+    if (tolerance < 0)
+      {
+        warning("User set 'tolerance' to less than 0.  Resetting to the default which is 0.00001.")
+        tolerance <- 0.00001
+      }
+    if (M < 1)
+      {
+        warning("User set 'M' to less than 1.  Resetting to the default which is 1.")
+        M <- 1
+      }
+    if ( M!=round(M) )
+      {
+        warning("User set 'M' to an illegal value.  Resetting to the default which is 1.")
+        M <- 1        
+      }
+    if (replace!=FALSE & replace!=TRUE)
+      {
+        warning("'replace' must be TRUE or FALSE.  Setting to TRUE")
+        replace <- TRUE
+      }
+    if(replace==FALSE)
+      ties <- FALSE
+    if (ties!=FALSE & ties!=TRUE)
+      {
+        warning("'ties' must be TRUE or FALSE.  Setting to TRUE")
+        ties <- TRUE
+      }
+
+    #print warning if pop.size, max.generations and wait.generations are all set to their original values
+    if(pop.size==100 & max.generations==100 & wait.generations==4)
+      {
+        warning("The key tuning parameters for optimization were are all left at their default values.  The 'pop.size' option in particular should probably be increased for optimal results.  For details please see the help page and http://sekhon.berkeley.edu/papers/MatchingJSS.pdf")
+      }
+
+    #loss function
+    if (is.double(loss))
+      {
+        if (loss==1)  {
+          loss.func=sort
+          lexical=ncol(BalanceMatrix)
+          if(ks)
+            lexical=lexical+lexical
+        } else if(loss==2) {
+          loss.func=min
+          lexical=0
+        } else{
+          stop("unknown loss function")
+        }
+      } else if (is.function(loss)) {
+        loss.func=loss
+        lexical=1
+      } else {
+        stop("unknown loss function")
+      }
+
+    #set lexical for fit.func
+    if (is.function(fit.func))
+      {
+        lexical = 1
+      } else if (fit.func=="qqmean.max" | fit.func=="qqmedian.max" | fit.func=="qqmax.max")   {
+        lexical=ncol(BalanceMatrix)
+      } else if (fit.func!="qqmean.mean" & fit.func!="qqmean.max" &
+                 fit.func!="qqmedian.median" & fit.func!="qqmedian.max"
+                 & fit.func!="pvals") {
+        stop("invalid 'fit.func' argument")
+      } else  if (!fit.func=="pvals") {
+        lexical = 0
+      }
+
+    if(replace==FALSE)
+      {
+        #replace==FALE, needs enough observation
+        #ATT
+        orig.weighted.control.nobs <- sum(weights[Tr!=1])
+        orig.weighted.treated.nobs <- sum(weights[Tr==1])
+        if(estimand=="ATC")
+          {
+            if (orig.weighted.treated.nobs < orig.weighted.control.nobs)
+              {
+                warning("replace==FALSE, but there are more (weighted) control obs than treated obs.  Some obs will be dropped.  You may want to estimate ATC instead")
+              }
+          } else if(estimand=="ATE") 
+            {
+              #ATE
+              if (orig.weighted.treated.nobs > orig.weighted.control.nobs)
+                {
+                  warning("replace==FALSE, but there are more (weighted) treated obs than control obs.  Some treated obs will not be matched.  You may want to estimate ATC instead.")
+                }              
+              if (orig.weighted.treated.nobs < orig.weighted.control.nobs)
+                {
+                  warning("replace==FALSE, but there are more (weighted) control obs than treated obs.  Some control obs will not be matched.  You may want to estimate ATT instead.")
+                }
+            } else {
+              #ATT
+              if (orig.weighted.treated.nobs > orig.weighted.control.nobs)
+                {
+                  warning("replace==FALSE, but there are more (weighted) treated obs than control obs.  Some treated obs will not be matched.  You may want to estimate ATC instead.")
+                }
+            }
+        
+        #we need a restrict matrix if we are going to not do replacement
+        if(is.null(restrict))
+          {
+            restrict <- t(as.matrix(c(0,0,0)))
+          }
+      }#end of replace==FALSE    
+
+    
+
+    #check the restrict matrix input
+    if(!is.null(restrict))
+      {
+        if(!is.matrix(restrict))
+          stop("'restrict' must be a matrix of restricted observations rows and three columns: c(i,j restriction)")
+
+        if(ncol(restrict)!=3 )
+          stop("'restrict' must be a matrix of restricted observations rows and three columns: c(i,j restriction)")
+
+        restrict.trigger <- TRUE
+      }  else {
+        restrict.trigger <- FALSE
+      }
+
+    if(!is.null(caliper) | !is.null(exact) | restrict.trigger | !ties)
+      {
+        GenMatchCaliper.trigger <- TRUE
+      } else {
+        GenMatchCaliper.trigger <- FALSE
+      }
+
+    isunix  <- .Platform$OS.type=="unix"
+    if (is.null(project.path))
+      {
+        if (print.level < 3 & isunix)
+          {
+            project.path="/dev/null"
+          } else {
+            project.path=paste(tempdir(),"/genoud.pro",sep="")
+            
+            #work around for rgenoud bug
+            #if (print.level==3)
+            #print.level <- 2
+          }
+      } 
+    
+    nvars <- ncol(X)
+    balancevars <- ncol(BalanceMatrix)
+
+    if (is.null(Domains))
+      {
+        Domains <- matrix(min.weight, nrow=nvars, ncol=2)
+        Domains[,2] <- max.weight
+      } else {
+        indx <- (starting.values < Domains[,1]) | (starting.values > Domains[,2])
+        starting.values[indx] <- round( (Domains[indx,1]+Domains[indx,2])/2 )
+      }
+
+    # create All
+    if (estimand=="ATT")
+      {
+        All  <- 0
+      } else if(estimand=="ATE") {
+        All  <- 1
+      } else if(estimand=="ATC") {
+        All  <- 2
+      } else {
+        All  <- 0
+        warning("User set 'estimand' to an illegal value.  Resetting to the default which is 'ATT'")
+      }
+
+    #stage 1 Match, only needs to be called once    
+    if(!GenMatchCaliper.trigger)
+      {
+
+        s1 <- MatchGenoudStage1(Tr=Tr, X=X, All=All, M=M, weights=weights,
+                                tolerance=tolerance);
+        s1.Tr <- s1$Tr
+        s1.X <- s1$X
+        s1.All <- s1$All
+        s1.M <- s1$M
+        s1.N <- s1$N
+        rm(s1)
+      } else {
+        s1 <- MatchGenoudStage1caliper(Tr=Tr, X=X, All=All, M=M, weights=weights,
+                                       exact=exact, caliper=caliper,
+                                       distance.tolerance=distance.tolerance,
+                                       tolerance=tolerance)
+        s1.Tr <- s1$Tr
+        s1.X <- s1$X
+        s1.All <- s1$All
+        s1.M <- s1$M
+        s1.N <- s1$N
+        s1.ecaliper  <- s1$ecaliper
+        
+        if (is.null(s1.ecaliper))
+          {
+            caliperFlag  <- 0
+            Xorig  <- 0
+            CaliperVec  <- 0
+          } else {
+            caliperFlag  <- 1
+            Xorig  <- X
+            CaliperVec  <- s1$ecaliper
+          }
+        rm(s1)        
+      } #GenMatchCaliper.trigger
+
+    genoudfunc  <- function(x)
+      {
+        wmatrix <- diag(x, nrow=nvars)
+        if ( min(eigen(wmatrix, symmetric=TRUE, only.values=TRUE)$values) < tolerance )
+            wmatrix <- wmatrix + diag(nvars)*tolerance
+        
+        ww <- chol(wmatrix)
+
+        if(!GenMatchCaliper.trigger)
+          {
+            
+            if (weights.flag==TRUE)
+              {
+                FastMatchC.internal <- function(N, xvars, All, M, cdd, ww, Tr, Xmod, weights)
+                  {
+                    ret <- .Call("FastMatchC", as.integer(N), as.integer(xvars), as.integer(All), as.integer(M),
+                                 as.double(cdd), as.double(ww), as.double(Tr),
+                                 as.double(Xmod), as.double(weights),
+                                 PACKAGE="Matching")
+                    return(ret)
+                  }
+                
+                rr <- FastMatchC.internal(N=s1.N, xvars=nvars, All=s1.All, M=s1.M,
+                                          cdd=distance.tolerance, ww=ww, Tr=s1.Tr, Xmod=s1.X,
+                                          weights=weights)
+              } else {
+                FasterMatchC.internal <- function(N, xvars, All, M, cdd, ww, Tr, Xmod, weights)
+                  {
+                    ret <- .Call("FasterMatchC", as.integer(N), as.integer(xvars), as.integer(All), as.integer(M),
+                                 as.double(cdd), as.double(ww), as.double(Tr),
+                                 as.double(Xmod), 
+                                 PACKAGE="Matching")
+                    return(ret)
+                  }
+                
+                rr <- FasterMatchC.internal(N=s1.N, xvars=nvars, All=s1.All, M=s1.M,
+                                             cdd=distance.tolerance, ww=ww, Tr=s1.Tr, Xmod=s1.X)
+              } #end of weights.flag
+          } else {
+            if (weights.flag==TRUE)
+              {
+                MatchLoopC.internal <- function(N, xvars, All, M, cdd, caliperflag, replace, ties, ww, Tr, Xmod, weights, CaliperVec,
+                                                Xorig, restrict.trigger, restrict)
+                  {
+                    
+                    if(restrict.trigger)
+                      {
+                        restrict.nrow <- nrow(restrict)
+                      } else {
+                        restrict.nrow <- 0
+                      }    
+                    
+                    ret <- .Call("MatchLoopC", as.integer(N), as.integer(xvars), as.integer(All), as.integer(M),
+                                 as.double(cdd), as.integer(caliperflag), as.integer(replace), as.integer(ties), as.double(ww), as.double(Tr),
+                                 as.double(Xmod), as.double(weights), as.double(CaliperVec), as.double(Xorig),
+                                 as.integer(restrict.trigger), as.integer(restrict.nrow), as.double(restrict),
+                                 #next line is sets the DiagWeightMatrixFlag
+                                 as.double(1),                             
+                                 PACKAGE="Matching")
+                    return(ret)
+                  } #end of MatchLoopC.internal
+                
+                rr <- MatchLoopC.internal(N=s1.N, xvars=nvars, All=s1.All, M=s1.M,
+                                          cdd=distance.tolerance,
+                                          caliperflag=caliperFlag,
+                                          replace=replace, ties=ties,
+                                          ww=ww, Tr=s1.Tr, Xmod=s1.X, weights=weights,
+                                          CaliperVec=CaliperVec, Xorig=Xorig,
+                                          restrict.trigger=restrict.trigger, restrict=restrict)
+              } else {
+                MatchLoopCfast.internal <- function(N, xvars, All, M, cdd, caliperflag, replace, ties, ww, Tr, Xmod, CaliperVec, Xorig,
+                                                    restrict.trigger, restrict)
+                  {
+                    
+                    if(restrict.trigger)
+                      {
+                        restrict.nrow <- nrow(restrict)
+                      } else {
+                        restrict.nrow <- 0
+                      }    
+                    
+                    ret <- .Call("MatchLoopCfast", as.integer(N), as.integer(xvars), as.integer(All), as.integer(M),
+                                 as.double(cdd), as.integer(caliperflag), as.integer(replace), as.integer(ties), as.double(ww), as.double(Tr),
+                                 as.double(Xmod), as.double(CaliperVec), as.double(Xorig),
+                                 as.integer(restrict.trigger), as.integer(restrict.nrow), as.double(restrict),
+                                 #next line is the DiagWeightMatrixFlag
+                                 as.double(1),                              
+                                 PACKAGE="Matching")
+                    return(ret)
+                  } #end of MatchLoopCfast.internal
+                
+                
+                rr <- MatchLoopCfast.internal(N=s1.N, xvars=nvars, All=s1.All, M=s1.M,
+                                              cdd=distance.tolerance,
+                                              caliperflag=caliperFlag,
+                                              replace=replace, ties=ties,
+                                              ww=ww, Tr=s1.Tr, Xmod=s1.X, 
+                                              CaliperVec=CaliperVec, Xorig=Xorig,
+                                              restrict.trigger=restrict.trigger, restrict=restrict)
+              } #end of weights.flag
+            
+            #no matches
+            if(rr[1,1]==0) {
+              warning("no valid matches found in GenMatch evaluation") 
+              return(rep(-9999, balancevars*2))
+            }
+            
+            rr <- rr[,c(4,5,3)]            
+          } #Caliper.Trigger
+
+        #should be the same as GenBalance() in GenBalance.R but we need to include it here because of
+        #cluster scoping issues.
+        GenBalance.internal <-
+          function(rr, X, nvars=ncol(X), nboots = 0, ks=TRUE, verbose = FALSE, paired=TRUE)
+          {
+
+            #CUT-AND-PASTE from GenBalance.R, the functions before GenBalance. but get rid of warn *switch*
+            MATCHpt <- function(q, df, ...)
+              {
+                #don't know how general it is so let's try to work around it.
+                ret=pt(q,df, ...)
+                
+                if (is.na(ret)) {
+                  ret   <- pt(q, df, ...)
+                  if(is.na(ret))
+                    warning("pt() generated NaN. q:",q," df:",df,"\n",date())
+                }
+                
+                return(ret)
+              } #end of MATCHpt
+
+            Mt.test.pvalue  <- function(Tr, Co, weights)
+              {
+                v1  <- Tr-Co
+                estimate  <- sum(v1*weights)/sum(weights)
+                var1  <- sum( ((v1-estimate)^2)*weights )/( sum(weights)*sum(weights) )
+                
+                if (estimate==0 & var1==0)
+                  {
+                    return(1)
+                  }
+                
+                statistic  <- estimate/sqrt(var1)
+                #    p.value    <- (1-pnorm(abs(statistic)))*2
+                p.value    <- (1-MATCHpt(abs(statistic), df=sum(weights)-1))*2
+                
+                return(p.value)
+              } #end of Mt.test.pvalue
+
+            Mt.test.unpaired.pvalue  <- function(Tr, Co, weights)
+              {
+                obs <- sum(weights)
+                
+                mean.Tr <- sum(Tr*weights)/obs
+                mean.Co <- sum(Co*weights)/obs
+                estimate <- mean.Tr-mean.Co
+                var.Tr  <- sum( ( (Tr - mean.Tr)^2 )*weights)/(obs-1)
+                var.Co  <- sum( ( (Co - mean.Co)^2 )*weights)/(obs-1)
+                dim <- sqrt(var.Tr/obs + var.Co/obs)
+                
+                if (estimate==0 & dim==0)
+                  {
+                    return(1)
+                  }
+                
+                statistic  <- estimate/dim
+                
+                a1 <- var.Tr/obs
+                a2 <- var.Co/obs
+                dof <- ((a1 + a2)^2)/( (a1^2)/(obs - 1) + (a2^2)/(obs - 1) )    
+                p.value    <- (1-MATCHpt(abs(statistic), df=dof))*2    
+                
+                return(p.value)
+              } #end of Mt.test.unpaired.pvalue
+
+            ks.fast <- function(x, y, n.x, n.y, n)
+              {
+                w <- c(x, y)
+                z <- cumsum(ifelse(order(w) <= n.x, 1/n.x, -1/n.y))
+                z <- z[c(which(diff(sort(w)) != 0), n.x + n.y)]        
+                
+                return( max(abs(z)) )
+              } #ks.fast
+
+            index.treated <- rr[,1]
+            index.control <- rr[,2]
+            weights <- rr[,3]
+            
+            tol  <- .Machine$double.eps*100  
+            storage.t <- c(rep(9,nvars))
+            storage.k <- c(rep(9,nvars))
+            fs.ks     <- matrix(nrow=nvars, ncol=1)
+            s.ks      <- matrix(nrow=nvars, ncol=1)  
+            bbcount   <- matrix(0, nrow=nvars, ncol=1)
+            dummy.indx  <- matrix(0, nrow=nvars, ncol=1)
+            
+            w  <- c(X[,1][index.treated], X[,1][index.control])
+            obs <- length(w)
+            n.x  <- length(X[,1][index.treated])
+            n.y  <- length(X[,1][index.control])
+            cutp <- round(obs/2)  
+            w  <- matrix(nrow=obs, ncol=nvars)
+            
+            for (i in 1:nvars)
+              {
+                w[,i] <- c(X[,i][index.treated], X[,i][index.control])
+                
+                if(paired)
+                  {
+                    t.out <- Mt.test.pvalue(X[,i][index.treated],
+                                            X[,i][index.control],
+                                            weights = weights)
+                  } else {
+                    t.out <- Mt.test.unpaired.pvalue(X[,i][index.treated],
+                                                     X[,i][index.control],
+                                                     weights = weights)
+                  }
+                
+                storage.t[i] <- t.out            
+        
+                dummy.indx[i]  <- length(unique(X[,i])) < 3
+                
+                if (!dummy.indx[i] & ks & nboots > 9)
+                  {
+                    fs.ks[i]  <- ks.fast(X[,i][index.treated], X[,i][index.control],
+                                         n.x=n.x, n.y=n.y, n=obs)
+                  } else if(!dummy.indx[i] & ks)
+                    {
+                      
+                      storage.k[i] <- Mks.test(X[,i][index.treated], X[,i][index.control])$p.value
+
+                    }
+              }#end of i loop
+
+            
+            if (ks & nboots > 9)
+              {
+                n.x  <- cutp
+                n.y  <- obs-cutp
+                for (b in 1:nboots)
+                  {
+                    sindx  <- sample(1:obs, obs, replace = TRUE)
+                    
+                    for (i in 1:nvars)
+                      {
+                        
+                        if (dummy.indx[i])
+                          next;
+                        
+                        X1tmp <- w[sindx[1:cutp],i ]
+                        X2tmp <- w[sindx[(cutp + 1):obs], i]
+                        s.ks[i] <- ks.fast(X1tmp, X2tmp, n.x=n.x, n.y=n.y, n=obs)
+                        if (s.ks[i] >= (fs.ks[i] - tol) )
+                          bbcount[i]  <-  bbcount[i] + 1
+                      }#end of i loop
+                  } #end of b loop
+                
+                for (i in 1:nvars)
+                  {
+                    
+                    if (dummy.indx[i])
+                      {
+                        storage.k[i]  <- 9
+                        next;
+                      }
+                    
+                    storage.k[i]  <- bbcount[i]/nboots
+                    
+                  }
+                storage.k[storage.k==9]=storage.t[storage.k==9]
+                output <- c(storage.t, storage.k)
+              } else if(ks){
+                storage.k[storage.k==9]=storage.t[storage.k==9]                
+                output <- c(storage.t, storage.k)
+              } else {
+                output <- storage.t
+              }
+            
+            if(sum(is.na(output)) > 0) {
+              output[is.na(output)] = 2
+              warning("output has NaNs")
+            }
+            
+            if (verbose == TRUE)
+              {
+                cat("\n")
+                for (i in 1:nvars)
+                  {
+                    cat("\n", i, " t-test p-val  =", storage.t[i], "\n" )
+                    if(ks)
+                      cat(" ", i, "  ks-test p-val = ", storage.k[i], " \n",sep="")
+                  }
+                cat("\nsorted return vector:\n", sort(output), "\n")
+                cat("number of return values:", length(output), "\n")
+              }
+            
+            return(output)
+          } #end of GenBalance.internal
+
+        GenBalanceQQ.internal <- function(rr, X, summarystat="mean", summaryfunc="mean")
+          {
+            index.treated <- rr[,1]
+            index.control <- rr[,2]
+    
+            nvars <- ncol(X)
+            qqsummary   <- c(rep(NA,nvars))
+            
+            for (i in 1:nvars)
+              {    
+                
+                qqfoo <- qqstats(X[,i][index.treated], X[,i][index.control], standardize=TRUE)
+                
+                if (summarystat=="median")
+                  {
+                    qqsummary[i] <- qqfoo$mediandiff
+                  } else if (summarystat=="max")  {
+                    qqsummary[i] <- qqfoo$maxdiff    
+                  } else {
+                    qqsummary[i] <- qqfoo$meandiff
+                  }
+                
+              } #end of for loop
+            
+            
+            if (summaryfunc=="median")
+              {
+                return(median(qqsummary))
+              } else if (summaryfunc=="max")  {
+                return(sort(qqsummary, decreasing=TRUE))
+              } else if (summaryfunc=="sort")  {
+                return(sort(qqsummary, decreasing=TRUE))
+              } else {
+                return(mean(qqsummary))
+              }    
+          } #end of GenBalanceQQ.internal
+
+
+        if (is.function(fit.func)) {
+          a <- fit.func(rr, BalanceMatrix)
+          return(a)
+        } else if (fit.func=="pvals")
+          {
+            a <- GenBalance.internal(rr=rr, X=BalanceMatrix, nvars=balancevars, nboots=nboots,
+                                     ks=ks, verbose=verbose, paired=paired)
+            a <- loss.func(a)
+            return(a)
+          } else if (fit.func=="qqmean.mean") {
+            a <- GenBalanceQQ.internal(rr=rr, X=BalanceMatrix, summarystat="mean", summaryfunc="mean")
+            return(a)
+          } else if (fit.func=="qqmean.max") {
+            a <- GenBalanceQQ.internal(rr=rr, X=BalanceMatrix, summarystat="mean", summaryfunc="max")
+            return(a)
+          } else if (fit.func=="qqmax.mean") {
+            a <- GenBalanceQQ.internal(rr=rr, X=BalanceMatrix, summarystat="max", summaryfunc="mean")
+            return(a)            
+          } else if (fit.func=="qqmax.max") {
+            a <- GenBalanceQQ.internal(rr=rr, X=BalanceMatrix, summarystat="max", summaryfunc="max")
+            return(a)                        
+          } else if (fit.func=="qqmedian.median") {
+            a <- GenBalanceQQ.internal(rr=rr, X=BalanceMatrix, summarystat="median", summaryfunc="median")
+            return(a)
+          } else if (fit.func=="qqmedian.max") {
+            a <- GenBalanceQQ.internal(rr=rr, X=BalanceMatrix, summarystat="median", summaryfunc="max")
+            return(a)
+          } 
+      } #end genoudfunc
+
+    #cluster info
+    clustertrigger=1
+    if (is.logical(cluster))
+      {
+        if (cluster==FALSE)  {
+          clustertrigger=0
+        } else {
+          stop("cluster option must be either FALSE, an object of the 'cluster' class (from the 'parallel' package) or a list of machines so 'genoud' can create such an object")
+        }
+      }
+    
+    if(clustertrigger) {
+      parallel.exists = requireNamespace("parallel")
+      if (!parallel.exists) {
+        stop("The 'cluster' feature cannot be used unless the package 'parallel' can be loaded.")
+      }
+    } 
+
+    if(clustertrigger)
+      {
+
+        GENclusterExport <- function (cl, list, envir = .GlobalEnv) 
+          {
+            gets <- function(n, v) {
+              assign(n, v, envir = envir)
+              NULL
+            }
+            for (name in list) {
+              parallel::clusterCall(cl, gets, name, get(name))
+            }
+          }        
+
+        if (class(cluster)[1]=="SOCKcluster" | class(cluster)[1]=="PVMcluster" | class(cluster)[1]=="spawnedMPIcluster" | class(cluster)[1]=="MPIcluster") {
+          clustertrigger=1
+          cl <- cluster
+          cl.genoud <- cl
+        } else {
+          clustertrigger=2
+          cluster <- as.vector(cluster)
+          cat("Initializing Cluster\n")
+          cl <- parallel::makePSOCKcluster(cluster)
+          cl.genoud <- cl
+        }      
+      } else {
+        cl.genoud <- FALSE
+      }#end of clustertrigger
+
+    if (clustertrigger > 0)
+      {
+        #create restrict.summary, because passing the entire restrict matrix is too much
+        
+        parallel::clusterEvalQ(cl, library("Matching"))
+        GENclusterExport(cl, c("s1.N", "s1.All", "s1.M", "s1.Tr", "s1.X", "nvars",
+                               "tolerance", "distance.tolerance", "weights",
+                               "BalanceMatrix", "balancevars", "nboots", "ks", "verbose", "paired", "loss.func",
+                               "fit.func"))
+
+        if(GenMatchCaliper.trigger) {
+          GENclusterExport(cl, c("caliperFlag", "CaliperVec", "Xorig", "restrict.trigger", "restrict","replace"))
+        }
+        
+        GENclusterExport(cl, "genoudfunc")
+      }
+
+    do.max <- FALSE    
+    if(!is.function(fit.func))
+      {
+        if (fit.func=="pvals") 
+          do.max <- TRUE
+      }
+
+    rr <- rgenoud::genoud(genoudfunc, nvars=nvars, starting.values=starting.values,
+                 pop.size=pop.size, max.generations=max.generations,
+                 wait.generations=wait.generations, hard.generation.limit=hard.generation.limit,
+                 Domains=Domains,
+                 MemoryMatrix=MemoryMatrix,
+                 max=do.max, gradient.check=FALSE, data.type.int=data.type.integer,
+                 hessian=FALSE,
+                 BFGS=FALSE, project.path=project.path, print.level=print.level,
+                 lexical=lexical,
+                 cluster=cl.genoud,
+                 balance=balance,
+                 ...)
+    
+    wmatrix <- diag(rr$par, nrow=nvars)
+    
+    if ( min(eigen(wmatrix, symmetric=TRUE, only.values=TRUE)$values) < tolerance )
+      wmatrix <- wmatrix + diag(nvars)*tolerance
+        
+    ww <- chol(wmatrix)
+
+    if(!GenMatchCaliper.trigger)
+      {
+        mout <- FastMatchC(N=s1.N, xvars=nvars, All=s1.All, M=s1.M,
+                           cdd=distance.tolerance, ww=ww, Tr=s1.Tr, Xmod=s1.X,
+                           weights=weights)
+        rr2 <- list(value=rr$value, par=rr$par, Weight.matrix=wmatrix, matches=mout, ecaliper=NULL)
+      } else {
+        mout <- MatchLoopC(N=s1.N, xvars=nvars, All=s1.All, M=s1.M,
+                           cdd=distance.tolerance,
+                           caliperflag=caliperFlag,
+                           replace=replace, ties=ties,
+                           ww=ww, Tr=s1.Tr, Xmod=s1.X, weights=weights,
+                           CaliperVec=CaliperVec, Xorig=Xorig,
+                           restrict.trigger=restrict.trigger, restrict=restrict,
+                           DiagWeightMatrixFlag=1)
+
+        #no matches
+        if(mout[1,1]==0) {
+          warning("no valid matches found by GenMatch") 
+        }        
+        
+        rr2 <- list(value=rr$value, par=rr$par, Weight.matrix=wmatrix, matches=mout, ecaliper=CaliperVec)
+      }
+
+    if (clustertrigger==2)
+      parallel::stopCluster(cl)    
+    
+    class(rr2) <- "GenMatch"
+    return(rr2)
+  } #end of GenMatch
diff --git a/R/Matchby.R b/R/Matchby.R
new file mode 100644
index 0000000..d5bc95a
--- /dev/null
+++ b/R/Matchby.R
@@ -0,0 +1,265 @@
+Matchby <- function(Y=NULL, Tr, X, by, estimand="ATT", M=1, ties=FALSE, replace=TRUE,
+                    exact = NULL, caliper = NULL,
+                    AI=FALSE, Var.calc=0,
+                    Weight = 1, Weight.matrix = NULL, 
+                    distance.tolerance = 1e-05, tolerance = sqrt(.Machine$double.eps), 
+                    print.level=1, version="Matchby", ...)
+  {
+
+    #index for raw obs
+    Tr <- as.double(Tr)    
+    nobs  <- length(Tr)
+    orig.treated.nobs  <- sum(Tr==1)
+
+    if(is.null(Y))
+      {
+        Y <- rep(0, nobs)
+      } else {
+        Y  <- as.double(Y)
+        if (nobs != length(Y))
+          {
+            stop("length(Tr) != length(Y)")
+          }
+      }
+    
+    X  <- as.matrix(X)
+
+    if( nobs != nrow(X))
+      {
+        stop("length(Tr) != nrow(X)")
+      }        
+
+    index.nobs <- 1:nobs
+    t.index.nobs <- split(index.nobs, by, drop=TRUE)
+
+    nindx  <- length(t.index.nobs)
+
+    # *OUTPUT* observation weights
+    weights  <- NULL
+
+    index.treated <- NULL
+    index.control <- NULL
+
+    if (Var.calc < 0)
+      {
+        warning("User set 'Var.calc' to less than 0.  Resetting to the default which is 0.")
+        Var.calc <- 0
+      }
+
+    if(Var.calc > 0)
+      AI <- TRUE
+
+    if(AI & estimand!="ATT")
+      {
+        warning("This function can only calculate Abadie-Imbens SEs for 'ATT'.  For AI SEs and other estimands, please use 'Match()'. Setting 'AI=FALSE'")
+        AI <- FALSE
+        Var.calc <- 0
+      }
+    if(AI & ties!=TRUE)
+      {
+        ties=TRUE
+        warning("Abadie-Imbens SEs have been requested. Setting 'ties=TRUE'")
+      }
+    if(AI & replace!=TRUE)
+      {
+        replace=TRUE
+        warning("Abadie-Imbens SEs have been requested. Setting 'replace=TRUE'")
+      }
+    if(AI)
+      version <- "MatchbyAI"
+
+    if (replace!=FALSE & replace!=TRUE)
+      {
+        warning("'replace' must be TRUE or FALSE.  Setting to TRUE")
+        replace <- TRUE
+      }
+    if(replace==FALSE)
+      {
+        ties <- FALSE        
+      }    
+    if (ties!=FALSE & ties!=TRUE)
+      {
+        warning("'ties' must be TRUE or FALSE.  Setting to TRUE")
+        ties <- TRUE
+      }
+
+    if(AI)
+      {
+        Kcount <- as.matrix(rep(0, nobs))    
+        KKcount <- as.matrix(rep(0, nobs))
+        YCAUS <- matrix(0, nrow=nobs, ncol=1)
+
+        if(Var.calc>0)
+          Sigs <- matrix(0, nrow=nobs, ncol=1)
+      }
+
+    for (i in 1:nindx)
+      {
+        if(print.level > 0)
+          cat(i,"of", nindx, "groups\n")
+
+        tmp.index.nobs <- t.index.nobs[[i]]
+        
+        f.Tr  <- Tr[tmp.index.nobs]
+        #need at least 1 Tr and 1 Co
+        if(length(f.Tr) < 2)
+          {
+            next;
+          }
+        #drop if we only have Tr or Co
+        if( var(f.Tr)==0 )
+          {
+            next;
+          }
+
+        t1  <- Match(Y=Y[tmp.index.nobs], Tr=f.Tr, X=X[tmp.index.nobs,],
+                     estimand=estimand, M=M,
+                     Var.calc=Var.calc,
+                     exact=exact, caliper=caliper, replace=replace, ties=ties,
+                     Weight=Weight, Weight.matrix=Weight.matrix,
+                     tolerance=tolerance, distance.tolerance=distance.tolerance,
+                     version=version, ...)
+        
+        if(is.na(t1[1]))
+          {
+            if(!is.null(exact) | !is.null(caliper))
+              {
+                warning("no matches found in group ",i," (probably because of the exact or caliper option) continuing")
+              } else {
+                warning("no matches found in group ",i," continuing")}
+            next
+          }
+
+        weights  <- c(weights, t1$weights)
+
+        index.treated <- c(index.treated,(tmp.index.nobs)[t1$index.treated])
+        index.control <- c(index.control,(tmp.index.nobs)[t1$index.control])
+
+        if(AI)
+          {
+            YCAUS[tmp.index.nobs]   <- t1$YCAUS
+            Kcount[tmp.index.nobs]  <- t1$Kcount
+            KKcount[tmp.index.nobs] <- t1$KKcount
+
+            if(Var.calc>0)
+              {
+                if(is.null(t1$Sigs))
+                  {
+                    pfoo <- paste("Var.calc=",Var.calc," cannot be calculated (group ",i,").  Var.calc is probably set to a number larger than the possible number of matches in a subgroup",sep="")
+                    stop(pfoo)
+                  } else {
+                    Sigs[tmp.index.nobs]    <- t1$Sigs
+                  }
+              }#if(Var.calc>0)
+          }#if(AI)
+      }#i:nindx
+
+    if(is.null(index.treated))
+      {
+        warning("no valid matches were found")
+        z <- NA
+        class(z)  <- "Matchby"    
+        return(z)
+      }
+
+    Yt  <- Y[index.treated]
+    Yc  <- Y[index.control]
+    
+    sum.tw  <- sum(weights)
+    est  <- sum(Yt*weights)/sum.tw  - sum(Yc*weights)/sum.tw
+    Tau  <- Yt - Yc
+    varest  <- sum( ((Tau-est)^2)*weights)/(sum.tw*sum.tw)
+    se.standard  <- sqrt(varest)
+    
+    ret  <- list(est=est, se=NULL, se.standard=se.standard,
+                 index.treated=index.treated,
+                 index.control=index.control,
+                 weights=weights)
+    ret$orig.nobs  <- nobs
+    ret$orig.wnobs <- nobs
+    ret$nobs  <- length(Yt)
+    ret$wnobs  <- sum.tw
+    ret$orig.treated.nobs  <- orig.treated.nobs
+    ret$ndrops  <- orig.treated.nobs-ret$wnobs
+    ret$estimand  <- estimand
+    ret$version  <- version
+    class(ret)  <- "Matchby"
+    
+    if(AI)
+      {
+        if(Var.calc==0)
+          {
+            eps <- Tau - est
+            eps.sq <- eps*eps
+            Sigs <- 0.5 * matrix(1, nobs, 1) %*% (t(eps.sq) %*% weights)/sum(weights)
+          }
+        
+        SN <- orig.treated.nobs
+        var.pop=sum((Sigs*((1-Tr)*Kcount*Kcount-(1-Tr)*KKcount))/(SN*SN))
+        
+        dvar.pop <- sum(Tr*(YCAUS-est)*(YCAUS-est))/(SN*SN)
+        
+        var <- var.pop + dvar.pop
+        
+        se <- sqrt(var)
+        ret$se <- se
+      }
+    
+    invisible(return(ret))
+  }
+  
+
+summary.Matchby  <- function(object, ..., digits=5)
+  {
+    if(!is.list(object)) {
+      warning("'Matchby' object contains less than two valid matches.  Cannot proceed.")
+      return(invisible(NULL))
+    }
+    
+    if (class(object) != "Matchby") {
+      warning("Object not of class 'Matchby'")
+      return(invisible(NULL))
+    }
+
+    cat("\n")
+    cat("Estimate... ",format(object$est,digits=digits),"\n")
+
+    if(!is.null(object$se))
+      {
+        cat("AI SE...... ",format(object$se,digits=digits),"\n")
+        cat("AI T-stat.. ",format(object$est/object$se,digits=digits),"\n")
+        cat("AI p.val... ",format.pval((1-pnorm(abs(object$est/object$se)))*2,digits=digits),"\n\n")
+      }
+    cat("SE......... ",format(object$se.standard,digits=digits),"\n")
+    cat("T-stat..... ",format(object$est/object$se.standard,digits=digits),"\n")
+    cat("p.val...... ",format.pval((1-pnorm(abs(object$est/object$se.standard)))*2,digits=digits),"\n")
+    cat("\n")        
+
+    cat("Original number of observations.............. ", object$orig.nobs,"\n")
+    if(object$estimand!="ATC")
+      {
+        cat("Original number of treated obs............... ", object$orig.treated.nobs,"\n")
+      } else {
+        cat("Original number of control obs............... ",
+            object$orig.nobs- object$orig.treated.nobs,"\n")        
+      }
+    cat("Matched number of observations............... ", round(object$wnobs, 3),"\n")
+    cat("Matched number of observations  (unweighted). ", object$nobs,"\n")
+    cat("\n")
+        
+    if ( object$ndrops > 0)
+        {
+          cat("Number of treated observations dropped....... ", object$ndrops, "\n")
+          cat("\n")
+        }
+
+    z <- list()
+    class(z) <- "summary.Matchby"
+    return(invisible(z))
+  } #end of summary.Matchby
+
+print.summary.Matchby <- function(x, ...)
+  {
+    invisible(NULL)
+  }
+
diff --git a/R/Matching.R b/R/Matching.R
new file mode 100644
index 0000000..d3d3b3c
--- /dev/null
+++ b/R/Matching.R
@@ -0,0 +1,3051 @@
+# Jasjeet S. Sekhon <sekhon at berkeley.edu>
+# HTTP://sekhon.berkeley.edu/
+# UC Berkeley
+
+# Match(): function to estimate treatments using a matching estimator.
+# Currently only the ability to estimate average treatment effects
+# using the approach of Abadie and Imbens is implemented.  In the
+# future, quantile treatment effects will be implemented along with
+# the ability to use robust estimation when estimating the propensity
+# score. MatchBalance(), and balanceUV() test for balance.
+
+Match  <- function(Y=NULL,Tr,X,Z=X,V=rep(1,length(Y)), estimand="ATT", M=1,
+                   BiasAdjust=FALSE,exact=NULL,caliper=NULL, replace=TRUE, ties=TRUE,
+                   CommonSupport=FALSE,Weight=1,Weight.matrix=NULL, weights=NULL,
+                   Var.calc=0, sample=FALSE, restrict=NULL, match.out=NULL,
+                   distance.tolerance=0.00001, tolerance=sqrt(.Machine$double.eps),
+                   version="standard")
+  {
+
+    BiasAdj  <- as.double(BiasAdjust)
+    sample  <- as.double(sample)
+
+    if ( (BiasAdj != 0) & (BiasAdj != 1) )
+      {
+        warning("User set 'BiasAdjust' to a non-logical value.  Resetting to the default which is FALSE.")        
+        BiasAdj <- 0
+      }
+    
+    #we don't need to use a Y
+    if (is.null(Y))
+      {
+        Y = rep(0, length(Tr))
+        version <- "fast"
+
+        if(BiasAdj)
+          {
+            warning("'BiasAdjust' set to FALSE because Y is NULL")
+            BiasAdj <- FALSE
+          }
+      }
+    
+    Y  <- as.double(Y)
+    Tr <- as.double(Tr)
+    X  <- as.matrix(X)
+    Z  <- as.matrix(Z)
+    V  <- as.matrix(V)
+
+    orig.nobs  <- length(Y)
+    nobs  <- orig.nobs
+    xvars <- ncol(X)    
+    orig.tr.nobs <- length(Tr)
+    if (orig.tr.nobs != orig.nobs)
+      {
+        stop("length(Y) != length(Tr)")
+      }
+    if( orig.tr.nobs != nrow(X))
+      {
+        stop("length(Tr) != nrow(X)")
+      }    
+    
+    if( orig.nobs != nrow(X))
+      {
+        stop("length(Y) != nrow(X)")
+      }
+    if( orig.nobs != nrow(V))
+      {
+        stop("length(Y) != nrow(V)")
+      }
+    if( orig.nobs != nrow(Z))
+      {
+        stop("length(Y) != nrow(Z)")
+      }
+
+    if (is.null(weights))
+      {
+        weights <- rep(1,length(Y))
+        weights.flag <- FALSE
+      } else {
+        weights.flag <- TRUE
+        weights <- as.double(weights)
+        if( orig.tr.nobs != length(weights))
+          {
+            stop("length(Tr) != length(weights)")
+          }        
+      }
+
+    isna  <- sum(is.na(Y)) + sum(is.na(Tr)) + sum(is.na(X)) + sum(is.na(weights)) + sum(is.na(Z)) + sum(is.na(V))
+    if (isna!=0)
+      {
+        stop("Match(): input includes NAs")
+        return(invisible(NULL))
+      }
+
+    if (sum(Tr !=1 & Tr !=0) > 0) {
+      stop("Treatment indicator ('Tr') must be a logical variable---i.e., TRUE (1) or FALSE (0)")
+    }
+    if (var(Tr)==0) {
+      stop("Treatment indicator ('Tr') must contain both treatment and control observations")
+    }
+    if (distance.tolerance < 0)
+      {
+        warning("User set 'distance.tolerance' to less than 0.  Resetting to the default which is 0.00001.")
+        distance.tolerance <- 0.00001
+      }
+
+    #CommonSupport
+    if (CommonSupport !=1 & CommonSupport !=0) {
+      stop("'CommonSupport' must be a logical variable---i.e., TRUE (1) or FALSE (0)")
+    }    
+    if(CommonSupport==TRUE)
+      {
+        tr.min <- min(X[Tr==1,1])
+        tr.max <- max(X[Tr==1,1])
+
+        co.min <- min(X[Tr==0,1])
+        co.max <- max(X[Tr==0,1])
+
+        if(tr.min >= co.min)
+          {
+            indx1 <- X[,1] < (tr.min-distance.tolerance)
+          } else {
+            indx1 <- X[,1] < (co.min-distance.tolerance)            
+          }
+
+        if(co.max <= tr.max)
+          {        
+            indx2 <- X[,1] > (co.max+distance.tolerance)
+          } else {
+            indx2 <- X[,1] > (tr.max+distance.tolerance)            
+          }
+
+        indx3 <- indx1==0 & indx2==0
+        Y  <- as.double(Y[indx3])
+        Tr <- as.double(Tr[indx3])
+        X  <- as.matrix(X[indx3,])
+        Z  <- as.matrix(Z[indx3,])
+        V  <- as.matrix(V[indx3,])
+        weights <- as.double(weights[indx3])
+
+        #let's recalculate these for common support
+        orig.nobs  <- length(Y)
+        nobs  <- orig.nobs
+      }#end of CommonSupport
+
+    #check additional inputs
+    if (tolerance < 0)
+      {
+        warning("User set 'tolerance' to less than 0.  Resetting to the default which is 0.00001.")
+        tolerance <- 0.00001
+      }
+    if (M < 1)
+      {
+        warning("User set 'M' to less than 1.  Resetting to the default which is 1.")
+        M <- 1
+      }
+    if ( M != round(M) )
+      {
+        warning("User set 'M' to an illegal value.  Resetting to the default which is 1.")
+        M <- 1        
+      }
+    if (Var.calc < 0)
+      {
+        warning("User set 'Var.calc' to less than 0.  Resetting to the default which is 0.")
+        Var.calc <- 0
+      }
+    if ( (sample != 0) & (sample != 1) )
+      {
+        warning("User set 'sample' to a non-logical value.  Resetting to the default which is FALSE.")        
+        sample <- 0
+      }
+    if (Weight != 1 & Weight != 2 & Weight != 3)
+      {
+        warning("User set 'Weight' to an illegal value.  Resetting to the default which is 1.")        
+        Weight <- 1
+      }
+    if (version!="fast" & version != "standard" & version != "legacy" & version != "Matchby" & version != "MatchbyAI")
+      {
+        warning("User set 'version' to an illegal value.  Resetting to the default which is 'standard'.")        
+        version <- "standard"
+      }
+
+    if(version=="Matchby")
+      {
+        version <- "fast"
+        Matchby.call <- TRUE
+        MatchbyAI <- FALSE
+      } else if(version=="MatchbyAI")
+      {
+        version <- "standard"
+        Matchby.call <- TRUE
+        MatchbyAI <- TRUE
+      } else {
+        Matchby.call <- FALSE
+        MatchbyAI <- FALSE
+      }
+
+    if (Var.calc !=0 & version=="fast")
+      {
+        warning("Var.calc cannot be estimate when version=='fast'")
+        Var.calc=0
+      }
+    if (BiasAdj!=FALSE & version=="fast")
+      {
+        warning("Bias Adjustment cannot be estimated when version=='fast'")
+        BiasAdj=0
+      }
+    if (replace!=FALSE & replace!=TRUE)
+      {
+        warning("'replace' must be TRUE or FALSE.  Setting to TRUE")
+        replace <- TRUE
+      }
+    if(replace==FALSE)
+      {
+        ties <- FALSE        
+        version="fast"
+        if (version=="legacy")
+          warning("'version' is set to 'fast' because replace==FALSE")
+      }
+    if (ties!=FALSE & ties!=TRUE)
+      {
+        warning("'ties' must be TRUE or FALSE.  Setting to TRUE")
+        ties <- TRUE
+      }
+    if(ties==FALSE)
+      {
+        version="fast"
+        if (version=="legacy")
+          warning("'version' is set to 'fast' because ties==FALSE")
+
+        if(BiasAdjust==TRUE) {
+          warning("Bias Adjustment can only be estimated when ties==TRUE and replace=TRUE.  Setting BiasAdjust=FALSE")
+          BiasAdjust <- FALSE
+          BiasAdj  <- 0
+        }
+      }
+
+    if (!is.null(match.out) & class(match.out) != "Match") {
+      warning("match.out object not of class 'Match'")
+      return(invisible(NULL))
+    }
+
+    ccc  <- tolerance
+    cdd  <- distance.tolerance
+
+    orig.treated.nobs  <- sum(Tr==1)
+    orig.control.nobs  <- sum(Tr==0)
+    orig.wnobs  <- sum(weights)
+    orig.weighted.treated.nobs <- sum( weights[Tr==1] )
+    orig.weighted.control.nobs <- sum( weights[Tr==0] )    
+    weights.orig  <- as.matrix(weights)
+    zvars <- ncol(Z);
+
+    estimand.orig <- estimand
+    if (estimand=="ATT")
+      {
+        estimand  <- 0
+
+        if(BiasAdj==1 & orig.treated.nobs<zvars)
+          {
+            warning("Fewer treated obs than variables in 'Z': BiasAdjust set to FALSE")
+            BiasAdj=0            
+          }
+
+      } else if(estimand=="ATE") {
+        estimand  <- 1
+
+        if(BiasAdj==1 & orig.nobs<zvars)
+          {
+            warning("Fewer obs than variables in 'Z': BiasAdjust set to FALSE")
+            BiasAdj=0            
+          }
+      } else if(estimand=="ATC") {
+        estimand  <- 2
+
+        if(BiasAdj==1 & orig.control.nobs<zvars)
+          {
+            warning("Fewer control obs than variables in 'Z': BiasAdjust set to FALSE")
+            BiasAdj=0            
+          }
+
+      } else {
+        estimand  <- 0
+        warning("User set 'estimand' to an illegal value.  Resetting to the default which is 'ATT'")
+      }
+
+    if (!is.null(Weight.matrix))
+      {
+
+        if(class(Weight.matrix)=="GenMatch")
+          {
+            Weight.matrix = Weight.matrix$Weight.matrix
+          }
+        
+        if (Weight==2)
+          {
+            warning("User supplied 'Weight.matrix' is being used even though 'Weight' is not set equal to 3")
+          }
+        Weight  <- 3
+      } else {
+        Weight.matrix <- dim(X)[2]
+      }
+
+    if(Var.calc > orig.weighted.treated.nobs)
+      {
+        warning("'Var.calc' > the number of treated obs: 'Var.calc' reset to ",
+                orig.weighted.treated.nobs, immediate.=Matchby.call)
+        Var.calc <- orig.weighted.treated.nobs
+      }
+    if(Var.calc > orig.weighted.control.nobs)
+      {
+        warning("'Var.calc' > the number of control obs: 'Var.calc' reset to ",
+                orig.weighted.control.nobs,  immediate.=Matchby.call)
+        Var.calc <- orig.weighted.control.nobs
+      }
+    
+    if(orig.nobs > 20000 & version!="fast" & !Matchby.call)
+      {
+        warning("The version='fast' option is recommended for large datasets if speed is desired.  For additional speed, you may also consider using the ties=FALSE option.", immediate.=TRUE)
+      }
+
+    #check the restrict matrix input
+    if(!is.null(restrict))
+      {
+        if(!is.matrix(restrict))
+          stop("'restrict' must be a matrix of restricted observations rows and three columns: c(i,j restriction)")
+
+        if(ncol(restrict)!=3 )
+          stop("'restrict' must be a matrix of restricted observations rows and three columns: c(i,j restriction)")
+      }
+
+    if (!is.null(exact))
+      {
+        exact = as.vector(exact)
+        nexacts = length(exact)
+        if ( (nexacts > 1) & (nexacts != xvars) )
+          {
+            warning("length of exact != ncol(X). Ignoring exact option")
+            exact <- NULL
+          } else if (nexacts==1 & (xvars > 1) ){
+            exact <- rep(exact, xvars)
+          }
+      }
+
+    if (!is.null(caliper))
+      {
+        caliper = as.vector(caliper)
+        ncalipers = length(caliper)
+        if ( (ncalipers > 1) & (ncalipers != xvars) )
+          {
+            warning("length of caliper != ncol(X). Ignoring caliper option")
+            caliper <- NULL
+          } else if (ncalipers==1 & (xvars > 1) ){
+            caliper <- rep(caliper, xvars)
+          }
+      }
+
+    if (!is.null(caliper))
+      {
+        ecaliper <- vector(mode="numeric", length=xvars)
+        sweights  <- sum(weights.orig)
+        for (i in 1:xvars)
+          {
+            meanX  <- sum( X[,i]*weights.orig )/sweights
+            sdX  <- sqrt(sum( (X[,i]-meanX)^2 )/sweights)
+            ecaliper[i]  <- caliper[i]*sdX
+          }
+      } else {
+        ecaliper <- NULL
+      }
+
+    if (!is.null(exact))
+      {
+        if(is.null(caliper))
+          {
+            max.diff <- abs(max(X)-min(X) + tolerance * 100)
+            ecaliper <- matrix(max.diff, nrow=xvars, ncol=1)
+          }
+        
+        for (i in 1:xvars)
+          {
+            if (exact[i])
+              ecaliper[i] <- tolerance;
+          }
+      }
+
+    if(replace==FALSE)
+      {
+        #replace==FALE, needs enough observation
+        #ATT
+        orig.weighted.control.nobs <- sum(weights[Tr!=1])
+        if(estimand==0)
+          {
+            if (orig.weighted.treated.nobs > orig.weighted.control.nobs)
+              {
+                warning("replace==FALSE, but there are more (weighted) treated obs than control obs.  Some treated obs will not be matched.  You may want to estimate ATC instead.")
+              }
+          } else if(estimand==1) 
+            {
+              #ATE
+              if (orig.weighted.treated.nobs > orig.weighted.control.nobs)
+                {
+                  warning("replace==FALSE, but there are more (weighted) treated obs than control obs.  Some treated obs will not be matched.  You may want to estimate ATC instead.")
+                }              
+              if (orig.weighted.treated.nobs < orig.weighted.control.nobs)
+                {
+                  warning("replace==FALSE, but there are more (weighted) control obs than treated obs.  Some control obs will not be matched.  You may want to estimate ATT instead.")
+                }
+            } else 
+        {
+              #ATC
+          if (orig.weighted.treated.nobs < orig.weighted.control.nobs)
+            {
+              warning("replace==FALSE, but there are more (weighted) control obs than treated obs.  Some obs will be dropped.  You may want to estimate ATC instead")
+            }
+        }
+        
+        #we need a restrict matrix if we are going to not do replacement
+        if(is.null(restrict))
+          {
+            restrict <- t(as.matrix(c(0,0,0)))
+          }
+        if(version!="fast" &  version!="standard")
+          {
+            warning("reverting to 'standard' version because replace=FALSE")
+            version="standard"
+          }
+      }#end of replace==FALSE
+
+#    if(version=="fast" & is.null(ecaliper) & sum(weights==1)==orig.nobs)
+    if(version=="fast" | version=="standard")
+      {
+        if(!is.null(match.out))
+          {
+            ret <- RmatchLoop(Y=Y, Tr=Tr, X=X, Z=Z, V=V, All=estimand, M=M, BiasAdj=BiasAdj,
+                              Weight=Weight, Weight.matrix=Weight.matrix, Var.calc=Var.calc,
+                              weight=weights, SAMPLE=sample, ccc=ccc, cdd=cdd,
+                              ecaliper=ecaliper, exact=exact, caliper=caliper,
+                              restrict=restrict, MatchLoopC.indx=match.out$MatchLoopC,
+                              weights.flag=weights.flag,  replace=replace, ties=ties,
+                              version=version, MatchbyAI=MatchbyAI)
+          } else {
+            ret <- RmatchLoop(Y=Y, Tr=Tr, X=X, Z=Z, V=V, All=estimand, M=M, BiasAdj=BiasAdj,
+                              Weight=Weight, Weight.matrix=Weight.matrix, Var.calc=Var.calc,
+                              weight=weights, SAMPLE=sample, ccc=ccc, cdd=cdd,
+                              ecaliper=ecaliper, exact=exact, caliper=caliper,
+                              restrict=restrict, weights.flag=weights.flag,  replace=replace, ties=ties,
+                              version=version, MatchbyAI=MatchbyAI)   
+          }
+      } else {
+        ret <- Rmatch(Y=Y, Tr=Tr, X=X, Z=Z, V=V, All=estimand, M=M, BiasAdj=BiasAdj,
+                      Weight=Weight, Weight.matrix=Weight.matrix, Var.calc=Var.calc,
+                      weight=weights, SAMPLE=sample, ccc=ccc, cdd=cdd,
+                      ecaliper=ecaliper, restrict=restrict)
+      }
+
+    if(is.null(ret$est))
+      {
+        if(!Matchby.call)
+          {
+            if(ret$valid < 1)
+              {
+                if (ret$sum.caliper.drops > 0) {
+                  warning("'Match' object contains no valid matches (probably because of the caliper or the exact option).") 
+                } else {
+                  warning("'Match' object contains no valid matches")
+                }
+              } else {
+                if (ret$sum.caliper.drops > 0) {
+                  warning("'Match' object contains only 1 valid match (probably because of the caliper or the exact option).") 
+                } else {
+                  warning("'Match' object contains only one valid match")
+                }            
+              }
+          } #endof if(!Matchby.call)
+
+        z <- NA
+        class(z)  <- "Match"    
+        return(z)
+      }
+    
+    indx <-  cbind(ret$art.data[,1],  ret$art.data[,2],  ret$W)
+
+    index.treated  <- indx[,1]
+    index.control  <- indx[,2]
+    weights        <- indx[,3]
+    sum.caliper.drops <- ret$sum.caliper.drops
+
+   #RESET INDEX.TREATED        
+    indx  <- as.matrix(cbind(index.treated,index.control))
+    if (estimand==0) {
+      #"ATT"
+      index.treated  <- indx[,1]
+      index.control  <- indx[,2]
+    } else if(estimand==1) {
+      #"ATE"
+      tmp.index.treated  <- indx[,1]
+      tmp.index.control  <- indx[,2]
+      
+      tl  <- length(tmp.index.treated)
+      index.treated <- vector(length=tl, mode="numeric")
+      index.control <- vector(length=tl, mode="numeric")
+      trt  <- Tr[tmp.index.treated]==1
+      for (i in 1:tl)
+        {
+          if (trt[i]) {
+            index.treated[i]  <- tmp.index.treated[i]
+            index.control[i]  <- tmp.index.control[i]
+          } else {
+            index.treated[i]  <- tmp.index.control[i]
+            index.control[i]  <- tmp.index.treated[i]
+          }
+        }
+    } else if(estimand==2) {
+      #"ATC"
+      index.treated  <- indx[,2]
+      index.control  <- indx[,1]
+    }        
+
+
+    mdata  <- list()
+    mdata$Y  <- c(Y[index.treated],Y[index.control])
+    mdata$Tr <- c(Tr[index.treated],Tr[index.control])
+    mdata$X  <- rbind(X[index.treated,],X[index.control,])
+    mdata$orig.weighted.treated.nobs <- orig.weighted.treated.nobs
+
+    #naive standard errors
+    mest  <- sum((Y[index.treated]-Y[index.control])*weights)/sum(weights)
+    v1  <- Y[index.treated] - Y[index.control]
+    varest  <- sum( ((v1-mest)^2)*weights)/(sum(weights)*sum(weights))
+    se.standard  <- sqrt(varest)
+
+    wnobs <- sum(weights)
+
+    if(estimand==0)
+      {
+        #ATT
+        actual.drops <- orig.weighted.treated.nobs-wnobs
+      } else if (estimand==1)
+        {
+          #ATE
+          actual.drops <- orig.wnobs-wnobs
+        } else {
+          #ATC
+          actual.drops <- (orig.wnobs-orig.weighted.treated.nobs)-wnobs 
+        }
+
+    #What obs were dropped?
+    index.dropped <-  NULL #nothing was dropped
+    if (sum.caliper.drops > 0 )
+      {
+        if(estimand.orig=="ATT")
+          {
+            matched.index <- which(Tr==1)
+            matched <- !(matched.index %in% index.treated)        
+            
+          } else if(estimand.orig=="ATC")
+            {
+              matched.index <- which(Tr==0)
+              matched <- !(matched.index %in% index.control)
+            } else if(estimand.orig=="ATE")
+              {
+                matched.index <- 1:length(Tr)
+                matched <- !(matched.index %in% c(index.treated,index.control))
+              } 
+        index.dropped <- matched.index[matched]  #obs not matched
+      } #end of sum.caliper.drops > 0
+            
+    z  <- list(est=ret$est, se=ret$se, est.noadj=mest, se.standard=se.standard,
+               se.cond=ret$se.cond, 
+               mdata=mdata, 
+               index.treated=index.treated, index.control=index.control, index.dropped=index.dropped,
+               weights=weights, orig.nobs=orig.nobs, orig.wnobs=orig.wnobs,
+               orig.treated.nobs=orig.treated.nobs,
+               nobs=nobs, wnobs=wnobs,
+               caliper=caliper, ecaliper=ecaliper, exact=exact,
+               ndrops=actual.drops, ndrops.matches=sum.caliper.drops, 
+               MatchLoopC=ret$MatchLoopC, version=version,
+               estimand=estimand.orig)
+
+    if(MatchbyAI)
+      {
+        z$YCAUS   <- ret$YCAUS
+        z$ZCAUS   <- ret$ZCAUS
+        z$Kcount  <- ret$Kcount
+        z$KKcount <- ret$KKcount
+        z$Sigs    <- ret$Sigs
+      }
+
+    class(z)  <- "Match"    
+    return(z)
+  } #end of Match
+
+summary.Match  <- function(object, ..., full=FALSE, digits=5)
+  {
+    if(!is.list(object)) {
+      warning("'Match' object contains less than two valid matches.  Cannot proceed.")
+      return(invisible(NULL))
+    }
+    
+    if (class(object) != "Match") {
+      warning("Object not of class 'Match'")
+      return(invisible(NULL))
+    }
+
+    if(object$version!="fast")
+      {
+        cat("\n")
+        cat("Estimate... ",format(object$est,digits=digits),"\n")
+        cat("AI SE...... ",format(object$se,digits=digits),"\n")
+        cat("T-stat..... ",format(object$est/object$se,digits=digits),"\n")
+        cat("p.val...... ",format.pval((1-pnorm(abs(object$est/object$se)))*2,digits=digits),"\n")
+        cat("\n")
+      } else {
+        cat("\n")
+        cat("Estimate... ",format(object$est,digits=digits),"\n")
+        cat("SE......... ",format(object$se.standard,digits=digits),"\n")
+        cat("T-stat..... ",format(object$est/object$se.standard,digits=digits),"\n")
+        cat("p.val...... ",format.pval((1-pnorm(abs(object$est/object$se.standard)))*2,digits=digits),"\n")
+        cat("\n")        
+      }
+
+    if(full)
+      {
+        cat("Est noAdj.. ",format(object$est.noadj,digits=digits),"\n")        
+        cat("SE......... ",format(object$se.standard,digits=digits),"\n")
+        cat("T-stat..... ",format(object$est.noadj/object$se.standard,digits=digits),"\n")
+        cat("p.val...... ",format.pval((1-pnorm(abs(object$est.noadj/object$se.standard)))*2,digits=digits),"\n")
+        cat("\n")
+      }
+
+
+    if(object$orig.wnobs!=object$orig.nobs)
+      cat("Original number of observations (weighted)... ", round(object$orig.wnobs, 3),"\n")
+    cat("Original number of observations.............. ", object$orig.nobs,"\n")
+    if(object$mdata$orig.weighted.treated.nobs!=object$orig.treated.nobs)
+      cat("Original number of treated obs (weighted).... ", round(object$mdata$orig.weighted.treated.nobs, 3),"\n")
+    if(object$estimand!="ATC")
+      {
+        cat("Original number of treated obs............... ", object$orig.treated.nobs,"\n")
+      } else {
+        cat("Original number of control obs............... ",
+            object$orig.nobs-object$orig.treated.nobs,"\n")        
+      }
+    cat("Matched number of observations............... ", round(object$wnobs, 3),"\n")
+    cat("Matched number of observations  (unweighted). ", length(object$index.treated),"\n")
+
+    cat("\n")
+    if(!is.null(object$exact))
+      {
+        cat("Number of obs dropped by 'exact' or 'caliper' ", object$ndrops.matches, "\n")
+        if (object$ndrops.matches!=round(object$ndrops))
+          cat("Weighted #obs dropped by 'exact' or 'caliper' ", round(object$ndrops, 3),"\n")        
+        cat("\n")        
+      }else if(!is.null(object$caliper))
+      {
+        cat("Caliper (SDs)........................................  ",object$caliper,"\n")            
+        cat("Number of obs dropped by 'exact' or 'caliper' ", object$ndrops.matches, "\n")
+        if (object$ndrops.matches!=round(object$ndrops))
+          cat("Weighted #obs dropped by 'exact' or 'caliper' ", round(object$ndrops, 3),"\n")        
+        cat("\n")
+      }
+    
+    z <- list()
+    class(z) <- "summary.Match"
+    return(invisible(z))
+  } #end of summary.Match
+
+print.summary.Match <- function(x, ...)
+  {
+    invisible(NULL)
+  }
+
+
+Rmatch <- function(Y, Tr, X, Z, V, All, M, BiasAdj, Weight, Weight.matrix, Var.calc, weight,
+                   SAMPLE, ccc, cdd, ecaliper=NULL, restrict=NULL)
+  {
+    sum.caliper.drops <- 0
+    X.orig <- X
+
+#are we using the restriction matrix?
+    if(is.matrix(restrict)) {
+      restrict.trigger <- TRUE
+    } else {
+      restrict.trigger <- FALSE
+    }
+    
+# if SATC is to be estimated the treatment indicator is reversed  
+    if (All==2) {
+      Tr <- 1-Tr
+    }
+
+    
+
+# check on the number of matches, to make sure the number is within the limits
+# feasible given the number of observations in both groups.
+    if (All==1)
+      {
+        M <- min(M,min(sum(Tr),sum(1-Tr)));        
+      } else {
+        M <- min(M,sum(1-Tr));
+      }
+
+# two slippage parameters that are used to determine whether distances are equal
+# distances less than ccc or cdd are interpeted as zero.
+# these are passed in.  ccc, cdd
+
+
+# I. set up
+# I.a. vector for which observations we want the average effect
+# iot_t is the vector with weights in the average treatment effects
+# iot_c is the vector of indicators for potential controls
+
+    if (All==1)
+      {
+        iot.t <- weight;
+        iot.c <- as.matrix(rep(1,length(Tr)))
+      } else {
+        iot.t <- Tr*weight;
+        iot.c <- 1-Tr    
+      }
+
+# I.b. determine sample and covariate vector sizes
+    N  <- nrow(X)
+    Kx <- ncol(X)
+    Kz <- ncol(Z)
+
+# K covariates
+# N observations
+#    Nt <- sum(Tr)
+#    Nc <- sum(1-Tr)
+#    on <- as.matrix(rep(1,N))
+
+# I.c. normalize regressors to have mean zero and unit variance.
+# If the standard deviation of a variable is zero, its normalization
+# leads to a variable with all zeros.
+# The matrix AA enables one to transform the user supplied weight matrix 
+# to take account of this transformation.  BUT THIS IS NOT USED!!
+# Mu_X and Sig_X keep track of the original mean and variances
+#    AA    <- diag(Kx)
+    Mu.X  <- matrix(0, Kx, 1)
+    Sig.X <- matrix(0, Kx, 1)
+
+    for (k in 1:Kx)
+      {
+        Mu.X[k,1] <- sum(X[,k]*weight)/sum(weight)
+        eps <- X[,k]-Mu.X[k,1]
+        Sig.X[k,1] <- sqrt(sum(X[,k]*X[,k]*weight)/sum(weight)-Mu.X[k,1]^2)
+        Sig.X[k,1] <- Sig.X[k,1]*sqrt(N/(N-1))
+        if(Sig.X[k,1] < ccc)
+          Sig.X[k,1] <- ccc
+        X[,k]=eps/Sig.X[k,1]
+#        AA[k,k]=Sig.X[k,1]
+      } #end of k loop
+
+#    Nv <- nrow(V)
+    Mv <- ncol(V)
+    Mu.V  <- matrix(0, Mv, 1)
+    Sig.V <- matrix(0, Mv, 1)
+
+    for (j in 1:Mv)
+      {
+        Mu.V[j,1]= ( t(V[,j])%*%weight ) /sum(weight)
+#        dv <- V[,j]-Mu.V[j,1]
+        sv <- sum(V[,j]*V[,j]*weight)/sum(weight)-Mu.V[j,1]^2
+        if (sv > 0)
+          {
+            sv <- sqrt(sv)
+          } else {
+            sv <- 0
+          }
+        sv <- sv * sqrt(N/(N-1))
+        Sig.V[j,1] <- sv
+      } #end of j loop
+
+# I.d. define weight matrix for metric, taking into account normalization of
+# regressors.
+# If the eigenvalues of the regressors are too close to zero the Mahalanobis metric
+# is not used and we revert back to the default inverse of variances.
+    if (Weight==1)
+      {
+        Weight.matrix=diag(Kx)
+      } else if (Weight==2) {
+        if (min (eigen( t(X)%*%X/N, only.values=TRUE)$values) > ccc)
+          {
+            Weight.matrix= solve(t(X)%*%X/N) 
+          } else {
+            Weight.matrix <- diag(Kx)
+          }
+      }
+      # DO NOT RESCALE THE Weight.matrix!!
+      #else if (Weight==3)
+      #  {
+      #    Weight.matrix <- AA %*% Weight.matrix %*% AA
+      #  }
+
+#    if (exact==1)
+#      {
+#        Weight.matrix <- cbind(Weight.matrix, matrix(0,nrow=Kx,ncol=Mv))
+#        Weight.matrix <- rbind(Weight.matrix, cbind(matrix(0,nrow=Mv,ncol=Kx),
+#                               1000*solve(diag(as.vector(Sig.V*Sig.V), nrow=length(Sig.V)))))
+#        Weight.matrix <- as.matrix(Weight.matrix)
+#        X <- cbind(X,V)
+#        Mu.X  <- rbind(Mu.X, matrix(0, nrow(Mu.V), 1))
+#        Sig.X <- rbind(Sig.X, matrix(1, nrow(Sig.V), 1))
+#      } #end of exact
+
+    Nx <- nrow(X)
+    Kx <- ncol(X)
+
+    if ( min(eigen(Weight.matrix, only.values=TRUE)$values) < ccc )
+      Weight.matrix <- Weight.matrix + diag(Kx)*ccc
+
+    # I.fg. initialize matrices before looping through sample
+    YCAUS  <- as.matrix(rep(0, N))
+    SCAUS  <- as.matrix(rep(0, N))
+    XCAUS  <- matrix(0, nrow=N, ncol=Kx)
+    ZCAUS  <- matrix(0, nrow=N, ncol=Kz)
+    Kcount <- as.matrix(rep(0, N))
+    KKcount <- as.matrix(rep(0, N))
+    MMi     <- as.matrix(rep(0, N))
+
+# II. Loop through all observations that need to be matched.
+    INN <- as.matrix(1:N)
+    ww <- chol(Weight.matrix) # so that ww*ww=w.m
+#    TT <- as.matrix(1:N)
+
+    # initialize some data objects
+    DD <- NULL
+    I  <- NULL
+    IM <- NULL
+    IT <- NULL
+    IX <- NULL
+    IZ <- NULL
+    IY <- NULL
+    W  <- NULL
+    ADist <- NULL
+    WWi <- NULL
+    Xt <- NULL
+    Zt <- NULL
+    Yt <- NULL
+    Xc <- NULL
+    Zc <- NULL
+    Yc <- NULL
+
+    for (i in 1:N)
+      {
+        #treatment indicator for observation to be matched        
+        TREATi <- Tr[i]
+
+        # proceed with all observations if All==1
+        # but only with treated observations if All=0        
+        if ( (TREATi==1 & All!=1) | All==1 )
+          {
+            # covariate value for observation to be matched                        
+            xx <- t(as.matrix(X[i,]))
+
+            # covariate value for observation to be matched            
+            zz <- t(as.matrix(Z[i,]))
+
+            # outcome value for observation to be matched                        
+            yy <- Y[i]
+
+            #JSS: check *
+            foo <- as.matrix(rep(1, Nx))
+            DX <- (X - foo %*% xx) %*% t(ww)
+
+            if (Kx>1)
+              {
+                #JSS
+                foo <- t(DX*DX)
+                Dist <- as.matrix(apply(foo, 2, sum))
+              } else {
+                Dist <- as.matrix(DX*DX)
+              } #end of Kx
+
+            # Dist distance to observation to be matched
+            # is N by 1 vector
+
+            #use the restriction matrix
+            if (restrict.trigger)
+              {
+                for (j in 1:nrow(restrict))
+                  {
+                    if (restrict[j,1]==i)
+                      {
+                        if (restrict[j,3] < 0) {
+                          Dist[restrict[j,2]] = .Machine$double.xmax
+                        } else {
+                          Dist[restrict[j,2]] = restrict[j,3]
+                        }
+                      } else if (restrict[j,2]==i) {
+                        if (restrict[j,3] < 0) {
+                          Dist[restrict[j,1]] = .Machine$double.xmax
+                        } else {
+                          Dist[restrict[j,1]] = restrict[j,3]
+                        }
+                      }
+                  }
+              } #end if restrict.trigger
+
+            # set of potential matches (all observations with other treatment)
+            # JSS, note:logical vector
+            POTMAT <- Tr == (1-TREATi) 
+
+            # X's for potential matches
+#            XPOT <- X[POTMAT,]
+            DistPot <- Dist[POTMAT,1]
+
+#            TTPotMat <- TT[POTMAT,1]
+            weightPot <- as.matrix(weight[POTMAT,1])
+
+            # sorted distance of potential matches            
+            S <- sort(DistPot)
+            L <- order(DistPot)
+            weightPot.sort <- weightPot[L,1]
+            weightPot.sum <- cumsum(weightPot.sort)
+            tt <- 1:(length(weightPot.sum))
+            MMM <- min(tt[weightPot.sum>=M])
+
+            # distance at last match
+            Distmax <- S[MMM]
+
+            # selection of actual matches 
+            #logical index
+            if (restrict.trigger)
+              {
+                ACTMAT <- POTMAT & ( (Dist <= (Distmax+cdd))  & (Dist < .Machine$double.xmax) )
+
+                if (sum(ACTMAT) < 1)
+                  next;                
+              } else {
+                ACTMAT <- POTMAT & ( Dist <= (Distmax+cdd) )
+              }
+            
+            Ii <- i * matrix(1, nrow=sum(ACTMAT), ncol=1)
+            IMi <- as.matrix(INN[ACTMAT,1])
+            
+            if(!is.null(ecaliper))
+              {
+                for (j in 1:length(Ii))
+                  {
+                    for( x in 1:Kx)
+                      {
+                        diff <- abs(X.orig[i,x] - X.orig[IMi[j], x])
+                        if (diff > ecaliper[x])
+                          {
+#                            print(diff)
+
+                            ACTMAT[IMi[j]] <- FALSE
+                            sum.caliper.drops <- sum.caliper.drops+1
+                            
+                            break
+                          }
+                      } #x loop
+                  } #j loop
+
+                if (sum(ACTMAT) < 1)
+                  next;
+              } #ecaliper check
+
+            # distance to actual matches            
+            ACTDIST <- as.matrix(Dist[ACTMAT,1])
+
+            # counts how many times each observation is matched.
+            Kcount <- Kcount + weight[i] * weight*ACTMAT/sum(ACTMAT*weight)
+            
+            KKcount <- KKcount+weight[i,1] * weight*weight*ACTMAT /
+              (sum(ACTMAT*weight)*sum(ACTMAT*weight))
+
+            # counts how many times each observation is matched.
+            # counts number of matches for observation i
+            # Unless there are ties this should equal M
+
+            Mi <- sum(weight*ACTMAT)            
+            MMi[i,1] <- Mi
+            Wi <- as.matrix(weight[ACTMAT,1])
+
+            # mean of Y's for actual matches
+            ymat <- t(Y[ACTMAT,1]) %*% Wi/Mi
+
+            # mean of X's for actual matches
+            # mean of Z's for actual matches
+            if (length(Wi)>1)
+              {
+                xmat <- t(t(X[ACTMAT,]) %*% Wi/Mi)
+                zmat <- t(t(Z[ACTMAT,]) %*% Wi/Mi)
+              } else {
+                xmat <- t(X[ACTMAT,]) * as.double(Wi)/Mi
+                zmat <- t(Z[ACTMAT,]) * as.double(Wi)/Mi
+              }
+
+            # estimate causal effect on y for observation i
+            YCAUS[i,1] <- TREATi %*% (yy-ymat)+(1-TREATi) %*% (ymat-yy)
+
+            # difference between x and actual matches for observation i
+            XCAUS[i,] <- TREATi %*% (xx-xmat)+(1-TREATi) %*% (xmat-xx)
+
+            ZCAUS[i,] <- TREATi %*% (zz-zmat)+(1-TREATi) %*% (zmat-zz)
+
+            # collect results
+            I  <- rbind(I, i * matrix(1, nrow=sum(ACTMAT), ncol=1))
+            DD <- rbind(DD, ACTDIST)
+            IM <- rbind(IM, as.matrix(INN[ACTMAT,1]))
+            IT <- rbind(IT, TREATi * as.matrix(rep(1, sum(ACTMAT))))
+            IX <- rbind(IX, as.matrix(rep(1, sum(ACTMAT))) %*% xx)
+            IZ <- rbind(IZ, as.matrix(rep(1, sum(ACTMAT))) %*% zz)
+            IY <- rbind(IY, as.matrix(rep(1, sum(ACTMAT))) * yy)
+
+            # weight for matches
+            W <- as.matrix(c(W, weight[i,1] * Wi/Mi))
+            ADist <- as.matrix(c(ADist, ACTDIST))
+            WWi   <- as.matrix(c(WWi, Wi))
+
+            if (TREATi==1)
+              {
+
+                if (ncol(X) > 1)
+                  {
+                    # covariates for treated
+                    Xt <- rbind(Xt, as.matrix(rep(1, sum(ACTMAT))) %*% xx)                    
+                    # covariate for matches
+                    Xc <- rbind(Xc, X[ACTMAT,])
+                    
+                  } else {
+                    # covariates for treated
+                    Xt <- as.matrix(c(Xt, as.matrix(rep(1, sum(ACTMAT))) %*% xx))
+                    # covariate for matches
+                    Xc <- as.matrix(c(Xc, X[ACTMAT,]))
+                  }
+
+                if (ncol(Z) > 1)
+                  {
+                    # covariates for treated                
+                    Zt <- rbind(Zt, as.matrix(rep(1, sum(ACTMAT))) %*% zz)
+                    # covariate for matches
+                    Zc <- rbind(Zc, Z[ACTMAT,])
+                  } else {
+                    # covariates for treated                
+                    Zt <- as.matrix(c(Zt, as.matrix(rep(1, sum(ACTMAT))) %*% zz))
+                    # covariate for matches                
+                    Zc <- as.matrix(c(Zc, Z[ACTMAT,]))
+                  }
+
+                # outcome for treated                              
+                Yt <- as.matrix(c(Yt, yy * as.matrix(rep(1, sum(ACTMAT))) ))
+                # outcome for matches
+                Yc <- as.matrix(c(Yc, Y[ACTMAT,1]))
+              } else {
+
+                if (ncol(X) > 1)
+                  {
+                    # covariates for controls
+                    Xc <- rbind(Xc, as.matrix(rep(1, sum(ACTMAT))) %*% xx)
+                    # covariate for matches
+                    Xt <- rbind(Xt, X[ACTMAT,])
+                  } else {
+                    # covariates for controls                
+                    Xc <- as.matrix(c(Xc, as.matrix(rep(1, sum(ACTMAT))) %*% xx))
+                    # covariate for matches
+                    Xt <- as.matrix(c(Xt, X[ACTMAT,]))
+                  }
+
+                if (ncol(Z) > 1)
+                  {
+                    # covariates for controls                
+                    Zc <- rbind(Zc, as.matrix(rep(1, sum(ACTMAT))) %*% zz)
+                    # covariate for matches                
+                    Zt <- rbind(Zt, Z[ACTMAT,])
+                  } else {
+                    # covariates for controls                
+                    Zc <- as.matrix(c(Zc, as.matrix(rep(1, sum(ACTMAT))) %*% zz))
+                    # covariate for matches                
+                    Zt <- as.matrix(c(Zt, Z[ACTMAT,]))
+                  }
+                # outcome for controls                               
+                Yc <- as.matrix(c(Yc, as.matrix(rep(1, sum(ACTMAT))) * yy))
+                # outcome for matches
+                Yt <- as.matrix(c(Yt, Y[ACTMAT,1]))
+
+              } #end of TREATi
+          } #end of if
+      } #i loop
+
+    # transform matched covariates back for artificial data set
+    Xt.u <- Xt
+    Xc.u <- Xc
+    IX.u <- IX
+    for (k in 1:Kx)
+      {
+        Xt.u[,k] <- Mu.X[k,1]+Sig.X[k,1] * Xt.u[,k]
+        Xc.u[,k] <- Mu.X[k,1]+Sig.X[k,1] * Xc.u[,k]
+        IX.u[,k] <- Mu.X[k,1]+Sig.X[k,1] * IX.u[,k]
+      }
+    if (All!=1)
+      {
+        I  <- as.matrix(I[IT==1,])
+        IM <- as.matrix(IM[IT==1,])
+        IT <- as.matrix(IT[IT==1,])
+        IY <- as.matrix(IY[IT==1,])
+        Yc <- as.matrix(Yc[IT==1,])
+        Yt <- as.matrix(Yt[IT==1,])
+        W  <- as.matrix(W[IT==1,])
+        ADist <- as.matrix(ADist[IT==1,])
+        WWi   <- as.matrix(WWi[IT==1,])
+        IX.u  <- as.matrix(IX.u[IT==1,])
+        Xc.u  <- as.matrix(Xc.u[IT==1,])
+        Xt.u  <- as.matrix(Xt.u[IT==1,])
+        Xc    <- as.matrix(Xc[IT==1,])
+        Xt <- as.matrix(Xt[IT==1,])
+        Zc <- as.matrix(Zc[IT==1,])
+        Zt <- as.matrix(Zt[IT==1,])
+        IZ <- as.matrix(IZ[IT==1,])
+      } #end of if
+
+    if (length(I) < 1)
+      {
+        return(list(sum.caliper.drops=sum.caliper.drops,valid=0))
+      } else if(length(I) < 2)
+        {
+          return(list(sum.caliper.drops=sum.caliper.drops,valid=1))          
+        }
+
+    if (BiasAdj==1)
+      {
+        # III. Regression of outcome on covariates for matches
+        if (All==1)
+          {
+            # number of observations
+            NNt <- nrow(Z)
+            # add intercept        
+            ZZt <- cbind(rep(1, NNt), Z)
+            # number of covariates
+            Nx <- nrow(ZZt)
+            Kx <- ncol(ZZt)
+            xw <- ZZt*(sqrt(Tr*Kcount) %*% t(as.matrix(rep(1,Kx))))
+            
+            foo <- min(eigen(t(xw)%*%xw, only.values=TRUE)$values)
+            foo <- as.double(foo<=ccc)
+            foo2 <- apply(xw, 2, sd)
+
+            options(show.error.messages = FALSE)
+            wout <- NULL
+            try(wout <- solve( t(xw) %*% xw + diag(Kx) * ccc * (foo) * max(foo2)) %*%
+                (t(xw) %*% (Y*sqrt(Tr*Kcount))))
+            if(is.null(wout))
+              {
+                wout2 <- NULL
+                try(wout2 <- ginv( t(xw) %*% xw + diag(Kx) * ccc * (foo) * max(foo2)) %*%
+                    (t(xw) %*% (Y*sqrt(Tr*Kcount))))
+                if(!is.null(wout2))
+                  {
+                    wout <-wout2
+                    warning("using generalized inverse to calculate Bias Adjustment probably because of singular 'Z'")
+                  }
+              }
+            options(show.error.messages = TRUE)
+            if(is.null(wout))
+              {
+                warning("unable to calculate Bias Adjustment probably because of singular 'Z'")
+                BiasAdj <- 0
+              } else {
+                NW <- nrow(wout)
+#                KW <- ncol(wout)
+                Alphat <- wout[2:NW,1]
+              }
+          } else {
+            Alphat <- matrix(0, nrow=Kz, ncol=1)
+          } #end if ALL
+      }
+
+    if(BiasAdj==1)
+      {
+        # III.b.  Controls
+        NNc <- nrow(Z)
+        ZZc <- cbind(matrix(1, nrow=NNc, ncol=1),Z)
+        Nx <- nrow(ZZc)
+        Kx <- ncol(ZZc)
+        
+        xw <- ZZc*(sqrt((1-Tr)*Kcount) %*% matrix(1, nrow=1, ncol=Kx))
+        
+        foo <- min(eigen(t(xw)%*%xw, only.values=TRUE)$values)
+        foo <- as.double(foo<=ccc)
+        foo2 <- apply(xw, 2, sd)
+
+        options(show.error.messages = FALSE)
+        wout <- NULL        
+        try(wout <- solve( t(xw) %*% xw + diag(Kx) * ccc * (foo) * max(foo2)) %*%
+            (t(xw) %*% (Y*sqrt((1-Tr)*Kcount))))
+        if(is.null(wout))
+          {
+            wout2 <- NULL
+            try(wout2 <- ginv( t(xw) %*% xw + diag(Kx) * ccc * (foo) * max(foo2)) %*%
+                (t(xw) %*% (Y*sqrt((1-Tr)*Kcount))))
+            if(!is.null(wout2))
+              {
+                wout <-wout2
+                warning("using generalized inverse to calculate Bias Adjustment probably because of singular 'Z'")
+              }
+          }        
+        options(show.error.messages = TRUE)
+        if(is.null(wout))
+          {
+            warning("unable to calculate Bias Adjustment probably because of singular 'Z'")
+            BiasAdj <- 0
+          } else {
+            NW <- nrow(wout)
+#            KW <- ncol(wout)
+            Alphac <- as.matrix(wout[2:NW,1])
+          }
+      }
+    
+
+    if(BiasAdj==1)
+      {
+        # III.c. adjust matched outcomes using regression adjustment for bias adjusted matching estimator
+
+        SCAUS <- YCAUS-Tr*(ZCAUS %*% Alphac)-(1-Tr)*(ZCAUS %*% Alphat)
+        # adjusted control outcome
+        Yc.adj <- Yc+BiasAdj * (IZ-Zc) %*% Alphac
+        # adjusted treated outcome
+        Yt.adj <- Yt+BiasAdj*(IZ-Zt) %*% Alphat
+        Tau.i <- Yt.adj - Yc.adj
+      } else {
+        Yc.adj <- Yc
+        Yt.adj <- Yt
+        Yt.adj <- Yt
+        Tau.i <- Yt.adj - Yc.adj        
+      }
+
+    art.data <- cbind(I,IM,IT,DD,IY,Yc,Yt,W,WWi,ADist,IX.u,Xc.u,Xt.u,
+                      Yc.adj,Yt.adj,Tau.i)
+
+
+    # III. If conditional variance is needed, initialize variance vector
+    # and loop through all observations
+
+    Nx <- nrow(X)
+    Kx <- ncol(X)
+
+#   ww <- chol(Weight.matrix)
+#   NN <- as.matrix(1:N)
+    if (Var.calc>0)
+      {
+        Sig <- matrix(0, nrow=N, ncol=1)
+        # overall standard deviation of outcome
+        # std <- sd(Y)
+        for (i in 1:N)
+          {
+            # treatment indicator observation to be matched
+            TREATi <- Tr[i,1]
+            # covariate value for observation to be matched
+            xx <- X[i,]
+            # potential matches are all observations with the same treatment value
+            POTMAT <- (Tr==TREATi)
+            POTMAT[i,1] <- 0
+            weightPOT <- as.matrix(weight[POTMAT==1,1])
+            DX <- (X - matrix(1, Nx,1) %*% xx) %*% t(ww)
+            if (Kx>1)
+              {
+                foo <- apply(t(DX*DX), 2, sum)
+                Dist <- as.matrix(foo)
+              } else {
+                Dist <- DX*DX
+              }
+
+            # distance to observation to be matched
+
+            # Distance vector only for potential matches
+            DistPot <- Dist[POTMAT==1,1]
+            # sorted distance of potential matches
+            S <- sort(DistPot)
+            L <- order(DistPot)
+            weightPOT.sort <- weightPOT[L,1]
+            weightPOT.sum <- cumsum(weightPOT.sort)
+            tt <-  1:(length(weightPOT.sum))
+            MMM <- min(tt[weightPOT.sum >= Var.calc])
+            MMM <- min(MMM,length(S))
+            Distmax=S[MMM]
+
+            # distance of Var_calc-th closest match
+            ACTMAT <- (POTMAT==1) & (Dist<= (Distmax+ccc))
+
+            # indicator for actual matches, that is all potential
+            # matches closer than, or as close as the Var_calc-th
+            # closest
+
+            Yactmat <- as.matrix(c(Y[i,1], Y[ACTMAT,1]))
+            weightactmat <- as.matrix(c(weight[i,1], weight[ACTMAT,1]))
+            fm <- t(Yactmat) %*% weightactmat/sum(weightactmat)
+            sm <- sum(Yactmat*Yactmat*weightactmat)/sum(weightactmat)
+            sigsig <- (sm-fm %*% fm)*sum(weightactmat)/(sum(weightactmat)-1)
+            
+            # standard deviation of actual matches
+            Sig[i,1] <- sqrt(sigsig)
+          }# end of i loop
+        #variance estimate 
+        Sigs <- Sig*Sig
+      } #end of var.calc > 0
+
+    # matching estimator
+    est <- t(W) %*% Tau.i/sum(W)
+#    est.t <- sum((iot.t*Tr+iot.c*Kcount*Tr)*Y)/sum(iot.t*Tr+iot.c*Kcount*Tr)
+#    est.c <- sum((iot.t*(1-Tr)+iot.c*Kcount*(1-Tr))*Y)/sum(iot.t*(1-Tr)+iot.c*Kcount*(1-Tr))
+
+    if (Var.calc==0)
+      {
+        eps <- Tau.i - as.double(est)
+        eps.sq <- eps*eps
+        Sigs <- 0.5 * matrix(1, N, 1) %*% (t(eps.sq) %*% W)/sum(W)
+#        sss <- sqrt(Sigs[1,1])
+      } #end of Var.calc==0
+
+    SN <- sum(iot.t)
+    var.sample <- sum((Sigs*(iot.t+iot.c*Kcount)*(iot.t+iot.c*Kcount))/(SN*SN))
+
+    if (All==1)
+      {
+        var.pop <- sum((Sigs*(iot.c*Kcount*Kcount+2*iot.c*Kcount-iot.c*KKcount))/(SN*SN))
+      } else {
+        var.pop=sum((Sigs*(iot.c*Kcount*Kcount-iot.c*KKcount))/(SN*SN))
+      }
+
+    if (BiasAdj==1)
+      {
+        dvar.pop <- sum(iot.t*(SCAUS-as.double(est))*(SCAUS-as.double(est)))/(SN*SN)
+      } else {
+        dvar.pop <- sum(iot.t*(YCAUS-as.double(est))*(YCAUS-as.double(est)))/(SN*SN)
+      }
+
+    var.pop <- var.pop + dvar.pop
+
+    if (SAMPLE==1)
+      {
+        var <- var.sample
+      } else {
+        var <- max(var.sample, var.pop)
+        var <- var.pop
+      }
+
+    var.cond <- max(var.sample,var.pop)-var.sample
+    se <- sqrt(var)
+    se.cond <- sqrt(var.cond)
+
+#    Sig <- sqrt(Sigs)
+#    aug.data <- cbind(Y,Tr,X,Z,Kcount,Sig,weight)
+
+    if (All==2)
+      est <- -1*est
+
+#    if (exact==1)
+#      {
+#        Vt.u <- Xt.u[,(Kx-Mv+1):Kx]
+#        Vc.u <- Xc.u[,(Kx-Mv+1):Kx]
+#        Vdif <- abs(Vt.u-Vc.u)
+#
+#        if (Mv>1)
+#          Vdif <- as.matrix(apply(t(Vdif), 2, sum))
+#
+#        em[1,1] <- length(Vdif)
+#        em[2,1] <- sum(Vdif>0.000001)
+#      }#end of exact==1
+
+    return(list(est=est, se=se, se.cond=se.cond, W=W,
+                sum.caliper.drops=sum.caliper.drops,
+                art.data=art.data))
+  }# end of Rmatch
+
+
+#
+# See Rosenbaum and Rubin (1985) and Smith and Todd Rejoinder (JofEconometrics) p.9
+#
+sdiff.pooled  <- function(Tr, Co, weights=rep(1,length(Co)),
+                          weights.Tr=rep(1,length(Tr)),
+                          weights.Co=rep(1,length(Co)),
+                          match=FALSE)
+  {
+    if (!match)
+      {
+        obs.Tr <- sum(weights.Tr)
+        obs.Co <- sum(weights.Co)
+#        obs.total <- obs.Tr+obs.Co
+        
+        mean.Tr <- sum(Tr*weights.Tr)/obs.Tr
+        mean.Co <- sum(Co*weights.Co)/obs.Co
+        diff  <- mean.Tr - mean.Co
+
+#match Rubin
+#        mean.total <- sum(Tr*weights.Tr)/obs.total + sum(Co*weights.Co)/obs.total
+#        var.total  <- sum( ( (Tr - mean.total)^2 )*weights.Tr)/(obs.total-1) +
+#          sum( ( (Co - mean.total)^2 )*weights.Co)/(obs.total-1)
+        var.pooled <- ( sum( ( (Tr - mean.Tr)^2)*weights.Tr)/(obs.Tr-1) +
+          sum( ( (Co - mean.Co)^2 )*weights.Co)/(obs.Co-1) )/2 
+        
+
+        if(var.pooled==0 & diff==0)
+          {
+            sdiff <- 0
+          } else {
+            sdiff <- 100*diff/sqrt( var.pooled )
+          }
+        
+      } else{
+        diff  <- sum( (Tr-Co)*weights ) /sum(weights)
+        mean.Tr <- sum(Tr*weights)/sum(weights)
+        mean.Co <- sum(Co*weights)/sum(weights)
+
+#match Rubin
+        obs <- sum(weights)
+
+#       obs for total        
+#       obs = sum(weights)*2
+#        mean.total <- (mean.Tr + mean.Co)/2
+#        var.total  <- sum( ( (Tr - mean.total)^2 )*weights)/(obs-1) +
+#          sum( ( (Co - mean.total)^2 )*weights)/(obs-1)
+        
+        var.pooled  <- ( sum( ( (Tr - mean.Tr)^2 )*weights)/(obs-1) +
+          sum( ( (Co - mean.Co)^2 )*weights)/(obs-1) )/2
+
+        if(var.pooled==0 & diff==0)
+          {
+            sdiff <- 0
+          } else {
+            sdiff <- 100*diff/sqrt(var.pooled)
+          }        
+      }
+
+    return(sdiff)
+  }
+
+
+#
+# STANDARDIZED BY THE VARIANCE OF THE TREATMENT GROUP
+# See sdiff.rubin for Rosenbaum and Rubin (1985) and Smith and Todd Rejoinder (JofEconometrics) p.9
+#
+sdiff  <- function(Tr, Co, weights=rep(1,length(Co)),
+                   weights.Tr=rep(1,length(Tr)),
+                   weights.Co=rep(1,length(Co)),
+                   match=FALSE,
+                   estimand="ATT")
+
+  {
+    if (!match)
+      {
+        obs.Tr <- sum(weights.Tr)
+        obs.Co <- sum(weights.Co)
+        
+        mean.Tr <- sum(Tr*weights.Tr)/obs.Tr
+        mean.Co <- sum(Co*weights.Co)/obs.Co
+        diff  <- mean.Tr - mean.Co
+
+        if(estimand=="ATC")
+          {
+            var  <- sum( ( (Co - mean.Co)^2 )*weights.Co)/(obs.Co-1)
+          } else {
+            var  <- sum( ( (Tr - mean.Tr)^2 )*weights.Tr)/(obs.Tr-1)
+          }
+
+        if(var==0 & diff==0)
+          {
+            sdiff=0
+          } else {
+            sdiff <- 100*diff/sqrt( (var) )
+          }
+      } else{
+        mean.Tr <- sum(Tr*weights)/sum(weights)
+        mean.Co <- sum(Co*weights)/sum(weights)
+        diff  <- mean.Tr - mean.Co
+
+        if(estimand=="ATC")
+          {
+            var  <- sum( ( (Co - mean.Co)^2 )*weights)/(sum(weights)-1)
+          } else {
+            var  <- sum( ( (Tr - mean.Tr)^2 )*weights)/(sum(weights)-1)
+          }
+
+        if(var==0 & diff==0)
+          {
+            sdiff <- 0
+          } else {
+            sdiff <- 100*diff/sqrt( (var) )
+          }        
+      }
+
+    return(sdiff)
+  }
+
+# function runs sdiff and t.test
+#
+balanceUV  <- function(Tr, Co, weights=rep(1,length(Co)), exact=FALSE, ks=FALSE, nboots=1000,
+                       paired=TRUE, match=FALSE,
+                       weights.Tr=rep(1,length(Tr)), weights.Co=rep(1,length(Co)),
+                       estimand="ATT")
+  {
+    ks.out  <- NULL
+
+    if (!match)
+      {
+        sbalance.pooled  <- sdiff.pooled(Tr=Tr, Co=Co,
+                                       weights.Tr=weights.Tr,
+                                       weights.Co=weights.Co,
+                                       match=FALSE)
+
+        sbalance.constvar  <- sdiff(Tr=Tr, Co=Co,
+                                    weights.Tr=weights.Tr,
+                                    weights.Co=weights.Co,
+                                    match=FALSE,
+                                    estimand=estimand)        
+
+        obs.Tr <- sum(weights.Tr)
+        obs.Co <- sum(weights.Co)        
+        
+        mean.Tr <- sum(Tr*weights.Tr)/obs.Tr
+        mean.Co <- sum(Co*weights.Co)/obs.Co
+        var.Tr  <- sum( ( (Tr - mean.Tr)^2 )*weights.Tr)/(obs.Tr-1)
+        var.Co  <- sum( ( (Co - mean.Co)^2 )*weights.Co)/(obs.Co-1)
+        var.ratio  <- var.Tr/var.Co
+
+        qqsummary <- qqstats(x=Tr, y=Co, standardize=TRUE)
+        qqsummary.raw <- qqstats(x=Tr, y=Co, standardize=FALSE)
+
+        tt  <- Mt.test.unpaired(Tr, Co,
+                                weights.Tr=weights.Tr,
+                                weights.Co=weights.Co)
+
+        if (ks)
+          ks.out <- ks.boot(Tr, Co,nboots=nboots)
+      } else {
+        sbalance.pooled  <- sdiff(Tr=Tr, Co=Co, weights=weights, match=TRUE)
+        sbalance.constvar  <- sdiff(Tr=Tr, Co=Co, weights=weights, match=TRUE, estimand=estimand)
+        
+        mean.Tr  <- sum(Tr*weights)/sum(weights);
+        mean.Co  <- sum(Co*weights)/sum(weights);
+        var.Tr  <- sum( ( (Tr - mean.Tr)^2 )*weights)/sum(weights);
+        var.Co  <- sum( ( (Co - mean.Co)^2 )*weights)/sum(weights);
+        var.ratio  <- var.Tr/var.Co
+
+        qqsummary <- qqstats(x=Tr, y=Co, standardize=TRUE)
+        qqsummary.raw <- qqstats(x=Tr, y=Co, standardize=FALSE)
+
+        if(paired)
+          {
+            tt  <- Mt.test(Tr, Co, weights)
+          } else {
+            tt  <- Mt.test.unpaired(Tr, Co, weights.Tr=weights, weights.Co=weights)
+          }
+        
+        if (ks)
+          ks.out  <- ks.boot(Tr, Co, nboots=nboots)
+      }        
+
+    ret  <- list(sdiff=sbalance.constvar,
+                 sdiff.pooled=sbalance.pooled,
+                 mean.Tr=mean.Tr,mean.Co=mean.Co,
+                 var.Tr=var.Tr,var.Co=var.Co, p.value=tt$p.value,
+                 var.ratio=var.ratio,
+                 ks=ks.out, tt=tt,
+                 qqsummary=qqsummary,
+                 qqsummary.raw=qqsummary.raw)
+
+    class(ret) <-  "balanceUV"
+    return(ret)
+  } #balanceUV
+
+summary.balanceUV  <- function(object, ..., digits=5)
+  {
+
+    if (class(object) != "balanceUV") {
+      warning("Object not of class 'balanceUV'")
+      return(NULL)
+    }
+
+    cat("mean treatment........", format(object$mean.Tr, digits=digits),"\n")
+    cat("mean control..........", format(object$mean.Co, digits=digits),"\n")
+    cat("std mean diff.........", format(object$sdiff, digits=digits),"\n\n")    
+
+    cat("mean raw eQQ diff.....", format(object$qqsummary.raw$meandiff, digits=digits),"\n")
+    cat("med  raw eQQ diff.....", format(object$qqsummary.raw$mediandiff, digits=digits),"\n")
+    cat("max  raw eQQ diff.....", format(object$qqsummary.raw$maxdiff, digits=digits),"\n\n")
+
+    cat("mean eCDF diff........", format(object$qqsummary$meandiff, digits=digits),"\n")
+    cat("med  eCDF diff........", format(object$qqsummary$mediandiff, digits=digits),"\n")
+    cat("max  eCDF diff........", format(object$qqsummary$maxdiff, digits=digits),"\n\n")
+
+    cat("var ratio (Tr/Co).....", format(object$var.ratio, digits=digits),"\n")
+    cat("T-test p-value........", format.pval(object$tt$p.value,digits=digits), "\n")            
+    if (!is.null(object$ks))
+      {
+        if(!is.na(object$ks$ks.boot.pvalue))
+          {
+            cat("KS Bootstrap p-value..", format.pval(object$ks$ks.boot.pvalue, digits=digits), "\n")
+          }
+        cat("KS Naive p-value......", format(object$ks$ks$p.value, digits=digits), "\n")                        
+        cat("KS Statistic..........", format(object$ks$ks$statistic, digits=digits), "\n")
+      }
+    cat("\n")
+  } #end of summary.balanceUV
+
+
+#print Before and After balanceUV together
+PrintBalanceUV  <- function(BeforeBalance, AfterBalance, ..., digits=5)
+  {
+
+    if (class(BeforeBalance) != "balanceUV") {
+      warning("BeforeBalance not of class 'balanceUV'")
+      return(NULL)
+    }
+
+    if (class(AfterBalance) != "balanceUV") {
+      warning("AfterBalance not of class 'balanceUV'")
+      return(NULL)
+    }
+
+    space.size <- digits*2
+#    space <- rep(" ",space.size)
+
+    cat("                      ", "Before Matching", "\t \t After Matching\n")
+    cat("mean treatment........", format(BeforeBalance$mean.Tr, digits=digits, width=space.size), "\t \t",
+        format(AfterBalance$mean.Tr, digits=digits, width=space.size), 
+        "\n")
+    cat("mean control..........", format(BeforeBalance$mean.Co, digits=digits, width=space.size), "\t \t",
+        format(AfterBalance$mean.Co, digits=digits, width=space.size),
+        "\n")
+    cat("std mean diff.........", format(BeforeBalance$sdiff, digits=digits, width=space.size), "\t \t",
+        format(AfterBalance$sdiff, digits=digits, width=space.size),
+        "\n\n")
+    
+    cat("mean raw eQQ diff.....", format(BeforeBalance$qqsummary.raw$meandiff, digits=digits, width=space.size), "\t \t",
+        format(AfterBalance$qqsummary.raw$meandiff, digits=digits, width=space.size),
+        "\n")
+    cat("med  raw eQQ diff.....", format(BeforeBalance$qqsummary.raw$mediandiff, digits=digits, width=space.size), "\t \t",
+        format(AfterBalance$qqsummary.raw$mediandiff, digits=digits, width=space.size),
+        "\n")
+    cat("max  raw eQQ diff.....", format(BeforeBalance$qqsummary.raw$maxdiff, digits=digits, width=space.size), "\t \t",
+        format(AfterBalance$qqsummary.raw$maxdiff, digits=digits, width=space.size),
+        "\n\n")
+
+    cat("mean eCDF diff........", format(BeforeBalance$qqsummary$meandiff, digits=digits, width=space.size), "\t \t",
+        format(AfterBalance$qqsummary$meandiff, digits=digits, width=space.size),
+        "\n")
+    cat("med  eCDF diff........", format(BeforeBalance$qqsummary$mediandiff, digits=digits, width=space.size), "\t \t",
+        format(AfterBalance$qqsummary$mediandiff, digits=digits, width=space.size),
+        "\n")
+    cat("max  eCDF diff........", format(BeforeBalance$qqsummary$maxdiff, digits=digits, width=space.size), "\t \t",
+        format(AfterBalance$qqsummary$maxdiff, digits=digits, width=space.size),
+        "\n\n")
+
+    cat("var ratio (Tr/Co).....", format(BeforeBalance$var.ratio, digits=digits, width=space.size), "\t \t",
+        format(AfterBalance$var.ratio, digits=digits, width=space.size),
+        "\n")
+    cat("T-test p-value........", format(format.pval(BeforeBalance$tt$p.value,digits=digits), justify="right", width=space.size), "\t \t",
+        format(format.pval(AfterBalance$tt$p.value,digits=digits), justify="right", width=space.size),
+        "\n")            
+    if (!is.null(BeforeBalance$ks))
+      {
+        if(!is.na(BeforeBalance$ks$ks.boot.pvalue))
+          {
+            cat("KS Bootstrap p-value..", format(format.pval(BeforeBalance$ks$ks.boot.pvalue, digits=digits),  justify="right",width=space.size), "\t \t",
+                format(format.pval(AfterBalance$ks$ks.boot.pvalue, digits=digits),  justify="right", width=space.size),
+                "\n")
+          }
+        cat("KS Naive p-value......", format(format.pval(BeforeBalance$ks$ks$p.value, digits=digits),  justify="right",width=space.size), "\t \t",
+            format(format.pval(AfterBalance$ks$ks$p.value, digits=digits),  justify="right",width=space.size),
+            "\n")                        
+        cat("KS Statistic..........", format(BeforeBalance$ks$ks$statistic, digits=digits, width=space.size), "\t \t",
+            format(AfterBalance$ks$ks$statistic, digits=digits, width=space.size),
+            "\n")
+      }
+    cat("\n")        
+  } #end of PrintBalanceUV
+
+
+#removed as of 0.99-7 (codetools)
+#McNemar  <- function(Tr, Co, weights=rep(1,length(Tr)))
+
+McNemar2 <- function (Tr, Co, correct = TRUE, weights=rep(1,length(Tr)))
+{
+  x  <- Tr
+  y  <- Co
+  if (is.matrix(x)) {
+    stop("this version of McNemar cannot handle x being a matrix")
+  } else {
+    if (is.null(y)) 
+      stop("if x is not a matrix, y must be given")
+    if (length(x) != length(y)) 
+      stop("x and y must have the same length")
+    DNAME <- paste(deparse(substitute(x)), "and", deparse(substitute(y)))
+    OK <- complete.cases(x, y)
+    x <- factor(x[OK])
+    y <- factor(y[OK])
+    r <- nlevels(x)
+    if ((r < 2) || (nlevels(y) != r))
+      {
+        stop("x and y must have the same number of levels (minimum 2)")
+      }
+  }
+  tx <- table(x, y)
+  facs  <- levels(x)
+  txw  <- tx
+  for(i in 1:r)
+    {
+      for(j in 1:r)
+        {
+          indx  <- x==facs[i] & y==facs[j]
+          txw[i,j]  <- sum(weights[indx]);
+        }
+    }
+  pdiscordant  <- sum( ( (x!=y)*weights )/sum(weights) )
+  x  <- txw
+  
+  PARAMETER <- r * (r - 1)/2
+  METHOD <- "McNemar's Chi-squared test"
+  if (correct && (r == 2) && any(x - t(x))) {
+    y <- (abs(x - t(x)) - 1)
+    METHOD <- paste(METHOD, "with continuity correction")
+  } else y <- x - t(x)
+  x <- x + t(x)
+  STATISTIC <- sum(y[upper.tri(x)]^2/x[upper.tri(x)])
+  PVAL <- pchisq(STATISTIC, PARAMETER, lower.tail = FALSE)
+  names(STATISTIC) <- "McNemar's chi-squared"
+  names(PARAMETER) <- "df"
+
+  RVAL <- list(statistic = STATISTIC, parameter = PARAMETER, 
+               p.value = PVAL, method = METHOD, data.name = DNAME,
+               pdiscordant=pdiscordant)
+  class(RVAL) <- "htest"
+  return(RVAL)
+}
+
+ks<-function(x,y,w=F,sig=T){
+#  Compute the Kolmogorov-Smirnov test statistic
+#
+# Code for the Kolmogorov-Smirnov test is adopted from the Splus code
+# written by Rand R. Wilcox for his book titled "Introduction to
+# Robust Estimation and Hypothesis Testing." Academic Press, 1997.
+#
+#  Also see 
+#@book( knuth1998,
+#  author=       {Knuth, Donald E.},
+#  title=        {The Art of Computer Programming, Vol. 2: Seminumerical Algorithms},
+#  edition=      "3rd",
+#  publisher=    "Addison-Wesley", address= "Reading: MA", 
+#  year=         1998
+#)
+# and Wilcox 1997 
+#
+#  w=T computes the weighted version instead. 
+#  sig=T indicates that the exact significance level is to be computed.
+#  If there are ties, the reported significance level is exact when
+#  using the unweighted test, but for the weighted test the reported
+#  level is too high.
+#
+#  This function uses the functions ecdf, kstiesig, kssig and kswsig
+#
+#  This function returns the value of the test statistic, the approximate .05
+#  critical value, and the exact significance level if sig=T.
+#
+#  Missing values are automatically removed
+#
+
+  ecdf<-function(x,val){
+  #  compute empirical cdf for data in x evaluated at val
+  #  That is, estimate P(X <= val) 
+  #
+    ecdf<-length(x[x<=val])/length(x)
+    ecdf
+  }#end ecdf
+  
+  x<-x[!is.na(x)]
+  y<-y[!is.na(y)]
+  w<-as.logical(w)
+  sig<-as.logical(sig)
+  tie<-logical(1)
+  tie<-F
+  siglevel<-NA
+  z<-sort(c(x,y))  # Pool and sort the observations
+  for (i in 2:length(z))if(z[i-1]==z[i])tie<-T #check for ties
+  v<-1   # Initializes v
+  for (i in 1:length(z))v[i]<-abs(ecdf(x,z[i])-ecdf(y,z[i]))
+  ks<-max(v)
+  crit<-1.36*sqrt((length(x)+length(y))/(length(x)*length(y))) # Approximate
+#                                                       .05 critical value
+  if(!w && sig && !tie)siglevel<-kssig(length(x),length(y),ks)
+  if(!w && sig && tie)siglevel<-kstiesig(x,y,ks)
+  if(w){
+    crit<-(max(length(x),length(y))-5)*.48/95+2.58+abs(length(x)-length(y))*.44/95
+    if(length(x)>100 || length(y)>100){
+      print("When either sample size is greater than 100,")
+      print("the approximate critical value can be inaccurate.")
+      print("It is recommended that the exact significance level be computed.")
+    }
+    for (i in 1:length(z)){
+      temp<-(length(x)*ecdf(x,z[i])+length(y)*ecdf(y,z[i]))/length(z)
+      temp<-temp*(1.-temp)
+      v[i]<-v[i]/sqrt(temp)
+    }
+    v<-v[!is.na(v)]
+    ks<-max(v)*sqrt(length(x)*length(y)/length(z))
+    if(sig)siglevel<-kswsig(length(x),length(y),ks)
+    if(tie && sig){
+      print("Ties were detected. The reported significance level")
+      print("of the weighted Kolmogorov-Smirnov test statistic is not exact.")
+    }}
+                                        #round off siglevel in a nicer way
+  if(is.double(ks) & is.double(crit) & !is.na(ks) & !is.na(crit))
+    {
+      if (is.na(siglevel) & ks < crit)
+        {
+          siglevel  <- 0.99999837212332
+        }
+      if (is.double(siglevel) & !is.na(siglevel))
+        {
+          if (siglevel < 0)
+            siglevel  <- 0
+        }
+    }
+  list(test=ks,critval=crit,pval=siglevel)
+}
+
+
+kssig<-function(m,n,val){
+#
+#    Compute significance level of the  Kolmogorov-Smirnov test statistic
+#    m=sample size of first group
+#    n=sample size of second group
+#    val=observed value of test statistic
+#
+  cmat<-matrix(0,m+1,n+1)
+  umat<-matrix(0,m+1,n+1)
+  for (i in 0:m){
+    for (j in 0:n)cmat[i+1,j+1]<-abs(i/m-j/n)
+  }
+  cmat<-ifelse(cmat<=val,1e0,0e0)
+  for (i in 0:m){
+    for (j in 0:n)if(i*j==0)umat[i+1,j+1]<-cmat[i+1,j+1]
+    else umat[i+1,j+1]<-cmat[i+1,j+1]*(umat[i+1,j]+umat[i,j+1])
+  }
+  term<-lgamma(m+n+1)-lgamma(m+1)-lgamma(n+1)
+  kssig<-1.-umat[m+1,n+1]/exp(term)
+  return(kssig)
+}
+
+kstiesig<-function(x,y,val){
+#
+#    Compute significance level of the  Kolmogorov-Smirnov test statistic
+#    for the data in x and y.
+#    This function allows ties among the  values.
+#    val=observed value of test statistic
+#
+m<-length(x)
+n<-length(y)
+z<-c(x,y)
+z<-sort(z)
+cmat<-matrix(0,m+1,n+1)
+umat<-matrix(0,m+1,n+1)
+for (i in 0:m){
+for (j in 0:n){
+if(abs(i/m-j/n)<=val)cmat[i+1,j+1]<-1e0
+k<-i+j
+if(k > 0 && k<length(z) && z[k]==z[k+1])cmat[i+1,j+1]<-1
+}
+}
+for (i in 0:m){
+for (j in 0:n)if(i*j==0)umat[i+1,j+1]<-cmat[i+1,j+1]
+else umat[i+1,j+1]<-cmat[i+1,j+1]*(umat[i+1,j]+umat[i,j+1])
+}
+term<-lgamma(m+n+1)-lgamma(m+1)-lgamma(n+1)
+kstiesig<-1.-umat[m+1,n+1]/exp(term)
+kstiesig
+}
+
+
+
+kswsig<-function(m,n,val){
+#
+#    Compute significance level of the weighted
+#    Kolmogorov-Smirnov test statistic
+#
+#    m=sample size of first group
+#    n=sample size of second group
+#    val=observed value of test statistic
+#
+  mpn<-m+n
+  cmat<-matrix(0,m+1,n+1)
+  umat<-matrix(0,m+1,n+1)
+  for (i in 1:m-1){
+    for (j in 1:n-1)cmat[i+1,j+1]<-abs(i/m-j/n)*sqrt(m*n/((i+j)*(1-(i+j)/mpn)))
+  }
+  cmat<-ifelse(cmat<=val,1,0)
+  for (i in 0:m){
+    for (j in 0:n)if(i*j==0)umat[i+1,j+1]<-cmat[i+1,j+1]
+    else umat[i+1,j+1]<-cmat[i+1,j+1]*(umat[i+1,j]+umat[i,j+1])
+  }
+  term<-lgamma(m+n+1)-lgamma(m+1)-lgamma(n+1)
+  kswsig<-1.-umat[m+1,n+1]/exp(term)
+  kswsig
+}
+
+Mks.test.handler <- function(w)
+  {
+    #suppress the following warning:
+    #In ks.test() :
+    # p-values will be approximate in the presence of ties
+    if( any( grepl( "ties", w) ) )
+      invokeRestart( "muffleWarning" )
+
+    #invoke as:
+    #withCallingHandlers( ks.test(round(x1), round(x2)), warning = Mks.test.handler )
+  }
+
+Mks.test <- function(...)
+  {
+    RVAL <- withCallingHandlers( ks.test(...), warning = Mks.test.handler )
+    return(RVAL)
+  }
+
+Mt.test  <- function(Tr, Co, weights)
+  {
+    v1  <- Tr-Co
+    estimate  <- sum(v1*weights)/sum(weights)
+    var1  <- sum( ((v1-estimate)^2)*weights )/( sum(weights)*sum(weights) )
+
+    parameter  <- Inf
+
+    #get rid of NA for t.test!
+    if (estimate==0 & var1==0)
+      {
+        statistic = 0        
+        p.value = 1
+      }  else {
+        statistic  <- estimate/sqrt(var1)
+        
+        p.value    <- (1-MATCHpt(abs(statistic), df=sum(weights)-1))*2
+      }
+
+    z  <- list(statistic=statistic, parameter=parameter, p.value=p.value,
+               estimate=estimate)
+    return(z)
+  } #end of Mt.test
+
+Mt.test.unpaired  <- function(Tr, Co,
+                              weights.Tr=rep(1,length(Tr)),
+                              weights.Co=rep(1,length(Co)))
+  {
+    obs.Tr <- sum(weights.Tr)
+    obs.Co <- sum(weights.Co)
+    
+    mean.Tr <- sum(Tr*weights.Tr)/obs.Tr
+    mean.Co <- sum(Co*weights.Co)/obs.Co
+    estimate <- mean.Tr-mean.Co
+    var.Tr  <- sum( ( (Tr - mean.Tr)^2 )*weights.Tr)/(obs.Tr-1)
+    var.Co  <- sum( ( (Co - mean.Co)^2 )*weights.Co)/(obs.Co-1)
+    dim <- sqrt(var.Tr/obs.Tr + var.Co/obs.Co)
+
+    parameter  <- Inf
+
+    #get rid of NA for t.test!
+    if (estimate==0 & dim==0)
+      {
+        statistic = 0
+        p.value = 1
+      }  else {
+        statistic  <- estimate/dim
+
+        a1 <- var.Tr/obs.Tr
+        a2 <- var.Co/obs.Co
+        dof <- ((a1 + a2)^2)/( (a1^2)/(obs.Tr - 1) + (a2^2)/(obs.Co - 1) )    
+        
+        p.value    <- (1-MATCHpt(abs(statistic), df=dof))*2
+      }
+
+    z  <- list(statistic=statistic, parameter=parameter, p.value=p.value,
+               estimate=estimate)
+    return(z)
+  } #end of Mt.test.unpaired
+
+MatchBalance <- function(formul, data=NULL, match.out=NULL, ks=TRUE, 
+                         nboots=500, weights=NULL,
+                         digits=5, paired=TRUE, print.level=1)
+  {
+    if(!is.list(match.out) & !is.null(match.out)) {
+      warning("'Match' object contains no valid matches")
+      match.out  <- NULL
+    }
+
+    if ( (class(match.out) != "Match") & (class(match.out) != "Matchby") & (!is.null(match.out)) ) {
+      warning("Object not of class 'Match'")
+      match.out  <- NULL
+    }
+
+    orig.na.action <- as.character(options("na.action"))
+    options("na.action"=na.pass)            
+    if (is.null(data))
+      {
+        xdata <- as.data.frame(get.xdata(formul,datafr=environment(formul)))
+        Tr <- as.double(get.ydata(formul,datafr=environment(formul)))
+
+      } else {
+        data  <- as.data.frame(data)
+
+        xdata  <- as.data.frame(get.xdata(formul, data))
+        Tr  <- as.double(get.ydata(formul, data))
+      }
+    options("na.action"=orig.na.action)
+
+    if (is.null(weights))
+      weights <- rep(1,length(Tr))
+
+    if(!is.numeric(weights))
+      stop("'weights' must be a numeric vector")
+
+    if( sum(is.na(xdata))!=0 | sum(is.na(Tr))!=0)
+      {
+
+        if(orig.na.action!="na.omit" & orig.na.action!="na.exclude" & orig.na.action!="na.fail")
+          warning("'na.action' should be set to 'na.omit', 'na.exclude' or 'na.fail' see 'help(na.action)'")
+
+        if (orig.na.action=="na.fail")
+          {
+            stop("NA's found in data input.")            
+          } else {
+            warning("NA's found in data input.  IT IS HIGHLY RECOMMENDED THAT YOU TEST IF THE MISSING VALUES ARE BALANCED INSTEAD OF JUST DELETING THEM.")
+          }
+
+        indx1 <- apply(is.na(xdata),1,sum)==0 & is.na(Tr)==0
+        Tr <- Tr[indx1]
+        xdata = xdata[indx1,]
+        weights <- weights[indx1]
+      } #end of na
+
+    if (sum(Tr !=1 & Tr !=0) > 0) {
+      stop("Treatment indicator must be a logical variable---i.e., TRUE (1) or FALSE (0)")
+    }
+
+    nvars  <- ncol(xdata)
+    names.xdata  <- names(xdata)
+
+    findx  <- 1
+    if (sum(xdata[,1]==rep(1,nrow(xdata)))==nrow(xdata))
+      {
+        findx  <- 2
+      }
+
+    if(nboots < 10 & nboots > 0)
+      nboots <- 10
+    
+    if (ks)
+      {
+        ks.bm <- KSbootBalanceSummary(index.treated=(Tr==0),
+                                      index.control=(Tr==1),
+                                      X=xdata[,findx:nvars],
+                                      nboots=nboots)
+
+        if (!is.null(match.out))
+          {
+            ks.am <- KSbootBalanceSummary(index.treated=match.out$index.treated,
+                                          index.control=match.out$index.control,
+                                          X=xdata[,findx:nvars],
+                                          nboots=nboots)
+          }
+      } 
+
+    BeforeMatchingBalance <- list()
+    AfterMatchingBalance <- list()
+
+    BMsmallest.p.value <- 1
+    BMsmallest.number <- 1
+    BMsmallest.name <- names.xdata[findx]
+
+    AMsmallest.p.value <- NULL
+    AMsmallest.number <- NULL
+    AMsmallest.name <- NULL
+    
+    if (!is.null(match.out))
+      {
+        AMsmallest.p.value <- 1
+        AMsmallest.number <- 1
+        AMsmallest.name <- names.xdata[findx]        
+      }
+
+    for( i in findx:nvars)
+      {
+        count <- i-findx+1
+        if(print.level > 0)
+          cat("\n***** (V",count,") ", names.xdata[i]," *****\n",sep="")
+        
+        ks.do  <- FALSE
+        is.dummy  <- length(unique( xdata[,i] )) < 3
+        if (ks & !is.dummy)
+          ks.do  <- TRUE
+
+        BeforeMatchingBalance[[count]]  <-  balanceUV(xdata[,i][Tr==1], xdata[,i][Tr==0], nboots=0,
+                                                      weights.Tr=weights[Tr==1], weights.Co=weights[Tr==0],
+                                                      match=FALSE)
+        
+        if (BeforeMatchingBalance[[count]]$tt$p.value < BMsmallest.p.value)
+          {
+            BMsmallest.p.value <- BeforeMatchingBalance[[count]]$tt$p.value
+            BMsmallest.number <- count
+            BMsmallest.name <- names.xdata[i]            
+          } else if (BeforeMatchingBalance[[count]]$tt$p.value == BMsmallest.p.value)
+            {
+              BMsmallest.number <- c(BMsmallest.number,count)
+              BMsmallest.name <- c(BMsmallest.name,names.xdata[i])
+            }
+        
+        if (ks.do)
+          {
+            BeforeMatchingBalance[[count]]$ks <- list()
+            BeforeMatchingBalance[[count]]$ks$ks <- list()
+            BeforeMatchingBalance[[count]]$ks$ks$p.value <- ks.bm$ks.naive.pval[count]
+            BeforeMatchingBalance[[count]]$ks$ks$statistic <- ks.bm$ks.stat[count]              
+            if (nboots > 0)
+              {
+                BeforeMatchingBalance[[count]]$ks$ks.boot.pvalue <- ks.bm$ks.boot.pval[count]
+
+                if (ks.bm$ks.boot.pval[count] < BMsmallest.p.value)
+                  {
+                    BMsmallest.p.value <- ks.bm$ks.boot.pval[count]
+                    BMsmallest.number <- count
+                    BMsmallest.name <- names.xdata[i]            
+                  } else if ( (ks.bm$ks.boot.pval[count] == BMsmallest.p.value) & (sum(BMsmallest.number==count)==0) )
+                    {
+                      BMsmallest.number <- c(BMsmallest.number,count)
+                      BMsmallest.name <- c(BMsmallest.name,names.xdata[i])
+                    }
+              } else {
+                BeforeMatchingBalance[[count]]$ks$ks.boot.pvalue <- NA
+
+                if (ks.bm$ks.naive.pval[count] < BMsmallest.p.value)
+                  {
+                    BMsmallest.p.value <- ks.bm$ks.naive.pval[count]
+                    BMsmallest.number <- count
+                    BMsmallest.name <- names.xdata[i]            
+                  } else if ( (ks.bm$ks.naive.pval[count] == BMsmallest.p.value) & (sum(BMsmallest.number==count)==0) )
+                    {
+                      BMsmallest.number <- c(BMsmallest.number,count)
+                      BMsmallest.name <- c(BMsmallest.name,names.xdata[i])
+                    }              
+              }
+            
+          } else {
+            BeforeMatchingBalance[[count]]$ks <- NULL
+          }
+        
+        if (!is.null(match.out))
+          {
+            AfterMatchingBalance[[count]]  <- balanceUV(xdata[,i][match.out$index.treated],
+                                                        xdata[,i][match.out$index.control],
+                                                        weights=match.out$weights, nboots=0,
+                                                        paired=paired, match=TRUE)
+            
+            if (AfterMatchingBalance[[count]]$tt$p.value < AMsmallest.p.value)
+              {
+                AMsmallest.p.value <- AfterMatchingBalance[[count]]$tt$p.value
+                AMsmallest.number <- count
+                AMsmallest.name <- names.xdata[i]            
+              } else if ( (AfterMatchingBalance[[count]]$tt$p.value == AMsmallest.p.value) & (sum(AMsmallest.number==count)==0) )
+                    {
+                      AMsmallest.number <- c(AMsmallest.number,count)
+                      AMsmallest.name <- c(AMsmallest.name,names.xdata[i])
+                    }
+            
+            if (ks.do)
+              {                
+                AfterMatchingBalance[[count]]$ks <- list()
+                AfterMatchingBalance[[count]]$ks$ks <- list()
+                AfterMatchingBalance[[count]]$ks$ks$p.value <- ks.am$ks.naive.pval[count]
+                AfterMatchingBalance[[count]]$ks$ks$statistic <- ks.am$ks.stat[count]
+                if (nboots > 0)
+                  {
+                    AfterMatchingBalance[[count]]$ks$ks.boot.pvalue <- ks.am$ks.boot.pval[count]
+
+                    if (ks.am$ks.boot.pval[count] < AMsmallest.p.value)
+                      {
+                        AMsmallest.p.value <- ks.am$ks.boot.pval[count]
+                        AMsmallest.number <- count
+                        AMsmallest.name <- names.xdata[i]            
+                      } else if ( (ks.am$ks.boot.pval[count] == AMsmallest.p.value) & (sum(AMsmallest.number==count)==0) )
+                        {
+                          AMsmallest.number <- c(AMsmallest.number,count)
+                          AMsmallest.name <- c(AMsmallest.name,names.xdata[i])
+                        }
+                  } else {
+                    AfterMatchingBalance[[count]]$ks$ks.boot.pvalue <- NA
+
+                    if (ks.am$ks.naive.pval[count] < AMsmallest.p.value)
+                      {
+                        AMsmallest.p.value <- ks.am$ks.naive.pval[count]
+                        AMsmallest.number <- count
+                        AMsmallest.name <- names.xdata[i]            
+                      } else if ( (ks.am$ks.naive.pval[count] == AMsmallest.p.value) & (sum(AMsmallest.number==count)==0) )
+                        {
+                          AMsmallest.number <- c(AMsmallest.number,count)
+                          AMsmallest.name <- c(AMsmallest.name,names.xdata[i])
+                        }              
+                  }                    
+              } else {
+                AfterMatchingBalance[[count]]$ks <- NULL
+              }
+            if(print.level > 0)
+              PrintBalanceUV(BeforeMatchingBalance[[count]], AfterMatchingBalance[[count]], digits=digits)
+          } else {
+            if(print.level > 0)
+              {
+                cat("before matching:\n")
+                summary(BeforeMatchingBalance[[count]], digits=digits)
+              }
+          } #end of if match.out
+      } #end of for loop
+    
+    if(print.level & ( (nvars-findx+1) > 1))
+      {
+        cat("\n")
+
+        if (BMsmallest.p.value < 1)
+          {
+            cat("Before Matching Minimum p.value:", format.pval(BMsmallest.p.value, digits=digits),"\n")
+            cat("Variable Name(s):",BMsmallest.name, " Number(s):",BMsmallest.number,"\n\n")
+          } else {
+            cat("Before Matching Minimum p.value: 1\n\n")
+          }
+
+        if (!is.null(match.out))
+          {
+            if(AMsmallest.p.value < 1)
+              {
+                cat("After Matching Minimum p.value:", format.pval(AMsmallest.p.value, digits=digits),"\n")
+                cat("Variable Name(s):",AMsmallest.name, " Number(s):",AMsmallest.number,"\n\n")
+              } else {
+                cat("After Matching Minimum p.value: 1\n\n")
+              }
+          } #end of !is.null(match.out)
+      }#end of print.level & (nvars > 1)
+  
+    return(invisible(list(BeforeMatching=BeforeMatchingBalance,
+                          AfterMatching=AfterMatchingBalance,
+                          BMsmallest.p.value=BMsmallest.p.value,
+                          BMsmallestVarName=BMsmallest.name,
+                          BMsmallestVarNumber=BMsmallest.number,
+                          AMsmallest.p.value=AMsmallest.p.value,
+                          AMsmallestVarName=AMsmallest.name,
+                          AMsmallestVarNumber=AMsmallest.number)))
+  } #end of MatchBalance
+
+
+get.xdata <- function(formul, datafr) {
+  t1 <- terms(formul, data=datafr);
+  if (length(attr(t1, "term.labels"))==0 & attr(t1, "intercept")==0) {
+    m <- NULL;  # no regressors specified for the model matrix
+  } else {
+    m <- model.matrix(formul, data=datafr, drop.unused.levels = TRUE)
+  }
+  return(m);
+}
+
+
+# get.ydata:
+# Return response vector corresponding to the formula in formul
+# 
+get.ydata <- function(formul, datafr) {
+  t1 <- terms(formul, data=datafr);
+  if (length(attr(t1, "response"))==0) {
+    m <- NULL;  # no response variable specified
+  }  else {
+    m <- model.response(model.frame(formul, data=datafr))
+  }
+  return(m);
+}
+
+#
+# bootstrap ks test implemented.  Fast version
+#
+
+ks.boot  <- function(Tr, Co, nboots=1000, alternative = c("two.sided", "less", "greater"), print.level=0)
+  {
+    alternative <- match.arg(alternative)
+    tol <- sqrt(.Machine$double.eps)
+    Tr <- Tr[!is.na(Tr)]
+    Co <- Co[!is.na(Co)]
+
+    w    <- c(Tr, Co)
+    obs  <- length(w)
+    n.x <- length(Tr)
+    n.y <- length(Co)
+    cutp <- n.x
+    ks.boot.pval <- NULL
+    bbcount <- 0
+
+    if (nboots < 10)
+      {
+        nboots  <- 10
+        warning("At least 10 'nboots' must be run; seting 'nboots' to 10")
+      }
+
+    if (nboots < 500)
+      warning("For publication quality p-values it is recommended that 'nboots'\n be set equal to at least 500 (preferably 1000)") 
+    
+    fs.ks  <- Mks.test(Tr, Co, alternative=alternative)    
+
+    if (alternative=="two.sided")
+      {
+        if (print.level > 0)
+          cat("ks.boot: two.sided test\n")
+        for (bb in 1:nboots)
+          {
+            if (print.level > 1)
+              cat("s:", bb, "\n")
+            
+            sindx  <- sample(1:obs, obs, replace=TRUE)
+            
+            X1tmp <- w[sindx[1:cutp]]
+            X2tmp <- w[sindx[(cutp+1):obs]]
+            
+            s.ks <- ks.fast(X1tmp, X2tmp, n.x=n.x, n.y=n.y, n=obs)
+            
+            if (s.ks >= (fs.ks$statistic - tol) )
+              bbcount  <- bbcount + 1
+          }
+      } else {
+        if (print.level > 0)
+          cat("ks.boot:",alternative,"test\n")            
+        for (bb in 1:nboots)
+          {
+            if (print.level > 1)
+              cat("s:", bb, "\n")
+            
+            sindx  <- sample(1:obs, obs, replace=TRUE)
+            
+            X1tmp <- w[sindx[1:cutp]]
+            X2tmp <- w[sindx[(cutp+1):obs]]
+            
+            s.ks <- Mks.test(X1tmp, X2tmp, alternative=alternative)$statistic
+            
+            if (s.ks >= (fs.ks$statistic - tol) )
+              bbcount  <- bbcount + 1                                
+          }        
+      }
+    ks.boot.pval  <- bbcount/nboots
+    
+    ret  <- list(ks.boot.pvalue=ks.boot.pval, ks=fs.ks, nboots=nboots)
+    class(ret)  <- "ks.boot"
+    
+    return(ret)
+  } #end of ks.boot
+
+summary.ks.boot <- function(object, ..., digits=5)
+  {
+    if(!is.list(object)) {
+      warning("object not a valid 'ks.boot' object")
+      return()
+    }
+
+    if (class(object) != "ks.boot") {
+      warning("Object not of class 'ks.boot'")
+      return()
+    }    
+        
+    cat("\n")
+    cat("Bootstrap p-value:    ", format.pval(object$ks.boot.pvalue, digits=digits), "\n")
+    cat("Naive p-value:        ", format(object$ks$p.value, digits=digits), "\n")
+    cat("Full Sample Statistic:", format(object$ks$statistic, digits=digits), "\n")
+#    cat("nboots completed      ", object$nboots, "\n")
+    cat("\n")
+
+    z <- list()
+    class(z) <- "summary.ks.boot"
+    return(invisible(z))
+  } #end of summary.ks.boot
+
+print.summary.ks.boot <- function(x, ...)
+  {
+    invisible(NULL)
+  }
+
+
+RmatchLoop <- function(Y, Tr, X, Z, V, All, M, BiasAdj, Weight, Weight.matrix, Var.calc, weight,
+                       SAMPLE, ccc, cdd, ecaliper=NULL, exact=NULL, caliper=NULL, restrict=NULL,
+                       MatchLoopC.indx=NULL, weights.flag, replace=TRUE, ties=TRUE,
+                       version="standard", MatchbyAI=FALSE)
+  {
+    s1 <- MatchGenoudStage1caliper(Tr=Tr, X=X, All=All, M=M, weights=weight,
+                                   exact=exact, caliper=caliper,
+                                   distance.tolerance=cdd,
+                                   tolerance=ccc)
+
+    sum.caliper.drops <- 0
+    X.orig <- X
+
+#are we using the restriction matrix?
+    if(is.matrix(restrict)) {
+      restrict.trigger <- TRUE
+    } else {
+      restrict.trigger <- FALSE
+    }    
+    
+# if SATC is to be estimated the treatment indicator is reversed    
+    if (All==2)
+      Tr <- 1-Tr
+
+# check on the number of matches, to make sure the number is within the limits
+# feasible given the number of observations in both groups.
+    if (All==1)
+      {
+        M <- min(M,min(sum(Tr),sum(1-Tr)));        
+      } else {
+        M <- min(M,sum(1-Tr));
+      }
+
+# two slippage parameters that are used to determine whether distances are equal
+# distances less than ccc or cdd are interpeted as zero.
+# these are passed in.  ccc, cdd
+
+
+# I. set up
+# I.a. vector for which observations we want the average effect
+# iot_t is the vector with weights in the average treatment effects
+# iot_c is the vector of indicators for potential controls
+
+    if (All==1)
+      {
+        iot.t <- weight;
+        iot.c <- as.matrix(rep(1,length(Tr)))
+      } else {
+        iot.t <- Tr*weight;
+        iot.c <- 1-Tr    
+      }
+
+# I.b. determine sample and covariate vector sizes
+    N  <- nrow(X)
+    Kx <- ncol(X)
+    Kz <- ncol(Z)
+
+# K covariates
+# N observations
+#    Nt <- sum(Tr)
+#    Nc <- sum(1-Tr)
+#    on <- as.matrix(rep(1,N))
+
+# I.c. normalize regressors to have mean zero and unit variance.
+# If the standard deviation of a variable is zero, its normalization
+# leads to a variable with all zeros.
+# The matrix AA enables one to transform the user supplied weight matrix 
+# to take account of this transformation.  BUT THIS IS NOT USED!!
+# Mu_X and Sig_X keep track of the original mean and variances
+#    AA    <- diag(Kx)
+    Mu.X  <- matrix(0, Kx, 1)
+    Sig.X <- matrix(0, Kx, 1)
+
+    for (k in 1:Kx)
+      {
+        Mu.X[k,1] <- sum(X[,k]*weight)/sum(weight)
+        eps <- X[,k]-Mu.X[k,1]
+        Sig.X[k,1] <- sqrt(sum(X[,k]*X[,k]*weight)/sum(weight)-Mu.X[k,1]^2)
+        Sig.X[k,1] <- Sig.X[k,1]*sqrt(N/(N-1))
+        if(Sig.X[k,1] < ccc)
+          Sig.X[k,1] <- ccc        
+        X[,k]=eps/Sig.X[k,1]
+#        AA[k,k]=Sig.X[k,1]
+      } #end of k loop
+
+#    Nv <- nrow(V)
+    Mv <- ncol(V)
+    Mu.V  <- matrix(0, Mv, 1)
+    Sig.V <- matrix(0, Mv, 1)
+
+    for (j in 1:Mv)
+      {
+        Mu.V[j,1]= ( t(V[,j])%*%weight ) /sum(weight)
+#        dv <- V[,j]-Mu.V[j,1]
+        sv <- sum(V[,j]*V[,j]*weight)/sum(weight)-Mu.V[j,1]^2
+        if (sv > 0)
+          {
+            sv <- sqrt(sv)
+          } else {
+            sv <- 0
+          }
+        sv <- sv * sqrt(N/(N-1))
+        Sig.V[j,1] <- sv
+      } #end of j loop
+
+# I.d. define weight matrix for metric, taking into account normalization of
+# regressors.
+# If the eigenvalues of the regressors are too close to zero the Mahalanobis metric
+# is not used and we revert back to the default inverse of variances.
+    if (Weight==1)
+      {
+        Weight.matrix=diag(Kx)
+      } else if (Weight==2) {
+        if (min (eigen( t(X)%*%X/N, only.values=TRUE)$values) > 0.0000001)
+          {
+            Weight.matrix= solve(t(X)%*%X/N)
+          } else {
+            Weight.matrix <- diag(Kx)
+          }
+      }
+      # DO NOT RESCALE THE Weight.matrix!!
+      #else if (Weight==3)
+      #  {
+      #    Weight.matrix <- AA %*% Weight.matrix %*% AA
+      #  }
+
+#    if (exact==1)
+#      {
+#        Weight.matrix <- cbind(Weight.matrix, matrix(0,nrow=Kx,ncol=Mv))
+#        Weight.matrix <- rbind(Weight.matrix, cbind(matrix(0,nrow=Mv,ncol=Kx),
+#                               1000*solve(diag(as.vector(Sig.V*Sig.V), nrow=length(Sig.V)))))
+#        Weight.matrix <- as.matrix(Weight.matrix)
+#        X <- cbind(X,V)
+#        Mu.X  <- rbind(Mu.X, matrix(0, nrow(Mu.V), 1))
+#        Sig.X <- rbind(Sig.X, matrix(1, nrow(Sig.V), 1))
+#      } #end of exact
+
+    if ( min(eigen(Weight.matrix, only.values=TRUE)$values) < ccc )
+      Weight.matrix <- Weight.matrix + diag(Kx)*ccc
+
+    ww <- chol(Weight.matrix) # so that ww*ww=w.m
+
+    if(is.null(s1$ecaliper))
+      {
+        caliperflag <- 0
+        use.ecaliper <- 0
+      } else {
+        caliperflag <- 1
+        use.ecaliper <- s1$ecaliper
+      }
+
+    #if we have a diagonal matrix we can void cblas_dgemm
+    if (Kx > 1)
+      {
+        DiagWeightMatrixFlag <- as.double(sum( (Weight.matrix!=diag(diag(Weight.matrix))) )==0)
+      } else {
+        DiagWeightMatrixFlag <- 1
+      }
+
+    if(is.null(MatchLoopC.indx))
+      {
+    #indx:
+    # 1] I (unadjusted); 2] IM (unadjusted); 3] weight; 4] I (adjusted); 5] IM (adjusted)
+        if(weights.flag==TRUE)
+          {
+            MatchLoopC.indx <- MatchLoopC(N=s1$N, xvars=Kx, All=s1$All, M=s1$M,
+                                          cdd=cdd, caliperflag=caliperflag, replace=replace, ties=ties,
+                                          ww=ww, Tr=s1$Tr, Xmod=s1$X,
+                                          weights=weight,
+                                          CaliperVec=use.ecaliper, Xorig=X.orig,
+                                          restrict.trigger=restrict.trigger, restrict=restrict,
+                                          DiagWeightMatrixFlag=DiagWeightMatrixFlag)
+          } else {
+            MatchLoopC.indx <- MatchLoopCfast(N=s1$N, xvars=Kx, All=s1$All, M=s1$M,
+                                              cdd=cdd, caliperflag=caliperflag, replace=replace, ties=ties,
+                                              ww=ww, Tr=s1$Tr, Xmod=s1$X,
+                                              CaliperVec=use.ecaliper, Xorig=X.orig,
+                                              restrict.trigger=restrict.trigger, restrict=restrict,
+                                              DiagWeightMatrixFlag=DiagWeightMatrixFlag)
+          }
+      }
+
+    indx <- MatchLoopC.indx
+
+    if(indx[1,1]==0)
+      {
+        ret <- list()
+        ret$valid <- 0
+        if (caliperflag)
+          {
+            ret$sum.caliper.drops <- indx[1,6]
+          } else {
+            ret$sum.caliper.drops <- 0
+          }
+        return(ret)
+      } 
+    #we now keep going if we only have 1 valid match
+    #else if (nrow(indx)< 2)
+    #  {
+    #    ret <- list()
+    #    ret$valid <- 1
+    #    if (caliperflag)
+    #      {
+    #        ret$sum.caliper.drops <- indx[1,6]
+    #      } else {
+    #        ret$sum.caliper.drops <- 0
+    #      }
+    #    return(ret)
+    #  }
+        
+    if (All==2)
+      {
+        foo <- indx[,5]
+        indx[,5] <- indx[,4]
+        indx[,4] <- foo
+      }
+
+    if (caliperflag)
+      {
+        sum.caliper.drops <- indx[1,6]
+      } else {
+        sum.caliper.drops <- 0
+      }
+
+    #
+    # Generate variables which we need later on
+    #
+
+    I <- indx[,1]
+    IT <- Tr[indx[,1]]
+    IM <- indx[,2]
+
+#    IX <- X[indx[,1],]
+#    Xt <- X[indx[,4],]
+#    Xc <- X[indx[,5],]
+
+#    IY <- Y[indx[,1]]
+    Yt <- Y[indx[,4]]
+    Yc <- Y[indx[,5]]
+
+    W <- indx[,3]
+    
+    if(BiasAdj==1 & sum(W) < ncol(Z))
+      {
+        warning("Fewer (weighted) matches than variables in 'Z': BiasAdjust set to FALSE")
+        BiasAdj=0
+      }    
+
+    if(BiasAdj==1)
+      {
+        if(sum(W) < ncol(Z))
+          {
+            warning("Fewer matches than variables for Bias Adjustment")
+          }
+        
+        IZ <- Z[indx[,1],]
+        Zt <- Z[indx[,4],]
+        Zc <- Z[indx[,5],]
+      }
+
+    est.func <- function(N, All, Tr, indx, weight, BiasAdj, Kz)
+      {
+        Kcount <- as.matrix(rep(0, N))    
+        KKcount <- as.matrix(rep(0, N))
+        YCAUS <- matrix(0, nrow=N, ncol=1)
+
+        if (BiasAdj==1)
+          {
+            ZCAUS <- matrix(0, nrow=N, ncol=Kz)
+          } else {
+            ZCAUS <- NULL
+          }
+        
+        for (i in 1:N)
+          {
+            if ( ( Tr[i]==1 & All!=1) | All==1 )
+              {
+
+                foo.indx <- indx[,1]==i
+                foo.indx2 <- foo.indx
+                
+                sum.foo <- sum(foo.indx)
+                
+                if (sum.foo < 1)
+                  next;            
+                
+                foo <- rep(FALSE, N)
+                foo.indx <- indx[foo.indx,2]
+                foo[foo.indx] <- rep(TRUE,sum.foo)
+
+                #   inner.func <- function(N, weight, indx, foo.indx2, Y, Tr, foo)
+  
+                Kcount <- Kcount + weight[i] * weight*foo/sum(foo*weight)
+                
+                KKcount <- KKcount + weight[i]*weight*weight*foo/
+                  (sum(foo*weight)*sum(foo*weight))
+                
+                foo.indx2.2 <- indx[foo.indx2,2];
+                foo.indx2.3 <- indx[foo.indx2,3];
+                sum.foo.indx2.3 <- sum(foo.indx2.3)
+
+                if(Tr[i]==1)
+                  {
+                    YCAUS[i] <- Y[i] - sum((Y[foo.indx2.2]*foo.indx2.3))/sum.foo.indx2.3
+                  } else {
+                    YCAUS[i] <- sum((Y[foo.indx2.2]*foo.indx2.3))/sum.foo.indx2.3 - Y[i]
+                  }
+
+                if (BiasAdj==1)
+                  {
+                    
+                    if(Tr[i]==1)
+                      {
+                        if (sum.foo > 1)
+                          {
+                            ZCAUS[i,] <-
+                              Z[i,] - t(Z[foo.indx2.2,]) %*% foo.indx2.3/sum.foo.indx2.3
+                          } else {
+                            ZCAUS[i,] <-
+                              Z[i,] - Z[foo.indx2.2,]*foo.indx2.3/sum.foo.indx2.3
+                          }
+                      } else {
+                        if (sum.foo > 1)
+                          {
+                            ZCAUS[i,] <- t(Z[foo.indx2.2,]) %*% foo.indx2.3/sum.foo.indx2.3 - Z[i,]
+                          } else {
+                            ZCAUS[i,] <- Z[foo.indx2.2,]*foo.indx2.3/sum.foo.indx2.3 - Z[i,]
+                          }
+                      }
+                  } #endof BiasAdj
+              }
+          } #end of if
+        return(list(YCAUS=YCAUS,ZCAUS=ZCAUS,Kcount=Kcount,KKcount=KKcount))
+      } #end of est.func
+    
+    if(version=="standard" & BiasAdj==0)
+      {
+        ret <- .Call("EstFuncC", as.integer(N), as.integer(All), as.integer(nrow(indx)),
+                     as.double(Y), as.double(Tr),
+                     as.double(weight), as.double(indx),
+                     PACKAGE="Matching")
+        YCAUS <- ret[,1];
+        Kcount <- ret[,2];
+        KKcount <- ret[,3];
+      } else if (version=="standard") {
+        ret.est <- est.func(N=N, All=All, Tr=Tr, indx=indx, weight=weight, BiasAdj=BiasAdj, Kz=Kz)
+        YCAUS <- ret.est$YCAUS
+        ZCAUS <- ret.est$ZCAUS
+        Kcount <- ret.est$Kcount
+        KKcount <- ret.est$KKcount
+      }
+
+    if (All!=1)
+      {
+        I  <- as.matrix(I[IT==1])
+        IT <- as.matrix(IT[IT==1])
+        Yc <- as.matrix(Yc[IT==1])
+        Yt <- as.matrix(Yt[IT==1])
+        W  <- as.matrix(W[IT==1])
+        if (BiasAdj==1)
+          {
+            if (Kz > 1)
+              {
+                Zc <- as.matrix(Zc[IT==1,])
+                Zt <- as.matrix(Zt[IT==1,])
+                IZ <- as.matrix(IZ[IT==1,])
+              } else{
+                Zc <- as.matrix(Zc[IT==1])
+                Zt <- as.matrix(Zt[IT==1])
+                IZ <- as.matrix(IZ[IT==1])            
+              }
+          }
+#        IM <- as.matrix(IM[IT==1,])
+#        IY <- as.matrix(IY[IT==1])
+#        IX.u  <- as.matrix(IX.u[IT==1,])
+#        Xc.u  <- as.matrix(Xc.u[IT==1,])
+#        Xt.u  <- as.matrix(Xt.u[IT==1,])
+#        Xc    <- as.matrix(Xc[IT==1,])
+#        Xt <- as.matrix(Xt[IT==1,])
+      } #end of if
+    
+    if (length(I) < 1)
+      {
+        return(list(sum.caliper.drops=N))
+      }
+    
+    if (BiasAdj==1)
+      {
+        # III. Regression of outcome on covariates for matches
+        if (All==1)
+          {
+            # number of observations
+            NNt <- nrow(Z)
+            # add intercept        
+            ZZt <- cbind(rep(1, NNt), Z)
+            # number of covariates
+            Kx <- ncol(ZZt)
+            xw <- ZZt*(sqrt(Tr*Kcount) %*% t(as.matrix(rep(1,Kx))))
+            
+            foo <- min(eigen(t(xw)%*%xw, only.values=TRUE)$values)
+            foo <- as.double(foo<=ccc)
+            foo2 <- apply(xw, 2, sd)
+
+            options(show.error.messages = FALSE)
+            wout <- NULL
+            try(wout <- solve( t(xw) %*% xw + diag(Kx) * ccc * (foo) * max(foo2)) %*%
+                (t(xw) %*% (Y*sqrt(Tr*Kcount))))
+            if(is.null(wout))
+              {
+                wout2 <- NULL
+                try(wout2 <- ginv( t(xw) %*% xw + diag(Kx) * ccc * (foo) * max(foo2)) %*%
+                    (t(xw) %*% (Y*sqrt(Tr*Kcount))))
+                if(!is.null(wout2))
+                  {
+                    wout <-wout2
+                    warning("using generalized inverse to calculate Bias Adjustment probably because of singular 'Z'")
+                  }
+              }
+            options(show.error.messages = TRUE)
+            if(is.null(wout))
+              {
+                warning("unable to calculate Bias Adjustment probably because of singular 'Z'")
+                BiasAdj <- 0
+              } else {
+                NW <- nrow(wout)
+#                KW <- ncol(wout)
+                Alphat <- wout[2:NW,1]
+              }
+          } else {
+            Alphat <- matrix(0, nrow=Kz, ncol=1)
+          } #end if ALL
+      }
+
+    if(BiasAdj==1)
+      {
+        # III.b.  Controls
+        NNc <- nrow(Z)
+        ZZc <- cbind(matrix(1, nrow=NNc, ncol=1),Z)
+        Kx <- ncol(ZZc)
+        
+        xw <- ZZc*(sqrt((1-Tr)*Kcount) %*% matrix(1, nrow=1, ncol=Kx))
+        
+        foo <- min(eigen(t(xw)%*%xw, only.values=TRUE)$values)
+        foo <- as.double(foo<=ccc)
+        foo2 <- apply(xw, 2, sd)
+
+        options(show.error.messages = FALSE)
+        wout <- NULL        
+        try(wout <- solve( t(xw) %*% xw + diag(Kx) * ccc * (foo) * max(foo2)) %*%
+            (t(xw) %*% (Y*sqrt((1-Tr)*Kcount))))
+        if(is.null(wout))
+          {
+            wout2 <- NULL
+            try(wout2 <- ginv( t(xw) %*% xw + diag(Kx) * ccc * (foo) * max(foo2)) %*%
+                (t(xw) %*% (Y*sqrt((1-Tr)*Kcount))))
+            if(!is.null(wout2))
+              {
+                wout <-wout2
+                warning("using generalized inverse to calculate Bias Adjustment probably because of singular 'Z'")
+              }
+          }        
+        options(show.error.messages = TRUE)
+        if(is.null(wout))
+          {
+            warning("unable to calculate Bias Adjustment probably because of singular 'Z'")
+            BiasAdj <- 0
+          } else {
+            NW <- nrow(wout)
+#            KW <- ncol(wout)
+            Alphac <- as.matrix(wout[2:NW,1])
+          }
+      }
+
+    if(BiasAdj==1)
+      {
+        # III.c. adjust matched outcomes using regression adjustment for bias adjusted matching estimator
+        IZ <- as.matrix(IZ)
+        Zc <- as.matrix(Zc)
+        Zt <- as.matrix(Zt)
+        Alphat <- as.matrix(Alphat)
+
+        SCAUS <- YCAUS-Tr*(ZCAUS %*% Alphac)-(1-Tr)*(ZCAUS %*% Alphat)
+        # adjusted control outcome
+        Yc.adj <- Yc+BiasAdj * (IZ-Zc) %*% Alphac
+        # adjusted treated outcome
+        Yt.adj <- Yt+BiasAdj*(IZ-Zt) %*% Alphat
+        Tau.i <- Yt.adj - Yc.adj
+      } else {
+        Yc.adj <- Yc
+        Yt.adj <- Yt
+        Tau.i <- Yt.adj - Yc.adj        
+      }
+       
+    art.data <- cbind(I,IM)
+
+    # III. If conditional variance is needed, initialize variance vector
+    # and loop through all observations
+
+    if (Var.calc>0)
+      {
+        #For R version of this function see Matching version < 4.5-0008
+        Sigs <- VarCalcMatchC(N=N, xvars=ncol(X), Var.calc=Var.calc,
+                              cdd=cdd, caliperflag=caliperflag, 
+                              ww=ww, Tr=Tr, Xmod=s1$X,
+                              CaliperVec=use.ecaliper, Xorig=X.orig,
+                              restrict.trigger=restrict.trigger, restrict=restrict,
+                              DiagWeightMatrixFlag=DiagWeightMatrixFlag,
+                              Y=Y, weightFlag=weights.flag, weight=weight)            
+      } #end of var.calc > 0
+
+    est <- t(W) %*% Tau.i/sum(W) # matching estimator
+
+    if(version=="standard")
+      {
+        if (Var.calc==0)
+          {
+            eps <- Tau.i - as.double(est)
+            eps.sq <- eps*eps
+            Sigs <- 0.5 * matrix(1, N, 1) %*% (t(eps.sq) %*% W)/sum(W) #sss <- sqrt(Sigs[1,1])
+          } #end of Var.calc==0
+        
+        SN <- sum(iot.t)
+        var.sample <- sum((Sigs*(iot.t+iot.c*Kcount)*(iot.t+iot.c*Kcount))/(SN*SN))
+        
+        if (All==1)
+          {
+            var.pop <- sum((Sigs*(iot.c*Kcount*Kcount+2*iot.c*Kcount-iot.c*KKcount))/(SN*SN))
+          } else {
+            var.pop=sum((Sigs*(iot.c*Kcount*Kcount-iot.c*KKcount))/(SN*SN))
+          }
+        
+        if (BiasAdj==1)
+          {
+            dvar.pop <- sum(iot.t*(SCAUS-as.double(est))*(SCAUS-as.double(est)))/(SN*SN)
+          } else {
+            dvar.pop <- sum(iot.t*(YCAUS-as.double(est))*(YCAUS-as.double(est)))/(SN*SN)
+          }
+        
+        var.pop <- var.pop + dvar.pop
+        
+        if (SAMPLE==1)
+          {
+            var <- var.sample
+          } else {
+            #var <- max(var.sample, var.pop)
+            var <- var.pop
+          }
+        
+        var.cond <- max(var.sample,var.pop)-var.sample
+        se <- sqrt(var)
+        se.cond <- sqrt(var.cond)
+        #Sig <- sqrt(Sigs)        
+      } else {
+        se=NULL
+        se.cond=NULL
+      }
+        
+    if (All==2)
+      est <- -1*est
+
+#    if (exact==1)
+#      {
+#        Vt.u <- Xt.u[,(Kx-Mv+1):Kx]
+#        Vc.u <- Xc.u[,(Kx-Mv+1):Kx]
+#        Vdif <- abs(Vt.u-Vc.u)
+#
+#        if (Mv>1)
+#          Vdif <- as.matrix(apply(t(Vdif), 2, sum))
+#
+#        em[1,1] <- length(Vdif)
+#        em[2,1] <- sum(Vdif>0.000001)
+#      }#end of exact==1
+
+    if(!MatchbyAI)
+      {
+        return(list(est=est, se=se, se.cond=se.cond, W=W,
+                    sum.caliper.drops=sum.caliper.drops,
+                    art.data=art.data, 
+                    MatchLoopC=MatchLoopC.indx))
+      } else {
+        if(Var.calc==0)
+          Sigs <- NULL
+        return(list(est=est, se=se, se.cond=se.cond, W=W,
+                    sum.caliper.drops=sum.caliper.drops,
+                    art.data=art.data, 
+                    MatchLoopC=MatchLoopC.indx,
+                    YCAUS=YCAUS, Kcount=Kcount, KKcount=KKcount,
+                    Sigs=Sigs))
+      }
+  }# end of RmatchLoop
+
+MatchLoopC <- function(N, xvars, All, M, cdd, caliperflag, replace, ties, ww, Tr, Xmod, weights, CaliperVec, Xorig,
+                       restrict.trigger, restrict, DiagWeightMatrixFlag)
+  {
+
+    if(restrict.trigger)
+      {
+        restrict.nrow <- nrow(restrict)
+      } else {
+        restrict.nrow <- 0
+      }    
+
+    ret <- .Call("MatchLoopC", as.integer(N), as.integer(xvars), as.integer(All), as.integer(M),
+                 as.double(cdd), as.integer(caliperflag), as.integer(replace), as.integer(ties),
+                 as.double(ww), as.double(Tr),
+                 as.double(Xmod), as.double(weights), as.double(CaliperVec), as.double(Xorig),
+                 as.integer(restrict.trigger), as.integer(restrict.nrow), as.double(restrict),
+                 as.double(DiagWeightMatrixFlag),
+                 PACKAGE="Matching")
+    return(ret)
+  } #end of MatchLoopC
+
+MatchLoopCfast <- function(N, xvars, All, M, cdd, caliperflag, replace, ties, ww, Tr, Xmod, CaliperVec,
+                           Xorig, restrict.trigger, restrict, DiagWeightMatrixFlag)
+  {
+
+    if(restrict.trigger)
+      {
+        restrict.nrow <- nrow(restrict)
+      } else {
+        restrict.nrow <- 0
+      }    
+    
+    ret <- .Call("MatchLoopCfast", as.integer(N), as.integer(xvars), as.integer(All), as.integer(M),
+                 as.double(cdd), as.integer(caliperflag), as.integer(replace), as.integer(ties),
+                 as.double(ww), as.double(Tr),
+                 as.double(Xmod), as.double(CaliperVec), as.double(Xorig),
+                 as.integer(restrict.trigger), as.integer(restrict.nrow), as.double(restrict),
+                 as.double(DiagWeightMatrixFlag),
+                 PACKAGE="Matching")
+    return(ret)
+  } #end of MatchLoopCfast
+
+VarCalcMatchC <- function(N, xvars, Var.calc, cdd, caliperflag, ww, Tr, Xmod, CaliperVec,
+                          Xorig, restrict.trigger, restrict, DiagWeightMatrixFlag,
+                          Y, weightFlag, weight)
+  {
+
+    if(restrict.trigger)
+      {
+        restrict.nrow <- nrow(restrict)
+      } else {
+        restrict.nrow <- 0
+      }    
+    
+    ret <- .Call("VarCalcMatchC", as.integer(N), as.integer(xvars), as.integer(Var.calc),
+                 as.double(cdd), as.integer(caliperflag), 
+                 as.double(ww), as.double(Tr),
+                 as.double(Xmod), as.double(CaliperVec), as.double(Xorig),
+                 as.integer(restrict.trigger), as.integer(restrict.nrow), as.double(restrict),
+                 as.double(DiagWeightMatrixFlag),
+                 as.double(Y),
+                 as.integer(weightFlag), as.double(weight),
+                 PACKAGE="Matching")
+    return(ret)
+  } #end of VarCalcMatchC
+
+
+
+.onAttach <- function( ... )
+{
+  MatchLib <- dirname(system.file(package = "Matching"))
+  version <- packageDescription("Matching", lib.loc = MatchLib)$Version
+  BuildDate <- packageDescription("Matching", lib.loc = MatchLib)$Date
+
+  foo <- paste("## \n##  Matching (Version ", version, ", Build Date: ", BuildDate, ")\n", 
+               "##  See http://sekhon.berkeley.edu/matching for additional documentation.\n",
+               "##  Please cite software as:\n",
+               "##   Jasjeet S. Sekhon. 2011. ``Multivariate and Propensity Score Matching\n",
+               "##   Software with Automated Balance Optimization: The Matching package for R.''\n",
+               "##   Journal of Statistical Software, 42(7): 1-52. \n##\n",
+               sep = "")
+  packageStartupMessage(foo)
+}
+
+
diff --git a/cleanup b/cleanup
new file mode 100755
index 0000000..0b4b7bc
--- /dev/null
+++ b/cleanup
@@ -0,0 +1,22 @@
+#!/bin/sh
+
+# Cleanup our user created Makevars configure
+rm -f src/Makevars 
+
+# Revert to a clean (non-Darwin) state
+
+if test -f src/malloc.c; then
+ rm src/malloc.c
+fi
+
+if test ! -f src/cblas.h; then
+ cp inst/extras/cblas.h src/cblas.h
+fi
+
+if test ! -f src/cblas_dgemm.c; then
+ cp inst/extras/cblas_dgemm.c src/cblas_dgemm.c
+fi
+
+
+
+  
diff --git a/configure b/configure
new file mode 100755
index 0000000..a80cb98
--- /dev/null
+++ b/configure
@@ -0,0 +1,4188 @@
+#! /bin/sh
+# Guess values for system-dependent variables and create Makefiles.
+# Generated by GNU Autoconf 2.68 for Matching 4.0.8+.
+#
+# Report bugs to <sekhon at berkeley.edu>.
+#
+#
+# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
+# 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software
+# Foundation, Inc.
+#
+#
+# This configure script is free software; the Free Software Foundation
+# gives unlimited permission to copy, distribute and modify it.
+## -------------------- ##
+## M4sh Initialization. ##
+## -------------------- ##
+
+# Be more Bourne compatible
+DUALCASE=1; export DUALCASE # for MKS sh
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
+  emulate sh
+  NULLCMD=:
+  # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in #(
+  *posix*) :
+    set -o posix ;; #(
+  *) :
+     ;;
+esac
+fi
+
+
+as_nl='
+'
+export as_nl
+# Printing a long string crashes Solaris 7 /usr/bin/printf.
+as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
+as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
+# Prefer a ksh shell builtin over an external printf program on Solaris,
+# but without wasting forks for bash or zsh.
+if test -z "$BASH_VERSION$ZSH_VERSION" \
+    && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
+  as_echo='print -r --'
+  as_echo_n='print -rn --'
+elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
+  as_echo='printf %s\n'
+  as_echo_n='printf %s'
+else
+  if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
+    as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
+    as_echo_n='/usr/ucb/echo -n'
+  else
+    as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
+    as_echo_n_body='eval
+      arg=$1;
+      case $arg in #(
+      *"$as_nl"*)
+	expr "X$arg" : "X\\(.*\\)$as_nl";
+	arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
+      esac;
+      expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
+    '
+    export as_echo_n_body
+    as_echo_n='sh -c $as_echo_n_body as_echo'
+  fi
+  export as_echo_body
+  as_echo='sh -c $as_echo_body as_echo'
+fi
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+  PATH_SEPARATOR=:
+  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
+    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
+      PATH_SEPARATOR=';'
+  }
+fi
+
+
+# IFS
+# We need space, tab and new line, in precisely that order.  Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+IFS=" ""	$as_nl"
+
+# Find who we are.  Look in the path if we contain no directory separator.
+as_myself=
+case $0 in #((
+  *[\\/]* ) as_myself=$0 ;;
+  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+  done
+IFS=$as_save_IFS
+
+     ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" = x; then
+  as_myself=$0
+fi
+if test ! -f "$as_myself"; then
+  $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+  exit 1
+fi
+
+# Unset variables that we do not need and which cause bugs (e.g. in
+# pre-3.0 UWIN ksh).  But do not cause bugs in bash 2.01; the "|| exit 1"
+# suppresses any "Segmentation fault" message there.  '((' could
+# trigger a bug in pdksh 5.2.14.
+for as_var in BASH_ENV ENV MAIL MAILPATH
+do eval test x\${$as_var+set} = xset \
+  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
+done
+PS1='$ '
+PS2='> '
+PS4='+ '
+
+# NLS nuisances.
+LC_ALL=C
+export LC_ALL
+LANGUAGE=C
+export LANGUAGE
+
+# CDPATH.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+if test "x$CONFIG_SHELL" = x; then
+  as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then :
+  emulate sh
+  NULLCMD=:
+  # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '\${1+\"\$@\"}'='\"\$@\"'
+  setopt NO_GLOB_SUBST
+else
+  case \`(set -o) 2>/dev/null\` in #(
+  *posix*) :
+    set -o posix ;; #(
+  *) :
+     ;;
+esac
+fi
+"
+  as_required="as_fn_return () { (exit \$1); }
+as_fn_success () { as_fn_return 0; }
+as_fn_failure () { as_fn_return 1; }
+as_fn_ret_success () { return 0; }
+as_fn_ret_failure () { return 1; }
+
+exitcode=0
+as_fn_success || { exitcode=1; echo as_fn_success failed.; }
+as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; }
+as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; }
+as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; }
+if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then :
+
+else
+  exitcode=1; echo positional parameters were not saved.
+fi
+test x\$exitcode = x0 || exit 1"
+  as_suggested="  as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO
+  as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO
+  eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" &&
+  test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1"
+  if (eval "$as_required") 2>/dev/null; then :
+  as_have_required=yes
+else
+  as_have_required=no
+fi
+  if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then :
+
+else
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+as_found=false
+for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  as_found=:
+  case $as_dir in #(
+	 /*)
+	   for as_base in sh bash ksh sh5; do
+	     # Try only shells that exist, to save several forks.
+	     as_shell=$as_dir/$as_base
+	     if { test -f "$as_shell" || test -f "$as_shell.exe"; } &&
+		    { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then :
+  CONFIG_SHELL=$as_shell as_have_required=yes
+		   if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then :
+  break 2
+fi
+fi
+	   done;;
+       esac
+  as_found=false
+done
+$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } &&
+	      { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then :
+  CONFIG_SHELL=$SHELL as_have_required=yes
+fi; }
+IFS=$as_save_IFS
+
+
+      if test "x$CONFIG_SHELL" != x; then :
+  # We cannot yet assume a decent shell, so we have to provide a
+	# neutralization value for shells without unset; and this also
+	# works around shells that cannot unset nonexistent variables.
+	# Preserve -v and -x to the replacement shell.
+	BASH_ENV=/dev/null
+	ENV=/dev/null
+	(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
+	export CONFIG_SHELL
+	case $- in # ((((
+	  *v*x* | *x*v* ) as_opts=-vx ;;
+	  *v* ) as_opts=-v ;;
+	  *x* ) as_opts=-x ;;
+	  * ) as_opts= ;;
+	esac
+	exec "$CONFIG_SHELL" $as_opts "$as_myself" ${1+"$@"}
+fi
+
+    if test x$as_have_required = xno; then :
+  $as_echo "$0: This script requires a shell more modern than all"
+  $as_echo "$0: the shells that I found on your system."
+  if test x${ZSH_VERSION+set} = xset ; then
+    $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should"
+    $as_echo "$0: be upgraded to zsh 4.3.4 or later."
+  else
+    $as_echo "$0: Please tell bug-autoconf at gnu.org and
+$0: sekhon at berkeley.edu about your system, including any
+$0: error possibly output before this message. Then install
+$0: a modern shell, or manually run the script under such a
+$0: shell if you do have one."
+  fi
+  exit 1
+fi
+fi
+fi
+SHELL=${CONFIG_SHELL-/bin/sh}
+export SHELL
+# Unset more variables known to interfere with behavior of common tools.
+CLICOLOR_FORCE= GREP_OPTIONS=
+unset CLICOLOR_FORCE GREP_OPTIONS
+
+## --------------------- ##
+## M4sh Shell Functions. ##
+## --------------------- ##
+# as_fn_unset VAR
+# ---------------
+# Portably unset VAR.
+as_fn_unset ()
+{
+  { eval $1=; unset $1;}
+}
+as_unset=as_fn_unset
+
+# as_fn_set_status STATUS
+# -----------------------
+# Set $? to STATUS, without forking.
+as_fn_set_status ()
+{
+  return $1
+} # as_fn_set_status
+
+# as_fn_exit STATUS
+# -----------------
+# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
+as_fn_exit ()
+{
+  set +e
+  as_fn_set_status $1
+  exit $1
+} # as_fn_exit
+
+# as_fn_mkdir_p
+# -------------
+# Create "$as_dir" as a directory, including parents if necessary.
+as_fn_mkdir_p ()
+{
+
+  case $as_dir in #(
+  -*) as_dir=./$as_dir;;
+  esac
+  test -d "$as_dir" || eval $as_mkdir_p || {
+    as_dirs=
+    while :; do
+      case $as_dir in #(
+      *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
+      *) as_qdir=$as_dir;;
+      esac
+      as_dirs="'$as_qdir' $as_dirs"
+      as_dir=`$as_dirname -- "$as_dir" ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_dir" : 'X\(//\)[^/]' \| \
+	 X"$as_dir" : 'X\(//\)$' \| \
+	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$as_dir" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+      test -d "$as_dir" && break
+    done
+    test -z "$as_dirs" || eval "mkdir $as_dirs"
+  } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir"
+
+
+} # as_fn_mkdir_p
+# as_fn_append VAR VALUE
+# ----------------------
+# Append the text in VALUE to the end of the definition contained in VAR. Take
+# advantage of any shell optimizations that allow amortized linear growth over
+# repeated appends, instead of the typical quadratic growth present in naive
+# implementations.
+if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
+  eval 'as_fn_append ()
+  {
+    eval $1+=\$2
+  }'
+else
+  as_fn_append ()
+  {
+    eval $1=\$$1\$2
+  }
+fi # as_fn_append
+
+# as_fn_arith ARG...
+# ------------------
+# Perform arithmetic evaluation on the ARGs, and store the result in the
+# global $as_val. Take advantage of shells that can avoid forks. The arguments
+# must be portable across $(()) and expr.
+if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
+  eval 'as_fn_arith ()
+  {
+    as_val=$(( $* ))
+  }'
+else
+  as_fn_arith ()
+  {
+    as_val=`expr "$@" || test $? -eq 1`
+  }
+fi # as_fn_arith
+
+
+# as_fn_error STATUS ERROR [LINENO LOG_FD]
+# ----------------------------------------
+# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
+# provided, also output the error to LOG_FD, referencing LINENO. Then exit the
+# script with STATUS, using 1 if that was 0.
+as_fn_error ()
+{
+  as_status=$1; test $as_status -eq 0 && as_status=1
+  if test "$4"; then
+    as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+    $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
+  fi
+  $as_echo "$as_me: error: $2" >&2
+  as_fn_exit $as_status
+} # as_fn_error
+
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
+  as_basename=basename
+else
+  as_basename=false
+fi
+
+if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
+  as_dirname=dirname
+else
+  as_dirname=false
+fi
+
+as_me=`$as_basename -- "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+	 X"$0" : 'X\(//\)$' \| \
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X/"$0" |
+    sed '/^.*\/\([^/][^/]*\)\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
+
+
+  as_lineno_1=$LINENO as_lineno_1a=$LINENO
+  as_lineno_2=$LINENO as_lineno_2a=$LINENO
+  eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" &&
+  test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || {
+  # Blame Lee E. McMahon (1931-1989) for sed's syntax.  :-)
+  sed -n '
+    p
+    /[$]LINENO/=
+  ' <$as_myself |
+    sed '
+      s/[$]LINENO.*/&-/
+      t lineno
+      b
+      :lineno
+      N
+      :loop
+      s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
+      t loop
+      s/-\n.*//
+    ' >$as_me.lineno &&
+  chmod +x "$as_me.lineno" ||
+    { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; }
+
+  # Don't try to exec as it changes $[0], causing all sort of problems
+  # (the dirname of $[0] is not the place where we might find the
+  # original and so on.  Autoconf is especially sensitive to this).
+  . "./$as_me.lineno"
+  # Exit status is that of the last command.
+  exit
+}
+
+ECHO_C= ECHO_N= ECHO_T=
+case `echo -n x` in #(((((
+-n*)
+  case `echo 'xy\c'` in
+  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
+  xy)  ECHO_C='\c';;
+  *)   echo `echo ksh88 bug on AIX 6.1` > /dev/null
+       ECHO_T='	';;
+  esac;;
+*)
+  ECHO_N='-n';;
+esac
+
+rm -f conf$$ conf$$.exe conf$$.file
+if test -d conf$$.dir; then
+  rm -f conf$$.dir/conf$$.file
+else
+  rm -f conf$$.dir
+  mkdir conf$$.dir 2>/dev/null
+fi
+if (echo >conf$$.file) 2>/dev/null; then
+  if ln -s conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s='ln -s'
+    # ... but there are two gotchas:
+    # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+    # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
+    # In both cases, we have to default to `cp -p'.
+    ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+      as_ln_s='cp -p'
+  elif ln conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s=ln
+  else
+    as_ln_s='cp -p'
+  fi
+else
+  as_ln_s='cp -p'
+fi
+rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
+rmdir conf$$.dir 2>/dev/null
+
+if mkdir -p . 2>/dev/null; then
+  as_mkdir_p='mkdir -p "$as_dir"'
+else
+  test -d ./-p && rmdir ./-p
+  as_mkdir_p=false
+fi
+
+if test -x / >/dev/null 2>&1; then
+  as_test_x='test -x'
+else
+  if ls -dL / >/dev/null 2>&1; then
+    as_ls_L_option=L
+  else
+    as_ls_L_option=
+  fi
+  as_test_x='
+    eval sh -c '\''
+      if test -d "$1"; then
+	test -d "$1/.";
+      else
+	case $1 in #(
+	-*)set "./$1";;
+	esac;
+	case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #((
+	???[sx]*):;;*)false;;esac;fi
+    '\'' sh
+  '
+fi
+as_executable_p=$as_test_x
+
+# Sed expression to map a string onto a valid CPP name.
+as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
+
+# Sed expression to map a string onto a valid variable name.
+as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
+
+
+test -n "$DJDIR" || exec 7<&0 </dev/null
+exec 6>&1
+
+# Name of the host.
+# hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status,
+# so uname gets run too.
+ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q`
+
+#
+# Initializations.
+#
+ac_default_prefix=/usr/local
+ac_clean_files=
+ac_config_libobj_dir=.
+LIBOBJS=
+cross_compiling=no
+subdirs=
+MFLAGS=
+MAKEFLAGS=
+
+# Identity of this package.
+PACKAGE_NAME='Matching'
+PACKAGE_TARNAME='matching'
+PACKAGE_VERSION='4.0.8+'
+PACKAGE_STRING='Matching 4.0.8+'
+PACKAGE_BUGREPORT='sekhon at berkeley.edu'
+PACKAGE_URL=''
+
+ac_subst_vars='LTLIBOBJS
+LIBOBJS
+PKG_CXXFLAGS
+PKG_CFLAGS
+ac_ct_CXX
+CXXFLAGS
+CXX
+OBJEXT
+EXEEXT
+ac_ct_CC
+CPPFLAGS
+LDFLAGS
+CFLAGS
+CC
+target_alias
+host_alias
+build_alias
+LIBS
+ECHO_T
+ECHO_N
+ECHO_C
+DEFS
+mandir
+localedir
+libdir
+psdir
+pdfdir
+dvidir
+htmldir
+infodir
+docdir
+oldincludedir
+includedir
+localstatedir
+sharedstatedir
+sysconfdir
+datadir
+datarootdir
+libexecdir
+sbindir
+bindir
+program_transform_name
+prefix
+exec_prefix
+PACKAGE_URL
+PACKAGE_BUGREPORT
+PACKAGE_STRING
+PACKAGE_VERSION
+PACKAGE_TARNAME
+PACKAGE_NAME
+PATH_SEPARATOR
+SHELL'
+ac_subst_files=''
+ac_user_opts='
+enable_option_checking
+'
+      ac_precious_vars='build_alias
+host_alias
+target_alias
+CC
+CFLAGS
+LDFLAGS
+LIBS
+CPPFLAGS
+CXX
+CXXFLAGS
+LDFLAGS
+LIBS
+CPPFLAGS
+CCC'
+
+
+# Initialize some variables set by options.
+ac_init_help=
+ac_init_version=false
+ac_unrecognized_opts=
+ac_unrecognized_sep=
+# The variables have the same names as the options, with
+# dashes changed to underlines.
+cache_file=/dev/null
+exec_prefix=NONE
+no_create=
+no_recursion=
+prefix=NONE
+program_prefix=NONE
+program_suffix=NONE
+program_transform_name=s,x,x,
+silent=
+site=
+srcdir=
+verbose=
+x_includes=NONE
+x_libraries=NONE
+
+# Installation directory options.
+# These are left unexpanded so users can "make install exec_prefix=/foo"
+# and all the variables that are supposed to be based on exec_prefix
+# by default will actually change.
+# Use braces instead of parens because sh, perl, etc. also accept them.
+# (The list follows the same order as the GNU Coding Standards.)
+bindir='${exec_prefix}/bin'
+sbindir='${exec_prefix}/sbin'
+libexecdir='${exec_prefix}/libexec'
+datarootdir='${prefix}/share'
+datadir='${datarootdir}'
+sysconfdir='${prefix}/etc'
+sharedstatedir='${prefix}/com'
+localstatedir='${prefix}/var'
+includedir='${prefix}/include'
+oldincludedir='/usr/include'
+docdir='${datarootdir}/doc/${PACKAGE_TARNAME}'
+infodir='${datarootdir}/info'
+htmldir='${docdir}'
+dvidir='${docdir}'
+pdfdir='${docdir}'
+psdir='${docdir}'
+libdir='${exec_prefix}/lib'
+localedir='${datarootdir}/locale'
+mandir='${datarootdir}/man'
+
+ac_prev=
+ac_dashdash=
+for ac_option
+do
+  # If the previous option needs an argument, assign it.
+  if test -n "$ac_prev"; then
+    eval $ac_prev=\$ac_option
+    ac_prev=
+    continue
+  fi
+
+  case $ac_option in
+  *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;;
+  *=)   ac_optarg= ;;
+  *)    ac_optarg=yes ;;
+  esac
+
+  # Accept the important Cygnus configure options, so we can diagnose typos.
+
+  case $ac_dashdash$ac_option in
+  --)
+    ac_dashdash=yes ;;
+
+  -bindir | --bindir | --bindi | --bind | --bin | --bi)
+    ac_prev=bindir ;;
+  -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*)
+    bindir=$ac_optarg ;;
+
+  -build | --build | --buil | --bui | --bu)
+    ac_prev=build_alias ;;
+  -build=* | --build=* | --buil=* | --bui=* | --bu=*)
+    build_alias=$ac_optarg ;;
+
+  -cache-file | --cache-file | --cache-fil | --cache-fi \
+  | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)
+    ac_prev=cache_file ;;
+  -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \
+  | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*)
+    cache_file=$ac_optarg ;;
+
+  --config-cache | -C)
+    cache_file=config.cache ;;
+
+  -datadir | --datadir | --datadi | --datad)
+    ac_prev=datadir ;;
+  -datadir=* | --datadir=* | --datadi=* | --datad=*)
+    datadir=$ac_optarg ;;
+
+  -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \
+  | --dataroo | --dataro | --datar)
+    ac_prev=datarootdir ;;
+  -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \
+  | --dataroot=* | --dataroo=* | --dataro=* | --datar=*)
+    datarootdir=$ac_optarg ;;
+
+  -disable-* | --disable-*)
+    ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'`
+    # Reject names that are not valid shell variable names.
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error $? "invalid feature name: $ac_useropt"
+    ac_useropt_orig=$ac_useropt
+    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"enable_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig"
+	 ac_unrecognized_sep=', ';;
+    esac
+    eval enable_$ac_useropt=no ;;
+
+  -docdir | --docdir | --docdi | --doc | --do)
+    ac_prev=docdir ;;
+  -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*)
+    docdir=$ac_optarg ;;
+
+  -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv)
+    ac_prev=dvidir ;;
+  -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*)
+    dvidir=$ac_optarg ;;
+
+  -enable-* | --enable-*)
+    ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'`
+    # Reject names that are not valid shell variable names.
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error $? "invalid feature name: $ac_useropt"
+    ac_useropt_orig=$ac_useropt
+    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"enable_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig"
+	 ac_unrecognized_sep=', ';;
+    esac
+    eval enable_$ac_useropt=\$ac_optarg ;;
+
+  -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
+  | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
+  | --exec | --exe | --ex)
+    ac_prev=exec_prefix ;;
+  -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \
+  | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \
+  | --exec=* | --exe=* | --ex=*)
+    exec_prefix=$ac_optarg ;;
+
+  -gas | --gas | --ga | --g)
+    # Obsolete; use --with-gas.
+    with_gas=yes ;;
+
+  -help | --help | --hel | --he | -h)
+    ac_init_help=long ;;
+  -help=r* | --help=r* | --hel=r* | --he=r* | -hr*)
+    ac_init_help=recursive ;;
+  -help=s* | --help=s* | --hel=s* | --he=s* | -hs*)
+    ac_init_help=short ;;
+
+  -host | --host | --hos | --ho)
+    ac_prev=host_alias ;;
+  -host=* | --host=* | --hos=* | --ho=*)
+    host_alias=$ac_optarg ;;
+
+  -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht)
+    ac_prev=htmldir ;;
+  -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \
+  | --ht=*)
+    htmldir=$ac_optarg ;;
+
+  -includedir | --includedir | --includedi | --included | --include \
+  | --includ | --inclu | --incl | --inc)
+    ac_prev=includedir ;;
+  -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \
+  | --includ=* | --inclu=* | --incl=* | --inc=*)
+    includedir=$ac_optarg ;;
+
+  -infodir | --infodir | --infodi | --infod | --info | --inf)
+    ac_prev=infodir ;;
+  -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*)
+    infodir=$ac_optarg ;;
+
+  -libdir | --libdir | --libdi | --libd)
+    ac_prev=libdir ;;
+  -libdir=* | --libdir=* | --libdi=* | --libd=*)
+    libdir=$ac_optarg ;;
+
+  -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \
+  | --libexe | --libex | --libe)
+    ac_prev=libexecdir ;;
+  -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \
+  | --libexe=* | --libex=* | --libe=*)
+    libexecdir=$ac_optarg ;;
+
+  -localedir | --localedir | --localedi | --localed | --locale)
+    ac_prev=localedir ;;
+  -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*)
+    localedir=$ac_optarg ;;
+
+  -localstatedir | --localstatedir | --localstatedi | --localstated \
+  | --localstate | --localstat | --localsta | --localst | --locals)
+    ac_prev=localstatedir ;;
+  -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
+  | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*)
+    localstatedir=$ac_optarg ;;
+
+  -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
+    ac_prev=mandir ;;
+  -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*)
+    mandir=$ac_optarg ;;
+
+  -nfp | --nfp | --nf)
+    # Obsolete; use --without-fp.
+    with_fp=no ;;
+
+  -no-create | --no-create | --no-creat | --no-crea | --no-cre \
+  | --no-cr | --no-c | -n)
+    no_create=yes ;;
+
+  -no-recursion | --no-recursion | --no-recursio | --no-recursi \
+  | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r)
+    no_recursion=yes ;;
+
+  -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \
+  | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \
+  | --oldin | --oldi | --old | --ol | --o)
+    ac_prev=oldincludedir ;;
+  -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \
+  | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \
+  | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*)
+    oldincludedir=$ac_optarg ;;
+
+  -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
+    ac_prev=prefix ;;
+  -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
+    prefix=$ac_optarg ;;
+
+  -program-prefix | --program-prefix | --program-prefi | --program-pref \
+  | --program-pre | --program-pr | --program-p)
+    ac_prev=program_prefix ;;
+  -program-prefix=* | --program-prefix=* | --program-prefi=* \
+  | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*)
+    program_prefix=$ac_optarg ;;
+
+  -program-suffix | --program-suffix | --program-suffi | --program-suff \
+  | --program-suf | --program-su | --program-s)
+    ac_prev=program_suffix ;;
+  -program-suffix=* | --program-suffix=* | --program-suffi=* \
+  | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*)
+    program_suffix=$ac_optarg ;;
+
+  -program-transform-name | --program-transform-name \
+  | --program-transform-nam | --program-transform-na \
+  | --program-transform-n | --program-transform- \
+  | --program-transform | --program-transfor \
+  | --program-transfo | --program-transf \
+  | --program-trans | --program-tran \
+  | --progr-tra | --program-tr | --program-t)
+    ac_prev=program_transform_name ;;
+  -program-transform-name=* | --program-transform-name=* \
+  | --program-transform-nam=* | --program-transform-na=* \
+  | --program-transform-n=* | --program-transform-=* \
+  | --program-transform=* | --program-transfor=* \
+  | --program-transfo=* | --program-transf=* \
+  | --program-trans=* | --program-tran=* \
+  | --progr-tra=* | --program-tr=* | --program-t=*)
+    program_transform_name=$ac_optarg ;;
+
+  -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd)
+    ac_prev=pdfdir ;;
+  -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*)
+    pdfdir=$ac_optarg ;;
+
+  -psdir | --psdir | --psdi | --psd | --ps)
+    ac_prev=psdir ;;
+  -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*)
+    psdir=$ac_optarg ;;
+
+  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+  | -silent | --silent | --silen | --sile | --sil)
+    silent=yes ;;
+
+  -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb)
+    ac_prev=sbindir ;;
+  -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
+  | --sbi=* | --sb=*)
+    sbindir=$ac_optarg ;;
+
+  -sharedstatedir | --sharedstatedir | --sharedstatedi \
+  | --sharedstated | --sharedstate | --sharedstat | --sharedsta \
+  | --sharedst | --shareds | --shared | --share | --shar \
+  | --sha | --sh)
+    ac_prev=sharedstatedir ;;
+  -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \
+  | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \
+  | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \
+  | --sha=* | --sh=*)
+    sharedstatedir=$ac_optarg ;;
+
+  -site | --site | --sit)
+    ac_prev=site ;;
+  -site=* | --site=* | --sit=*)
+    site=$ac_optarg ;;
+
+  -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
+    ac_prev=srcdir ;;
+  -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
+    srcdir=$ac_optarg ;;
+
+  -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \
+  | --syscon | --sysco | --sysc | --sys | --sy)
+    ac_prev=sysconfdir ;;
+  -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \
+  | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*)
+    sysconfdir=$ac_optarg ;;
+
+  -target | --target | --targe | --targ | --tar | --ta | --t)
+    ac_prev=target_alias ;;
+  -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*)
+    target_alias=$ac_optarg ;;
+
+  -v | -verbose | --verbose | --verbos | --verbo | --verb)
+    verbose=yes ;;
+
+  -version | --version | --versio | --versi | --vers | -V)
+    ac_init_version=: ;;
+
+  -with-* | --with-*)
+    ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'`
+    # Reject names that are not valid shell variable names.
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error $? "invalid package name: $ac_useropt"
+    ac_useropt_orig=$ac_useropt
+    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"with_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig"
+	 ac_unrecognized_sep=', ';;
+    esac
+    eval with_$ac_useropt=\$ac_optarg ;;
+
+  -without-* | --without-*)
+    ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'`
+    # Reject names that are not valid shell variable names.
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error $? "invalid package name: $ac_useropt"
+    ac_useropt_orig=$ac_useropt
+    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"with_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig"
+	 ac_unrecognized_sep=', ';;
+    esac
+    eval with_$ac_useropt=no ;;
+
+  --x)
+    # Obsolete; use --with-x.
+    with_x=yes ;;
+
+  -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \
+  | --x-incl | --x-inc | --x-in | --x-i)
+    ac_prev=x_includes ;;
+  -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \
+  | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*)
+    x_includes=$ac_optarg ;;
+
+  -x-libraries | --x-libraries | --x-librarie | --x-librari \
+  | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l)
+    ac_prev=x_libraries ;;
+  -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \
+  | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*)
+    x_libraries=$ac_optarg ;;
+
+  -*) as_fn_error $? "unrecognized option: \`$ac_option'
+Try \`$0 --help' for more information"
+    ;;
+
+  *=*)
+    ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='`
+    # Reject names that are not valid shell variable names.
+    case $ac_envvar in #(
+      '' | [0-9]* | *[!_$as_cr_alnum]* )
+      as_fn_error $? "invalid variable name: \`$ac_envvar'" ;;
+    esac
+    eval $ac_envvar=\$ac_optarg
+    export $ac_envvar ;;
+
+  *)
+    # FIXME: should be removed in autoconf 3.0.
+    $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2
+    expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+      $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2
+    : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}"
+    ;;
+
+  esac
+done
+
+if test -n "$ac_prev"; then
+  ac_option=--`echo $ac_prev | sed 's/_/-/g'`
+  as_fn_error $? "missing argument to $ac_option"
+fi
+
+if test -n "$ac_unrecognized_opts"; then
+  case $enable_option_checking in
+    no) ;;
+    fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;;
+    *)     $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;;
+  esac
+fi
+
+# Check all directory arguments for consistency.
+for ac_var in	exec_prefix prefix bindir sbindir libexecdir datarootdir \
+		datadir sysconfdir sharedstatedir localstatedir includedir \
+		oldincludedir docdir infodir htmldir dvidir pdfdir psdir \
+		libdir localedir mandir
+do
+  eval ac_val=\$$ac_var
+  # Remove trailing slashes.
+  case $ac_val in
+    */ )
+      ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'`
+      eval $ac_var=\$ac_val;;
+  esac
+  # Be sure to have absolute directory names.
+  case $ac_val in
+    [\\/$]* | ?:[\\/]* )  continue;;
+    NONE | '' ) case $ac_var in *prefix ) continue;; esac;;
+  esac
+  as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val"
+done
+
+# There might be people who depend on the old broken behavior: `$host'
+# used to hold the argument of --host etc.
+# FIXME: To remove some day.
+build=$build_alias
+host=$host_alias
+target=$target_alias
+
+# FIXME: To remove some day.
+if test "x$host_alias" != x; then
+  if test "x$build_alias" = x; then
+    cross_compiling=maybe
+    $as_echo "$as_me: WARNING: if you wanted to set the --build type, don't use --host.
+    If a cross compiler is detected then cross compile mode will be used" >&2
+  elif test "x$build_alias" != "x$host_alias"; then
+    cross_compiling=yes
+  fi
+fi
+
+ac_tool_prefix=
+test -n "$host_alias" && ac_tool_prefix=$host_alias-
+
+test "$silent" = yes && exec 6>/dev/null
+
+
+ac_pwd=`pwd` && test -n "$ac_pwd" &&
+ac_ls_di=`ls -di .` &&
+ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` ||
+  as_fn_error $? "working directory cannot be determined"
+test "X$ac_ls_di" = "X$ac_pwd_ls_di" ||
+  as_fn_error $? "pwd does not report name of working directory"
+
+
+# Find the source files, if location was not specified.
+if test -z "$srcdir"; then
+  ac_srcdir_defaulted=yes
+  # Try the directory containing this script, then the parent directory.
+  ac_confdir=`$as_dirname -- "$as_myself" ||
+$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_myself" : 'X\(//\)[^/]' \| \
+	 X"$as_myself" : 'X\(//\)$' \| \
+	 X"$as_myself" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$as_myself" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+  srcdir=$ac_confdir
+  if test ! -r "$srcdir/$ac_unique_file"; then
+    srcdir=..
+  fi
+else
+  ac_srcdir_defaulted=no
+fi
+if test ! -r "$srcdir/$ac_unique_file"; then
+  test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .."
+  as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir"
+fi
+ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work"
+ac_abs_confdir=`(
+	cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg"
+	pwd)`
+# When building in place, set srcdir=.
+if test "$ac_abs_confdir" = "$ac_pwd"; then
+  srcdir=.
+fi
+# Remove unnecessary trailing slashes from srcdir.
+# Double slashes in file names in object file debugging info
+# mess up M-x gdb in Emacs.
+case $srcdir in
+*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;;
+esac
+for ac_var in $ac_precious_vars; do
+  eval ac_env_${ac_var}_set=\${${ac_var}+set}
+  eval ac_env_${ac_var}_value=\$${ac_var}
+  eval ac_cv_env_${ac_var}_set=\${${ac_var}+set}
+  eval ac_cv_env_${ac_var}_value=\$${ac_var}
+done
+
+#
+# Report the --help message.
+#
+if test "$ac_init_help" = "long"; then
+  # Omit some internal or obsolete options to make the list less imposing.
+  # This message is too long to be a string in the A/UX 3.1 sh.
+  cat <<_ACEOF
+\`configure' configures Matching 4.0.8+ to adapt to many kinds of systems.
+
+Usage: $0 [OPTION]... [VAR=VALUE]...
+
+To assign environment variables (e.g., CC, CFLAGS...), specify them as
+VAR=VALUE.  See below for descriptions of some of the useful variables.
+
+Defaults for the options are specified in brackets.
+
+Configuration:
+  -h, --help              display this help and exit
+      --help=short        display options specific to this package
+      --help=recursive    display the short help of all the included packages
+  -V, --version           display version information and exit
+  -q, --quiet, --silent   do not print \`checking ...' messages
+      --cache-file=FILE   cache test results in FILE [disabled]
+  -C, --config-cache      alias for \`--cache-file=config.cache'
+  -n, --no-create         do not create output files
+      --srcdir=DIR        find the sources in DIR [configure dir or \`..']
+
+Installation directories:
+  --prefix=PREFIX         install architecture-independent files in PREFIX
+                          [$ac_default_prefix]
+  --exec-prefix=EPREFIX   install architecture-dependent files in EPREFIX
+                          [PREFIX]
+
+By default, \`make install' will install all the files in
+\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc.  You can specify
+an installation prefix other than \`$ac_default_prefix' using \`--prefix',
+for instance \`--prefix=\$HOME'.
+
+For better control, use the options below.
+
+Fine tuning of the installation directories:
+  --bindir=DIR            user executables [EPREFIX/bin]
+  --sbindir=DIR           system admin executables [EPREFIX/sbin]
+  --libexecdir=DIR        program executables [EPREFIX/libexec]
+  --sysconfdir=DIR        read-only single-machine data [PREFIX/etc]
+  --sharedstatedir=DIR    modifiable architecture-independent data [PREFIX/com]
+  --localstatedir=DIR     modifiable single-machine data [PREFIX/var]
+  --libdir=DIR            object code libraries [EPREFIX/lib]
+  --includedir=DIR        C header files [PREFIX/include]
+  --oldincludedir=DIR     C header files for non-gcc [/usr/include]
+  --datarootdir=DIR       read-only arch.-independent data root [PREFIX/share]
+  --datadir=DIR           read-only architecture-independent data [DATAROOTDIR]
+  --infodir=DIR           info documentation [DATAROOTDIR/info]
+  --localedir=DIR         locale-dependent data [DATAROOTDIR/locale]
+  --mandir=DIR            man documentation [DATAROOTDIR/man]
+  --docdir=DIR            documentation root [DATAROOTDIR/doc/matching]
+  --htmldir=DIR           html documentation [DOCDIR]
+  --dvidir=DIR            dvi documentation [DOCDIR]
+  --pdfdir=DIR            pdf documentation [DOCDIR]
+  --psdir=DIR             ps documentation [DOCDIR]
+_ACEOF
+
+  cat <<\_ACEOF
+_ACEOF
+fi
+
+if test -n "$ac_init_help"; then
+  case $ac_init_help in
+     short | recursive ) echo "Configuration of Matching 4.0.8+:";;
+   esac
+  cat <<\_ACEOF
+
+Some influential environment variables:
+  CC          C compiler command
+  CFLAGS      C compiler flags
+  LDFLAGS     linker flags, e.g. -L<lib dir> if you have libraries in a
+              nonstandard directory <lib dir>
+  LIBS        libraries to pass to the linker, e.g. -l<library>
+  CPPFLAGS    (Objective) C/C++ preprocessor flags, e.g. -I<include dir> if
+              you have headers in a nonstandard directory <include dir>
+  CXX         C++ compiler command
+  CXXFLAGS    C++ compiler flags
+
+Use these variables to override the choices made by `configure' or to help
+it to find libraries and programs with nonstandard names/locations.
+
+Report bugs to <sekhon at berkeley.edu>.
+_ACEOF
+ac_status=$?
+fi
+
+if test "$ac_init_help" = "recursive"; then
+  # If there are subdirs, report their specific --help.
+  for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue
+    test -d "$ac_dir" ||
+      { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } ||
+      continue
+    ac_builddir=.
+
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+  ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
+
+case $srcdir in
+  .)  # We are building in place.
+    ac_srcdir=.
+    ac_top_srcdir=$ac_top_builddir_sub
+    ac_abs_top_srcdir=$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
+    ac_srcdir=$srcdir$ac_dir_suffix;
+    ac_top_srcdir=$srcdir
+    ac_abs_top_srcdir=$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+    cd "$ac_dir" || { ac_status=$?; continue; }
+    # Check for guested configure.
+    if test -f "$ac_srcdir/configure.gnu"; then
+      echo &&
+      $SHELL "$ac_srcdir/configure.gnu" --help=recursive
+    elif test -f "$ac_srcdir/configure"; then
+      echo &&
+      $SHELL "$ac_srcdir/configure" --help=recursive
+    else
+      $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2
+    fi || ac_status=$?
+    cd "$ac_pwd" || { ac_status=$?; break; }
+  done
+fi
+
+test -n "$ac_init_help" && exit $ac_status
+if $ac_init_version; then
+  cat <<\_ACEOF
+Matching configure 4.0.8+
+generated by GNU Autoconf 2.68
+
+Copyright (C) 2010 Free Software Foundation, Inc.
+This configure script is free software; the Free Software Foundation
+gives unlimited permission to copy, distribute and modify it.
+_ACEOF
+  exit
+fi
+
+## ------------------------ ##
+## Autoconf initialization. ##
+## ------------------------ ##
+
+# ac_fn_c_try_compile LINENO
+# --------------------------
+# Try to compile conftest.$ac_ext, and return whether this succeeded.
+ac_fn_c_try_compile ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  rm -f conftest.$ac_objext
+  if { { ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_compile") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    grep -v '^ *+' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+    mv -f conftest.er1 conftest.err
+  fi
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	ac_retval=1
+fi
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+  as_fn_set_status $ac_retval
+
+} # ac_fn_c_try_compile
+
+# ac_fn_cxx_try_compile LINENO
+# ----------------------------
+# Try to compile conftest.$ac_ext, and return whether this succeeded.
+ac_fn_cxx_try_compile ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  rm -f conftest.$ac_objext
+  if { { ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_compile") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    grep -v '^ *+' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+    mv -f conftest.er1 conftest.err
+  fi
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } && {
+	 test -z "$ac_cxx_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	ac_retval=1
+fi
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+  as_fn_set_status $ac_retval
+
+} # ac_fn_cxx_try_compile
+cat >config.log <<_ACEOF
+This file contains any messages produced by compilers while
+running configure, to aid debugging if configure makes a mistake.
+
+It was created by Matching $as_me 4.0.8+, which was
+generated by GNU Autoconf 2.68.  Invocation command line was
+
+  $ $0 $@
+
+_ACEOF
+exec 5>>config.log
+{
+cat <<_ASUNAME
+## --------- ##
+## Platform. ##
+## --------- ##
+
+hostname = `(hostname || uname -n) 2>/dev/null | sed 1q`
+uname -m = `(uname -m) 2>/dev/null || echo unknown`
+uname -r = `(uname -r) 2>/dev/null || echo unknown`
+uname -s = `(uname -s) 2>/dev/null || echo unknown`
+uname -v = `(uname -v) 2>/dev/null || echo unknown`
+
+/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown`
+/bin/uname -X     = `(/bin/uname -X) 2>/dev/null     || echo unknown`
+
+/bin/arch              = `(/bin/arch) 2>/dev/null              || echo unknown`
+/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null       || echo unknown`
+/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown`
+/usr/bin/hostinfo      = `(/usr/bin/hostinfo) 2>/dev/null      || echo unknown`
+/bin/machine           = `(/bin/machine) 2>/dev/null           || echo unknown`
+/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null       || echo unknown`
+/bin/universe          = `(/bin/universe) 2>/dev/null          || echo unknown`
+
+_ASUNAME
+
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    $as_echo "PATH: $as_dir"
+  done
+IFS=$as_save_IFS
+
+} >&5
+
+cat >&5 <<_ACEOF
+
+
+## ----------- ##
+## Core tests. ##
+## ----------- ##
+
+_ACEOF
+
+
+# Keep a trace of the command line.
+# Strip out --no-create and --no-recursion so they do not pile up.
+# Strip out --silent because we don't want to record it for future runs.
+# Also quote any args containing shell meta-characters.
+# Make two passes to allow for proper duplicate-argument suppression.
+ac_configure_args=
+ac_configure_args0=
+ac_configure_args1=
+ac_must_keep_next=false
+for ac_pass in 1 2
+do
+  for ac_arg
+  do
+    case $ac_arg in
+    -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;;
+    -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+    | -silent | --silent | --silen | --sile | --sil)
+      continue ;;
+    *\'*)
+      ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
+    esac
+    case $ac_pass in
+    1) as_fn_append ac_configure_args0 " '$ac_arg'" ;;
+    2)
+      as_fn_append ac_configure_args1 " '$ac_arg'"
+      if test $ac_must_keep_next = true; then
+	ac_must_keep_next=false # Got value, back to normal.
+      else
+	case $ac_arg in
+	  *=* | --config-cache | -C | -disable-* | --disable-* \
+	  | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \
+	  | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \
+	  | -with-* | --with-* | -without-* | --without-* | --x)
+	    case "$ac_configure_args0 " in
+	      "$ac_configure_args1"*" '$ac_arg' "* ) continue ;;
+	    esac
+	    ;;
+	  -* ) ac_must_keep_next=true ;;
+	esac
+      fi
+      as_fn_append ac_configure_args " '$ac_arg'"
+      ;;
+    esac
+  done
+done
+{ ac_configure_args0=; unset ac_configure_args0;}
+{ ac_configure_args1=; unset ac_configure_args1;}
+
+# When interrupted or exit'd, cleanup temporary files, and complete
+# config.log.  We remove comments because anyway the quotes in there
+# would cause problems or look ugly.
+# WARNING: Use '\'' to represent an apostrophe within the trap.
+# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug.
+trap 'exit_status=$?
+  # Save into config.log some information that might help in debugging.
+  {
+    echo
+
+    $as_echo "## ---------------- ##
+## Cache variables. ##
+## ---------------- ##"
+    echo
+    # The following way of writing the cache mishandles newlines in values,
+(
+  for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do
+    eval ac_val=\$$ac_var
+    case $ac_val in #(
+    *${as_nl}*)
+      case $ac_var in #(
+      *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
+$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
+      esac
+      case $ac_var in #(
+      _ | IFS | as_nl) ;; #(
+      BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #(
+      *) { eval $ac_var=; unset $ac_var;} ;;
+      esac ;;
+    esac
+  done
+  (set) 2>&1 |
+    case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #(
+    *${as_nl}ac_space=\ *)
+      sed -n \
+	"s/'\''/'\''\\\\'\'''\''/g;
+	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p"
+      ;; #(
+    *)
+      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
+      ;;
+    esac |
+    sort
+)
+    echo
+
+    $as_echo "## ----------------- ##
+## Output variables. ##
+## ----------------- ##"
+    echo
+    for ac_var in $ac_subst_vars
+    do
+      eval ac_val=\$$ac_var
+      case $ac_val in
+      *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+      esac
+      $as_echo "$ac_var='\''$ac_val'\''"
+    done | sort
+    echo
+
+    if test -n "$ac_subst_files"; then
+      $as_echo "## ------------------- ##
+## File substitutions. ##
+## ------------------- ##"
+      echo
+      for ac_var in $ac_subst_files
+      do
+	eval ac_val=\$$ac_var
+	case $ac_val in
+	*\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+	esac
+	$as_echo "$ac_var='\''$ac_val'\''"
+      done | sort
+      echo
+    fi
+
+    if test -s confdefs.h; then
+      $as_echo "## ----------- ##
+## confdefs.h. ##
+## ----------- ##"
+      echo
+      cat confdefs.h
+      echo
+    fi
+    test "$ac_signal" != 0 &&
+      $as_echo "$as_me: caught signal $ac_signal"
+    $as_echo "$as_me: exit $exit_status"
+  } >&5
+  rm -f core *.core core.conftest.* &&
+    rm -f -r conftest* confdefs* conf$$* $ac_clean_files &&
+    exit $exit_status
+' 0
+for ac_signal in 1 2 13 15; do
+  trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal
+done
+ac_signal=0
+
+# confdefs.h avoids OS command line length limits that DEFS can exceed.
+rm -f -r conftest* confdefs.h
+
+$as_echo "/* confdefs.h */" > confdefs.h
+
+# Predefined preprocessor variables.
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_NAME "$PACKAGE_NAME"
+_ACEOF
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_TARNAME "$PACKAGE_TARNAME"
+_ACEOF
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_VERSION "$PACKAGE_VERSION"
+_ACEOF
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_STRING "$PACKAGE_STRING"
+_ACEOF
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT"
+_ACEOF
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_URL "$PACKAGE_URL"
+_ACEOF
+
+
+# Let the site file select an alternate cache file if it wants to.
+# Prefer an explicitly selected file to automatically selected ones.
+ac_site_file1=NONE
+ac_site_file2=NONE
+if test -n "$CONFIG_SITE"; then
+  # We do not want a PATH search for config.site.
+  case $CONFIG_SITE in #((
+    -*)  ac_site_file1=./$CONFIG_SITE;;
+    */*) ac_site_file1=$CONFIG_SITE;;
+    *)   ac_site_file1=./$CONFIG_SITE;;
+  esac
+elif test "x$prefix" != xNONE; then
+  ac_site_file1=$prefix/share/config.site
+  ac_site_file2=$prefix/etc/config.site
+else
+  ac_site_file1=$ac_default_prefix/share/config.site
+  ac_site_file2=$ac_default_prefix/etc/config.site
+fi
+for ac_site_file in "$ac_site_file1" "$ac_site_file2"
+do
+  test "x$ac_site_file" = xNONE && continue
+  if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5
+$as_echo "$as_me: loading site script $ac_site_file" >&6;}
+    sed 's/^/| /' "$ac_site_file" >&5
+    . "$ac_site_file" \
+      || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "failed to load site script $ac_site_file
+See \`config.log' for more details" "$LINENO" 5; }
+  fi
+done
+
+if test -r "$cache_file"; then
+  # Some versions of bash will fail to source /dev/null (special files
+  # actually), so we avoid doing that.  DJGPP emulates it as a regular file.
+  if test /dev/null != "$cache_file" && test -f "$cache_file"; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5
+$as_echo "$as_me: loading cache $cache_file" >&6;}
+    case $cache_file in
+      [\\/]* | ?:[\\/]* ) . "$cache_file";;
+      *)                      . "./$cache_file";;
+    esac
+  fi
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5
+$as_echo "$as_me: creating cache $cache_file" >&6;}
+  >$cache_file
+fi
+
+# Check that the precious variables saved in the cache have kept the same
+# value.
+ac_cache_corrupted=false
+for ac_var in $ac_precious_vars; do
+  eval ac_old_set=\$ac_cv_env_${ac_var}_set
+  eval ac_new_set=\$ac_env_${ac_var}_set
+  eval ac_old_val=\$ac_cv_env_${ac_var}_value
+  eval ac_new_val=\$ac_env_${ac_var}_value
+  case $ac_old_set,$ac_new_set in
+    set,)
+      { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5
+$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;}
+      ac_cache_corrupted=: ;;
+    ,set)
+      { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5
+$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}
+      ac_cache_corrupted=: ;;
+    ,);;
+    *)
+      if test "x$ac_old_val" != "x$ac_new_val"; then
+	# differences in whitespace do not lead to failure.
+	ac_old_val_w=`echo x $ac_old_val`
+	ac_new_val_w=`echo x $ac_new_val`
+	if test "$ac_old_val_w" != "$ac_new_val_w"; then
+	  { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5
+$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;}
+	  ac_cache_corrupted=:
+	else
+	  { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5
+$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;}
+	  eval $ac_var=\$ac_old_val
+	fi
+	{ $as_echo "$as_me:${as_lineno-$LINENO}:   former value:  \`$ac_old_val'" >&5
+$as_echo "$as_me:   former value:  \`$ac_old_val'" >&2;}
+	{ $as_echo "$as_me:${as_lineno-$LINENO}:   current value: \`$ac_new_val'" >&5
+$as_echo "$as_me:   current value: \`$ac_new_val'" >&2;}
+      fi;;
+  esac
+  # Pass precious variables to config.status.
+  if test "$ac_new_set" = set; then
+    case $ac_new_val in
+    *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
+    *) ac_arg=$ac_var=$ac_new_val ;;
+    esac
+    case " $ac_configure_args " in
+      *" '$ac_arg' "*) ;; # Avoid dups.  Use of quotes ensures accuracy.
+      *) as_fn_append ac_configure_args " '$ac_arg'" ;;
+    esac
+  fi
+done
+if $ac_cache_corrupted; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+  { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5
+$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;}
+  as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5
+fi
+## -------------------- ##
+## Main body of script. ##
+## -------------------- ##
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+
+: ${R_HOME=`R RHOME`}
+if test -z "${R_HOME}"; then
+  echo "could not determine R_HOME"
+  exit 1
+fi
+CC=`"${R_HOME}/bin/R" CMD config CC`
+CXX=`"${R_HOME}/bin/R" CMD config CXX`
+RCFLAGS=`"${R_HOME}/bin/R" CMD config CFLAGS`
+RCXXFLAGS=`"${R_HOME}/bin/R" CMD config CXXFLAGS`
+
+
+MYCFLAGS0="-O3"
+MYCFLAGS1="-finline-functions -funroll-loops -fexpensive-optimizations"
+MYCFLAGS2="-funswitch-loops -fgcse-after-reload -fstrict-aliasing -freorder-blocks -fsched-interblock"
+
+
+
+
+MYCXXFLAGS0="-O3"
+MYCXXFLAGS1="-finline-functions -funroll-loops -fexpensive-optimizations"
+MYCXXFLAGS2="-funswitch-loops -fgcse-after-reload -fstrict-aliasing -freorder-blocks -fsched-interblock"
+
+
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args.
+set dummy ${ac_tool_prefix}gcc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_CC="${ac_tool_prefix}gcc"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+fi
+if test -z "$ac_cv_prog_CC"; then
+  ac_ct_CC=$CC
+  # Extract the first word of "gcc", so it can be a program name with args.
+set dummy gcc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_CC"; then
+  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_CC="gcc"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_CC=$ac_cv_prog_ac_ct_CC
+if test -n "$ac_ct_CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
+$as_echo "$ac_ct_CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+  if test "x$ac_ct_CC" = x; then
+    CC=""
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    CC=$ac_ct_CC
+  fi
+else
+  CC="$ac_cv_prog_CC"
+fi
+
+if test -z "$CC"; then
+          if test -n "$ac_tool_prefix"; then
+    # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args.
+set dummy ${ac_tool_prefix}cc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_CC="${ac_tool_prefix}cc"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  fi
+fi
+if test -z "$CC"; then
+  # Extract the first word of "cc", so it can be a program name with args.
+set dummy cc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+  ac_prog_rejected=no
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then
+       ac_prog_rejected=yes
+       continue
+     fi
+    ac_cv_prog_CC="cc"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+if test $ac_prog_rejected = yes; then
+  # We found a bogon in the path, so make sure we never use it.
+  set dummy $ac_cv_prog_CC
+  shift
+  if test $# != 0; then
+    # We chose a different compiler from the bogus one.
+    # However, it has the same basename, so the bogon will be chosen
+    # first if we set CC to just the basename; use the full file name.
+    shift
+    ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@"
+  fi
+fi
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+fi
+if test -z "$CC"; then
+  if test -n "$ac_tool_prefix"; then
+  for ac_prog in cl.exe
+  do
+    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
+set dummy $ac_tool_prefix$ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_CC="$ac_tool_prefix$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+    test -n "$CC" && break
+  done
+fi
+if test -z "$CC"; then
+  ac_ct_CC=$CC
+  for ac_prog in cl.exe
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_CC"; then
+  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_CC="$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_CC=$ac_cv_prog_ac_ct_CC
+if test -n "$ac_ct_CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
+$as_echo "$ac_ct_CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$ac_ct_CC" && break
+done
+
+  if test "x$ac_ct_CC" = x; then
+    CC=""
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    CC=$ac_ct_CC
+  fi
+fi
+
+fi
+
+
+test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "no acceptable C compiler found in \$PATH
+See \`config.log' for more details" "$LINENO" 5; }
+
+# Provide some information about the compiler.
+$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5
+set X $ac_compile
+ac_compiler=$2
+for ac_option in --version -v -V -qversion; do
+  { { ac_try="$ac_compiler $ac_option >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_compiler $ac_option >&5") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    sed '10a\
+... rest of stderr output deleted ...
+         10q' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+  fi
+  rm -f conftest.er1 conftest.err
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+done
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+ac_clean_files_save=$ac_clean_files
+ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out"
+# Try to create an executable without -o first, disregard a.out.
+# It will help us diagnose broken compilers, and finding out an intuition
+# of exeext.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5
+$as_echo_n "checking whether the C compiler works... " >&6; }
+ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'`
+
+# The possible output files:
+ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*"
+
+ac_rmfiles=
+for ac_file in $ac_files
+do
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;;
+    * ) ac_rmfiles="$ac_rmfiles $ac_file";;
+  esac
+done
+rm -f $ac_rmfiles
+
+if { { ac_try="$ac_link_default"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link_default") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then :
+  # Autoconf-2.13 could set the ac_cv_exeext variable to `no'.
+# So ignore a value of `no', otherwise this would lead to `EXEEXT = no'
+# in a Makefile.  We should not override ac_cv_exeext if it was cached,
+# so that the user can short-circuit this test for compilers unknown to
+# Autoconf.
+for ac_file in $ac_files ''
+do
+  test -f "$ac_file" || continue
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj )
+	;;
+    [ab].out )
+	# We found the default executable, but exeext='' is most
+	# certainly right.
+	break;;
+    *.* )
+	if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no;
+	then :; else
+	   ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
+	fi
+	# We set ac_cv_exeext here because the later test for it is not
+	# safe: cross compilers may not add the suffix if given an `-o'
+	# argument, so we may need to know it at that point already.
+	# Even if this section looks crufty: it has the advantage of
+	# actually working.
+	break;;
+    * )
+	break;;
+  esac
+done
+test "$ac_cv_exeext" = no && ac_cv_exeext=
+
+else
+  ac_file=''
+fi
+if test -z "$ac_file"; then :
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+$as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error 77 "C compiler cannot create executables
+See \`config.log' for more details" "$LINENO" 5; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5
+$as_echo_n "checking for C compiler default output file name... " >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5
+$as_echo "$ac_file" >&6; }
+ac_exeext=$ac_cv_exeext
+
+rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out
+ac_clean_files=$ac_clean_files_save
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5
+$as_echo_n "checking for suffix of executables... " >&6; }
+if { { ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then :
+  # If both `conftest.exe' and `conftest' are `present' (well, observable)
+# catch `conftest.exe'.  For instance with Cygwin, `ls conftest' will
+# work properly (i.e., refer to `conftest.exe'), while it won't with
+# `rm'.
+for ac_file in conftest.exe conftest conftest.*; do
+  test -f "$ac_file" || continue
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;;
+    *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
+	  break;;
+    * ) break;;
+  esac
+done
+else
+  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "cannot compute suffix of executables: cannot compile and link
+See \`config.log' for more details" "$LINENO" 5; }
+fi
+rm -f conftest conftest$ac_cv_exeext
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5
+$as_echo "$ac_cv_exeext" >&6; }
+
+rm -f conftest.$ac_ext
+EXEEXT=$ac_cv_exeext
+ac_exeext=$EXEEXT
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdio.h>
+int
+main ()
+{
+FILE *f = fopen ("conftest.out", "w");
+ return ferror (f) || fclose (f) != 0;
+
+  ;
+  return 0;
+}
+_ACEOF
+ac_clean_files="$ac_clean_files conftest.out"
+# Check that the compiler produces executables we can run.  If not, either
+# the compiler is broken, or we cross compile.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5
+$as_echo_n "checking whether we are cross compiling... " >&6; }
+if test "$cross_compiling" != yes; then
+  { { ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+  if { ac_try='./conftest$ac_cv_exeext'
+  { { case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_try") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; }; then
+    cross_compiling=no
+  else
+    if test "$cross_compiling" = maybe; then
+	cross_compiling=yes
+    else
+	{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "cannot run C compiled programs.
+If you meant to cross compile, use \`--host'.
+See \`config.log' for more details" "$LINENO" 5; }
+    fi
+  fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5
+$as_echo "$cross_compiling" >&6; }
+
+rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out
+ac_clean_files=$ac_clean_files_save
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5
+$as_echo_n "checking for suffix of object files... " >&6; }
+if ${ac_cv_objext+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.o conftest.obj
+if { { ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_compile") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then :
+  for ac_file in conftest.o conftest.obj conftest.*; do
+  test -f "$ac_file" || continue;
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;;
+    *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'`
+       break;;
+  esac
+done
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "cannot compute suffix of object files: cannot compile
+See \`config.log' for more details" "$LINENO" 5; }
+fi
+rm -f conftest.$ac_cv_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5
+$as_echo "$ac_cv_objext" >&6; }
+OBJEXT=$ac_cv_objext
+ac_objext=$OBJEXT
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5
+$as_echo_n "checking whether we are using the GNU C compiler... " >&6; }
+if ${ac_cv_c_compiler_gnu+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+#ifndef __GNUC__
+       choke me
+#endif
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_compiler_gnu=yes
+else
+  ac_compiler_gnu=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ac_cv_c_compiler_gnu=$ac_compiler_gnu
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5
+$as_echo "$ac_cv_c_compiler_gnu" >&6; }
+if test $ac_compiler_gnu = yes; then
+  GCC=yes
+else
+  GCC=
+fi
+ac_test_CFLAGS=${CFLAGS+set}
+ac_save_CFLAGS=$CFLAGS
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5
+$as_echo_n "checking whether $CC accepts -g... " >&6; }
+if ${ac_cv_prog_cc_g+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_save_c_werror_flag=$ac_c_werror_flag
+   ac_c_werror_flag=yes
+   ac_cv_prog_cc_g=no
+   CFLAGS="-g"
+   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_prog_cc_g=yes
+else
+  CFLAGS=""
+      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+
+else
+  ac_c_werror_flag=$ac_save_c_werror_flag
+	 CFLAGS="-g"
+	 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_prog_cc_g=yes
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+   ac_c_werror_flag=$ac_save_c_werror_flag
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5
+$as_echo "$ac_cv_prog_cc_g" >&6; }
+if test "$ac_test_CFLAGS" = set; then
+  CFLAGS=$ac_save_CFLAGS
+elif test $ac_cv_prog_cc_g = yes; then
+  if test "$GCC" = yes; then
+    CFLAGS="-g -O2"
+  else
+    CFLAGS="-g"
+  fi
+else
+  if test "$GCC" = yes; then
+    CFLAGS="-O2"
+  else
+    CFLAGS=
+  fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5
+$as_echo_n "checking for $CC option to accept ISO C89... " >&6; }
+if ${ac_cv_prog_cc_c89+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_cv_prog_cc_c89=no
+ac_save_CC=$CC
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdarg.h>
+#include <stdio.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+/* Most of the following tests are stolen from RCS 5.7's src/conf.sh.  */
+struct buf { int x; };
+FILE * (*rcsopen) (struct buf *, struct stat *, int);
+static char *e (p, i)
+     char **p;
+     int i;
+{
+  return p[i];
+}
+static char *f (char * (*g) (char **, int), char **p, ...)
+{
+  char *s;
+  va_list v;
+  va_start (v,p);
+  s = g (p, va_arg (v,int));
+  va_end (v);
+  return s;
+}
+
+/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default.  It has
+   function prototypes and stuff, but not '\xHH' hex character constants.
+   These don't provoke an error unfortunately, instead are silently treated
+   as 'x'.  The following induces an error, until -std is added to get
+   proper ANSI mode.  Curiously '\x00'!='x' always comes out true, for an
+   array size at least.  It's necessary to write '\x00'==0 to get something
+   that's true only with -std.  */
+int osf4_cc_array ['\x00' == 0 ? 1 : -1];
+
+/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters
+   inside strings and character constants.  */
+#define FOO(x) 'x'
+int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1];
+
+int test (int i, double x);
+struct s1 {int (*f) (int a);};
+struct s2 {int (*f) (double a);};
+int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int);
+int argc;
+char **argv;
+int
+main ()
+{
+return f (e, argv, 0) != argv[0]  ||  f (e, argv, 1) != argv[1];
+  ;
+  return 0;
+}
+_ACEOF
+for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \
+	-Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
+do
+  CC="$ac_save_CC $ac_arg"
+  if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_prog_cc_c89=$ac_arg
+fi
+rm -f core conftest.err conftest.$ac_objext
+  test "x$ac_cv_prog_cc_c89" != "xno" && break
+done
+rm -f conftest.$ac_ext
+CC=$ac_save_CC
+
+fi
+# AC_CACHE_VAL
+case "x$ac_cv_prog_cc_c89" in
+  x)
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5
+$as_echo "none needed" >&6; } ;;
+  xno)
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5
+$as_echo "unsupported" >&6; } ;;
+  *)
+    CC="$CC $ac_cv_prog_cc_c89"
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5
+$as_echo "$ac_cv_prog_cc_c89" >&6; } ;;
+esac
+if test "x$ac_cv_prog_cc_c89" != xno; then :
+
+fi
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts $MYCFLAGS0" >&5
+$as_echo_n "checking whether $CC accepts $MYCFLAGS0... " >&6; }
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+CFLAGS="$MYCFLAGS0 $RCFLAGS"
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+char b[10];
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  mycflags0_set=yes
+else
+  mycflags0_set=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mycflags0_set" >&5
+$as_echo "$mycflags0_set" >&6; }
+
+if test $mycflags0_set = no; then
+   PKG_CLFAGS=""
+else
+   PKG_CFLAGS=$MYCFLAGS0
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts $MYCFLAGS1" >&5
+$as_echo_n "checking whether $CC accepts $MYCFLAGS1... " >&6; }
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+CFLAGS="$MYCFLAGS1 $RCFLAGS -pedantic"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+char b[10];
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  mycflags1_set=yes
+else
+  mycflags1_set=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mycflags1_set" >&5
+$as_echo "$mycflags1_set" >&6; }
+
+if test $mycflags1_set = yes; then
+   PKG_CFLAGS="$PKG_CFLAGS $MYCFLAGS1"
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts $MYCFLAGS2" >&5
+$as_echo_n "checking whether $CC accepts $MYCFLAGS2... " >&6; }
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+CFLAGS="$MYCFLAGS2 $RCFLAGS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+char b[10];
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  mycflags2_set=yes
+else
+  mycflags2_set=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mycflags2_set" >&5
+$as_echo "$mycflags2_set" >&6; }
+
+if test $mycflags2_set = yes; then
+   PKG_CFLAGS="$PKG_CFLAGS $MYCFLAGS2"
+fi
+
+ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+if test -z "$CXX"; then
+  if test -n "$CCC"; then
+    CXX=$CCC
+  else
+    if test -n "$ac_tool_prefix"; then
+  for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC
+  do
+    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
+set dummy $ac_tool_prefix$ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CXX+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CXX"; then
+  ac_cv_prog_CXX="$CXX" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_CXX="$ac_tool_prefix$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+CXX=$ac_cv_prog_CXX
+if test -n "$CXX"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXX" >&5
+$as_echo "$CXX" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+    test -n "$CXX" && break
+  done
+fi
+if test -z "$CXX"; then
+  ac_ct_CXX=$CXX
+  for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_CXX+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_CXX"; then
+  ac_cv_prog_ac_ct_CXX="$ac_ct_CXX" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_CXX="$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_CXX=$ac_cv_prog_ac_ct_CXX
+if test -n "$ac_ct_CXX"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CXX" >&5
+$as_echo "$ac_ct_CXX" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$ac_ct_CXX" && break
+done
+
+  if test "x$ac_ct_CXX" = x; then
+    CXX="g++"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    CXX=$ac_ct_CXX
+  fi
+fi
+
+  fi
+fi
+# Provide some information about the compiler.
+$as_echo "$as_me:${as_lineno-$LINENO}: checking for C++ compiler version" >&5
+set X $ac_compile
+ac_compiler=$2
+for ac_option in --version -v -V -qversion; do
+  { { ac_try="$ac_compiler $ac_option >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_compiler $ac_option >&5") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    sed '10a\
+... rest of stderr output deleted ...
+         10q' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+  fi
+  rm -f conftest.er1 conftest.err
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+done
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C++ compiler" >&5
+$as_echo_n "checking whether we are using the GNU C++ compiler... " >&6; }
+if ${ac_cv_cxx_compiler_gnu+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+#ifndef __GNUC__
+       choke me
+#endif
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_cxx_try_compile "$LINENO"; then :
+  ac_compiler_gnu=yes
+else
+  ac_compiler_gnu=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ac_cv_cxx_compiler_gnu=$ac_compiler_gnu
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cxx_compiler_gnu" >&5
+$as_echo "$ac_cv_cxx_compiler_gnu" >&6; }
+if test $ac_compiler_gnu = yes; then
+  GXX=yes
+else
+  GXX=
+fi
+ac_test_CXXFLAGS=${CXXFLAGS+set}
+ac_save_CXXFLAGS=$CXXFLAGS
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CXX accepts -g" >&5
+$as_echo_n "checking whether $CXX accepts -g... " >&6; }
+if ${ac_cv_prog_cxx_g+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_save_cxx_werror_flag=$ac_cxx_werror_flag
+   ac_cxx_werror_flag=yes
+   ac_cv_prog_cxx_g=no
+   CXXFLAGS="-g"
+   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_cxx_try_compile "$LINENO"; then :
+  ac_cv_prog_cxx_g=yes
+else
+  CXXFLAGS=""
+      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_cxx_try_compile "$LINENO"; then :
+
+else
+  ac_cxx_werror_flag=$ac_save_cxx_werror_flag
+	 CXXFLAGS="-g"
+	 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_cxx_try_compile "$LINENO"; then :
+  ac_cv_prog_cxx_g=yes
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+   ac_cxx_werror_flag=$ac_save_cxx_werror_flag
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cxx_g" >&5
+$as_echo "$ac_cv_prog_cxx_g" >&6; }
+if test "$ac_test_CXXFLAGS" = set; then
+  CXXFLAGS=$ac_save_CXXFLAGS
+elif test $ac_cv_prog_cxx_g = yes; then
+  if test "$GXX" = yes; then
+    CXXFLAGS="-g -O2"
+  else
+    CXXFLAGS="-g"
+  fi
+else
+  if test "$GXX" = yes; then
+    CXXFLAGS="-O2"
+  else
+    CXXFLAGS=
+  fi
+fi
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CXX accepts $MYCXXFLAGS0" >&5
+$as_echo_n "checking whether $CXX accepts $MYCXXFLAGS0... " >&6; }
+ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+CXXFLAGS="$MYCXXFLAGS0 $RCXXFLAGS"
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <cmath>
+                    int main() {
+                      std::sqrt(5.1);
+                      return 0;
+                    }
+_ACEOF
+if ac_fn_cxx_try_compile "$LINENO"; then :
+  mycxxflags0_set=yes
+else
+  mycxxflags0_set=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mycxxflags0_set" >&5
+$as_echo "$mycxxflags0_set" >&6; }
+
+if test $mycxxflags0_set = no; then
+  PKG_CXXLFAGS=""
+else
+  PKG_CXXFLAGS=$MYCXXFLAGS0
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CXX accepts $MYCXXFLAGS1" >&5
+$as_echo_n "checking whether $CXX accepts $MYCXXFLAGS1... " >&6; }
+ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+CXXFLAGS="$MYCXXFLAGS1 $RCXXFLAGS -pedantic"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <cmath>
+                    int main() {
+                      std::sqrt(5.1);
+                      return 0;
+                    }
+_ACEOF
+if ac_fn_cxx_try_compile "$LINENO"; then :
+  mycxxflags1_set=yes
+else
+  mycxxflags1_set=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mycxxflags1_set" >&5
+$as_echo "$mycxxflags1_set" >&6; }
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CXX accepts $MYCXXFLAGS2" >&5
+$as_echo_n "checking whether $CXX accepts $MYCXXFLAGS2... " >&6; }
+ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+CXXFLAGS="$MYCXXFLAGS2 $RCXXFLAGS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <cmath>
+                    int main() {
+                      std::sqrt(5.1);
+                      return 0;
+                    }
+_ACEOF
+if ac_fn_cxx_try_compile "$LINENO"; then :
+  mycxxflags2_set=yes
+else
+  mycxxflags2_set=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mycxxflags2_set" >&5
+$as_echo "$mycxxflags2_set" >&6; }
+
+if test $mycxxflags1_set = yes; then
+   PKG_CXXFLAGS="$PKG_CXXFLAGS $MYCXXFLAGS1"
+fi
+
+if test $mycxxflags2_set = yes; then
+   PKG_CXXFLAGS="$PKG_CXXFLAGS $MYCXXFLAGS2"
+fi
+
+
+
+
+
+
+
+ac_config_files="$ac_config_files src/Makevars"
+
+cat >confcache <<\_ACEOF
+# This file is a shell script that caches the results of configure
+# tests run on this system so they can be shared between configure
+# scripts and configure runs, see configure's option --config-cache.
+# It is not useful on other systems.  If it contains results you don't
+# want to keep, you may remove or edit it.
+#
+# config.status only pays attention to the cache file if you give it
+# the --recheck option to rerun configure.
+#
+# `ac_cv_env_foo' variables (set or unset) will be overridden when
+# loading this file, other *unset* `ac_cv_foo' will be assigned the
+# following values.
+
+_ACEOF
+
+# The following way of writing the cache mishandles newlines in values,
+# but we know of no workaround that is simple, portable, and efficient.
+# So, we kill variables containing newlines.
+# Ultrix sh set writes to stderr and can't be redirected directly,
+# and sets the high bit in the cache file unless we assign to the vars.
+(
+  for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do
+    eval ac_val=\$$ac_var
+    case $ac_val in #(
+    *${as_nl}*)
+      case $ac_var in #(
+      *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
+$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
+      esac
+      case $ac_var in #(
+      _ | IFS | as_nl) ;; #(
+      BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #(
+      *) { eval $ac_var=; unset $ac_var;} ;;
+      esac ;;
+    esac
+  done
+
+  (set) 2>&1 |
+    case $as_nl`(ac_space=' '; set) 2>&1` in #(
+    *${as_nl}ac_space=\ *)
+      # `set' does not quote correctly, so add quotes: double-quote
+      # substitution turns \\\\ into \\, and sed turns \\ into \.
+      sed -n \
+	"s/'/'\\\\''/g;
+	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p"
+      ;; #(
+    *)
+      # `set' quotes correctly as required by POSIX, so do not add quotes.
+      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
+      ;;
+    esac |
+    sort
+) |
+  sed '
+     /^ac_cv_env_/b end
+     t clear
+     :clear
+     s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/
+     t end
+     s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/
+     :end' >>confcache
+if diff "$cache_file" confcache >/dev/null 2>&1; then :; else
+  if test -w "$cache_file"; then
+    if test "x$cache_file" != "x/dev/null"; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5
+$as_echo "$as_me: updating cache $cache_file" >&6;}
+      if test ! -f "$cache_file" || test -h "$cache_file"; then
+	cat confcache >"$cache_file"
+      else
+        case $cache_file in #(
+        */* | ?:*)
+	  mv -f confcache "$cache_file"$$ &&
+	  mv -f "$cache_file"$$ "$cache_file" ;; #(
+        *)
+	  mv -f confcache "$cache_file" ;;
+	esac
+      fi
+    fi
+  else
+    { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5
+$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;}
+  fi
+fi
+rm -f confcache
+
+test "x$prefix" = xNONE && prefix=$ac_default_prefix
+# Let make expand exec_prefix.
+test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'
+
+# Transform confdefs.h into DEFS.
+# Protect against shell expansion while executing Makefile rules.
+# Protect against Makefile macro expansion.
+#
+# If the first sed substitution is executed (which looks for macros that
+# take arguments), then branch to the quote section.  Otherwise,
+# look for a macro that doesn't take arguments.
+ac_script='
+:mline
+/\\$/{
+ N
+ s,\\\n,,
+ b mline
+}
+t clear
+:clear
+s/^[	 ]*#[	 ]*define[	 ][	 ]*\([^	 (][^	 (]*([^)]*)\)[	 ]*\(.*\)/-D\1=\2/g
+t quote
+s/^[	 ]*#[	 ]*define[	 ][	 ]*\([^	 ][^	 ]*\)[	 ]*\(.*\)/-D\1=\2/g
+t quote
+b any
+:quote
+s/[	 `~#$^&*(){}\\|;'\''"<>?]/\\&/g
+s/\[/\\&/g
+s/\]/\\&/g
+s/\$/$$/g
+H
+:any
+${
+	g
+	s/^\n//
+	s/\n/ /g
+	p
+}
+'
+DEFS=`sed -n "$ac_script" confdefs.h`
+
+
+ac_libobjs=
+ac_ltlibobjs=
+U=
+for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue
+  # 1. Remove the extension, and $U if already installed.
+  ac_script='s/\$U\././;s/\.o$//;s/\.obj$//'
+  ac_i=`$as_echo "$ac_i" | sed "$ac_script"`
+  # 2. Prepend LIBOBJDIR.  When used with automake>=1.10 LIBOBJDIR
+  #    will be set to the directory where LIBOBJS objects are built.
+  as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext"
+  as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo'
+done
+LIBOBJS=$ac_libobjs
+
+LTLIBOBJS=$ac_ltlibobjs
+
+
+
+: "${CONFIG_STATUS=./config.status}"
+ac_write_fail=0
+ac_clean_files_save=$ac_clean_files
+ac_clean_files="$ac_clean_files $CONFIG_STATUS"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5
+$as_echo "$as_me: creating $CONFIG_STATUS" >&6;}
+as_write_fail=0
+cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1
+#! $SHELL
+# Generated by $as_me.
+# Run this file to recreate the current configuration.
+# Compiler output produced by configure, useful for debugging
+# configure, is in config.log if it exists.
+
+debug=false
+ac_cs_recheck=false
+ac_cs_silent=false
+
+SHELL=\${CONFIG_SHELL-$SHELL}
+export SHELL
+_ASEOF
+cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1
+## -------------------- ##
+## M4sh Initialization. ##
+## -------------------- ##
+
+# Be more Bourne compatible
+DUALCASE=1; export DUALCASE # for MKS sh
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
+  emulate sh
+  NULLCMD=:
+  # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in #(
+  *posix*) :
+    set -o posix ;; #(
+  *) :
+     ;;
+esac
+fi
+
+
+as_nl='
+'
+export as_nl
+# Printing a long string crashes Solaris 7 /usr/bin/printf.
+as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
+as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
+# Prefer a ksh shell builtin over an external printf program on Solaris,
+# but without wasting forks for bash or zsh.
+if test -z "$BASH_VERSION$ZSH_VERSION" \
+    && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
+  as_echo='print -r --'
+  as_echo_n='print -rn --'
+elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
+  as_echo='printf %s\n'
+  as_echo_n='printf %s'
+else
+  if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
+    as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
+    as_echo_n='/usr/ucb/echo -n'
+  else
+    as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
+    as_echo_n_body='eval
+      arg=$1;
+      case $arg in #(
+      *"$as_nl"*)
+	expr "X$arg" : "X\\(.*\\)$as_nl";
+	arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
+      esac;
+      expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
+    '
+    export as_echo_n_body
+    as_echo_n='sh -c $as_echo_n_body as_echo'
+  fi
+  export as_echo_body
+  as_echo='sh -c $as_echo_body as_echo'
+fi
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+  PATH_SEPARATOR=:
+  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
+    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
+      PATH_SEPARATOR=';'
+  }
+fi
+
+
+# IFS
+# We need space, tab and new line, in precisely that order.  Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+IFS=" ""	$as_nl"
+
+# Find who we are.  Look in the path if we contain no directory separator.
+as_myself=
+case $0 in #((
+  *[\\/]* ) as_myself=$0 ;;
+  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+  done
+IFS=$as_save_IFS
+
+     ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" = x; then
+  as_myself=$0
+fi
+if test ! -f "$as_myself"; then
+  $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+  exit 1
+fi
+
+# Unset variables that we do not need and which cause bugs (e.g. in
+# pre-3.0 UWIN ksh).  But do not cause bugs in bash 2.01; the "|| exit 1"
+# suppresses any "Segmentation fault" message there.  '((' could
+# trigger a bug in pdksh 5.2.14.
+for as_var in BASH_ENV ENV MAIL MAILPATH
+do eval test x\${$as_var+set} = xset \
+  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
+done
+PS1='$ '
+PS2='> '
+PS4='+ '
+
+# NLS nuisances.
+LC_ALL=C
+export LC_ALL
+LANGUAGE=C
+export LANGUAGE
+
+# CDPATH.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+
+# as_fn_error STATUS ERROR [LINENO LOG_FD]
+# ----------------------------------------
+# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
+# provided, also output the error to LOG_FD, referencing LINENO. Then exit the
+# script with STATUS, using 1 if that was 0.
+as_fn_error ()
+{
+  as_status=$1; test $as_status -eq 0 && as_status=1
+  if test "$4"; then
+    as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+    $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
+  fi
+  $as_echo "$as_me: error: $2" >&2
+  as_fn_exit $as_status
+} # as_fn_error
+
+
+# as_fn_set_status STATUS
+# -----------------------
+# Set $? to STATUS, without forking.
+as_fn_set_status ()
+{
+  return $1
+} # as_fn_set_status
+
+# as_fn_exit STATUS
+# -----------------
+# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
+as_fn_exit ()
+{
+  set +e
+  as_fn_set_status $1
+  exit $1
+} # as_fn_exit
+
+# as_fn_unset VAR
+# ---------------
+# Portably unset VAR.
+as_fn_unset ()
+{
+  { eval $1=; unset $1;}
+}
+as_unset=as_fn_unset
+# as_fn_append VAR VALUE
+# ----------------------
+# Append the text in VALUE to the end of the definition contained in VAR. Take
+# advantage of any shell optimizations that allow amortized linear growth over
+# repeated appends, instead of the typical quadratic growth present in naive
+# implementations.
+if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
+  eval 'as_fn_append ()
+  {
+    eval $1+=\$2
+  }'
+else
+  as_fn_append ()
+  {
+    eval $1=\$$1\$2
+  }
+fi # as_fn_append
+
+# as_fn_arith ARG...
+# ------------------
+# Perform arithmetic evaluation on the ARGs, and store the result in the
+# global $as_val. Take advantage of shells that can avoid forks. The arguments
+# must be portable across $(()) and expr.
+if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
+  eval 'as_fn_arith ()
+  {
+    as_val=$(( $* ))
+  }'
+else
+  as_fn_arith ()
+  {
+    as_val=`expr "$@" || test $? -eq 1`
+  }
+fi # as_fn_arith
+
+
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
+  as_basename=basename
+else
+  as_basename=false
+fi
+
+if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
+  as_dirname=dirname
+else
+  as_dirname=false
+fi
+
+as_me=`$as_basename -- "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+	 X"$0" : 'X\(//\)$' \| \
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X/"$0" |
+    sed '/^.*\/\([^/][^/]*\)\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
+
+ECHO_C= ECHO_N= ECHO_T=
+case `echo -n x` in #(((((
+-n*)
+  case `echo 'xy\c'` in
+  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
+  xy)  ECHO_C='\c';;
+  *)   echo `echo ksh88 bug on AIX 6.1` > /dev/null
+       ECHO_T='	';;
+  esac;;
+*)
+  ECHO_N='-n';;
+esac
+
+rm -f conf$$ conf$$.exe conf$$.file
+if test -d conf$$.dir; then
+  rm -f conf$$.dir/conf$$.file
+else
+  rm -f conf$$.dir
+  mkdir conf$$.dir 2>/dev/null
+fi
+if (echo >conf$$.file) 2>/dev/null; then
+  if ln -s conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s='ln -s'
+    # ... but there are two gotchas:
+    # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+    # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
+    # In both cases, we have to default to `cp -p'.
+    ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+      as_ln_s='cp -p'
+  elif ln conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s=ln
+  else
+    as_ln_s='cp -p'
+  fi
+else
+  as_ln_s='cp -p'
+fi
+rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
+rmdir conf$$.dir 2>/dev/null
+
+
+# as_fn_mkdir_p
+# -------------
+# Create "$as_dir" as a directory, including parents if necessary.
+as_fn_mkdir_p ()
+{
+
+  case $as_dir in #(
+  -*) as_dir=./$as_dir;;
+  esac
+  test -d "$as_dir" || eval $as_mkdir_p || {
+    as_dirs=
+    while :; do
+      case $as_dir in #(
+      *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
+      *) as_qdir=$as_dir;;
+      esac
+      as_dirs="'$as_qdir' $as_dirs"
+      as_dir=`$as_dirname -- "$as_dir" ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_dir" : 'X\(//\)[^/]' \| \
+	 X"$as_dir" : 'X\(//\)$' \| \
+	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$as_dir" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+      test -d "$as_dir" && break
+    done
+    test -z "$as_dirs" || eval "mkdir $as_dirs"
+  } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir"
+
+
+} # as_fn_mkdir_p
+if mkdir -p . 2>/dev/null; then
+  as_mkdir_p='mkdir -p "$as_dir"'
+else
+  test -d ./-p && rmdir ./-p
+  as_mkdir_p=false
+fi
+
+if test -x / >/dev/null 2>&1; then
+  as_test_x='test -x'
+else
+  if ls -dL / >/dev/null 2>&1; then
+    as_ls_L_option=L
+  else
+    as_ls_L_option=
+  fi
+  as_test_x='
+    eval sh -c '\''
+      if test -d "$1"; then
+	test -d "$1/.";
+      else
+	case $1 in #(
+	-*)set "./$1";;
+	esac;
+	case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #((
+	???[sx]*):;;*)false;;esac;fi
+    '\'' sh
+  '
+fi
+as_executable_p=$as_test_x
+
+# Sed expression to map a string onto a valid CPP name.
+as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
+
+# Sed expression to map a string onto a valid variable name.
+as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
+
+
+exec 6>&1
+## ----------------------------------- ##
+## Main body of $CONFIG_STATUS script. ##
+## ----------------------------------- ##
+_ASEOF
+test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+# Save the log message, to keep $0 and so on meaningful, and to
+# report actual input values of CONFIG_FILES etc. instead of their
+# values after options handling.
+ac_log="
+This file was extended by Matching $as_me 4.0.8+, which was
+generated by GNU Autoconf 2.68.  Invocation command line was
+
+  CONFIG_FILES    = $CONFIG_FILES
+  CONFIG_HEADERS  = $CONFIG_HEADERS
+  CONFIG_LINKS    = $CONFIG_LINKS
+  CONFIG_COMMANDS = $CONFIG_COMMANDS
+  $ $0 $@
+
+on `(hostname || uname -n) 2>/dev/null | sed 1q`
+"
+
+_ACEOF
+
+case $ac_config_files in *"
+"*) set x $ac_config_files; shift; ac_config_files=$*;;
+esac
+
+
+
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+# Files that config.status was made for.
+config_files="$ac_config_files"
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+ac_cs_usage="\
+\`$as_me' instantiates files and other configuration actions
+from templates according to the current configuration.  Unless the files
+and actions are specified as TAGs, all are instantiated by default.
+
+Usage: $0 [OPTION]... [TAG]...
+
+  -h, --help       print this help, then exit
+  -V, --version    print version number and configuration settings, then exit
+      --config     print configuration, then exit
+  -q, --quiet, --silent
+                   do not print progress messages
+  -d, --debug      don't remove temporary files
+      --recheck    update $as_me by reconfiguring in the same conditions
+      --file=FILE[:TEMPLATE]
+                   instantiate the configuration file FILE
+
+Configuration files:
+$config_files
+
+Report bugs to <sekhon at berkeley.edu>."
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
+ac_cs_version="\\
+Matching config.status 4.0.8+
+configured by $0, generated by GNU Autoconf 2.68,
+  with options \\"\$ac_cs_config\\"
+
+Copyright (C) 2010 Free Software Foundation, Inc.
+This config.status script is free software; the Free Software Foundation
+gives unlimited permission to copy, distribute and modify it."
+
+ac_pwd='$ac_pwd'
+srcdir='$srcdir'
+test -n "\$AWK" || AWK=awk
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+# The default lists apply if the user does not specify any file.
+ac_need_defaults=:
+while test $# != 0
+do
+  case $1 in
+  --*=?*)
+    ac_option=`expr "X$1" : 'X\([^=]*\)='`
+    ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'`
+    ac_shift=:
+    ;;
+  --*=)
+    ac_option=`expr "X$1" : 'X\([^=]*\)='`
+    ac_optarg=
+    ac_shift=:
+    ;;
+  *)
+    ac_option=$1
+    ac_optarg=$2
+    ac_shift=shift
+    ;;
+  esac
+
+  case $ac_option in
+  # Handling of the options.
+  -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
+    ac_cs_recheck=: ;;
+  --version | --versio | --versi | --vers | --ver | --ve | --v | -V )
+    $as_echo "$ac_cs_version"; exit ;;
+  --config | --confi | --conf | --con | --co | --c )
+    $as_echo "$ac_cs_config"; exit ;;
+  --debug | --debu | --deb | --de | --d | -d )
+    debug=: ;;
+  --file | --fil | --fi | --f )
+    $ac_shift
+    case $ac_optarg in
+    *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
+    '') as_fn_error $? "missing file argument" ;;
+    esac
+    as_fn_append CONFIG_FILES " '$ac_optarg'"
+    ac_need_defaults=false;;
+  --he | --h |  --help | --hel | -h )
+    $as_echo "$ac_cs_usage"; exit ;;
+  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+  | -silent | --silent | --silen | --sile | --sil | --si | --s)
+    ac_cs_silent=: ;;
+
+  # This is an error.
+  -*) as_fn_error $? "unrecognized option: \`$1'
+Try \`$0 --help' for more information." ;;
+
+  *) as_fn_append ac_config_targets " $1"
+     ac_need_defaults=false ;;
+
+  esac
+  shift
+done
+
+ac_configure_extra_args=
+
+if $ac_cs_silent; then
+  exec 6>/dev/null
+  ac_configure_extra_args="$ac_configure_extra_args --silent"
+fi
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+if \$ac_cs_recheck; then
+  set X '$SHELL' '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
+  shift
+  \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6
+  CONFIG_SHELL='$SHELL'
+  export CONFIG_SHELL
+  exec "\$@"
+fi
+
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+exec 5>>config.log
+{
+  echo
+  sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
+## Running $as_me. ##
+_ASBOX
+  $as_echo "$ac_log"
+} >&5
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+
+# Handling of arguments.
+for ac_config_target in $ac_config_targets
+do
+  case $ac_config_target in
+    "src/Makevars") CONFIG_FILES="$CONFIG_FILES src/Makevars" ;;
+
+  *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;;
+  esac
+done
+
+
+# If the user did not use the arguments to specify the items to instantiate,
+# then the envvar interface is used.  Set only those that are not.
+# We use the long form for the default assignment because of an extremely
+# bizarre bug on SunOS 4.1.3.
+if $ac_need_defaults; then
+  test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files
+fi
+
+# Have a temporary directory for convenience.  Make it in the build tree
+# simply because there is no reason against having it here, and in addition,
+# creating and moving files from /tmp can sometimes cause problems.
+# Hook for its removal unless debugging.
+# Note that there is a small window in which the directory will not be cleaned:
+# after its creation but before its name has been assigned to `$tmp'.
+$debug ||
+{
+  tmp= ac_tmp=
+  trap 'exit_status=$?
+  : "${ac_tmp:=$tmp}"
+  { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status
+' 0
+  trap 'as_fn_exit 1' 1 2 13 15
+}
+# Create a (secure) tmp directory for tmp files.
+
+{
+  tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
+  test -d "$tmp"
+}  ||
+{
+  tmp=./conf$$-$RANDOM
+  (umask 077 && mkdir "$tmp")
+} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5
+ac_tmp=$tmp
+
+# Set up the scripts for CONFIG_FILES section.
+# No need to generate them if there are no CONFIG_FILES.
+# This happens for instance with `./config.status config.h'.
+if test -n "$CONFIG_FILES"; then
+
+
+ac_cr=`echo X | tr X '\015'`
+# On cygwin, bash can eat \r inside `` if the user requested igncr.
+# But we know of no other shell where ac_cr would be empty at this
+# point, so we can use a bashism as a fallback.
+if test "x$ac_cr" = x; then
+  eval ac_cr=\$\'\\r\'
+fi
+ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' </dev/null 2>/dev/null`
+if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then
+  ac_cs_awk_cr='\\r'
+else
+  ac_cs_awk_cr=$ac_cr
+fi
+
+echo 'BEGIN {' >"$ac_tmp/subs1.awk" &&
+_ACEOF
+
+
+{
+  echo "cat >conf$$subs.awk <<_ACEOF" &&
+  echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' &&
+  echo "_ACEOF"
+} >conf$$subs.sh ||
+  as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
+ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'`
+ac_delim='%!_!# '
+for ac_last_try in false false false false false :; do
+  . ./conf$$subs.sh ||
+    as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
+
+  ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X`
+  if test $ac_delim_n = $ac_delim_num; then
+    break
+  elif $ac_last_try; then
+    as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
+  else
+    ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
+  fi
+done
+rm -f conf$$subs.sh
+
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK &&
+_ACEOF
+sed -n '
+h
+s/^/S["/; s/!.*/"]=/
+p
+g
+s/^[^!]*!//
+:repl
+t repl
+s/'"$ac_delim"'$//
+t delim
+:nl
+h
+s/\(.\{148\}\)..*/\1/
+t more1
+s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/
+p
+n
+b repl
+:more1
+s/["\\]/\\&/g; s/^/"/; s/$/"\\/
+p
+g
+s/.\{148\}//
+t nl
+:delim
+h
+s/\(.\{148\}\)..*/\1/
+t more2
+s/["\\]/\\&/g; s/^/"/; s/$/"/
+p
+b
+:more2
+s/["\\]/\\&/g; s/^/"/; s/$/"\\/
+p
+g
+s/.\{148\}//
+t delim
+' <conf$$subs.awk | sed '
+/^[^""]/{
+  N
+  s/\n//
+}
+' >>$CONFIG_STATUS || ac_write_fail=1
+rm -f conf$$subs.awk
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+_ACAWK
+cat >>"\$ac_tmp/subs1.awk" <<_ACAWK &&
+  for (key in S) S_is_set[key] = 1
+  FS = ""
+
+}
+{
+  line = $ 0
+  nfields = split(line, field, "@")
+  substed = 0
+  len = length(field[1])
+  for (i = 2; i < nfields; i++) {
+    key = field[i]
+    keylen = length(key)
+    if (S_is_set[key]) {
+      value = S[key]
+      line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3)
+      len += length(value) + length(field[++i])
+      substed = 1
+    } else
+      len += 1 + keylen
+  }
+
+  print line
+}
+
+_ACAWK
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then
+  sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g"
+else
+  cat
+fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \
+  || as_fn_error $? "could not setup config files machinery" "$LINENO" 5
+_ACEOF
+
+# VPATH may cause trouble with some makes, so we remove sole $(srcdir),
+# ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and
+# trailing colons and then remove the whole line if VPATH becomes empty
+# (actually we leave an empty line to preserve line numbers).
+if test "x$srcdir" = x.; then
+  ac_vpsub='/^[	 ]*VPATH[	 ]*=[	 ]*/{
+h
+s///
+s/^/:/
+s/[	 ]*$/:/
+s/:\$(srcdir):/:/g
+s/:\${srcdir}:/:/g
+s/:@srcdir@:/:/g
+s/^:*//
+s/:*$//
+x
+s/\(=[	 ]*\).*/\1/
+G
+s/\n//
+s/^[^=]*=[	 ]*$//
+}'
+fi
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+fi # test -n "$CONFIG_FILES"
+
+
+eval set X "  :F $CONFIG_FILES      "
+shift
+for ac_tag
+do
+  case $ac_tag in
+  :[FHLC]) ac_mode=$ac_tag; continue;;
+  esac
+  case $ac_mode$ac_tag in
+  :[FHL]*:*);;
+  :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;;
+  :[FH]-) ac_tag=-:-;;
+  :[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
+  esac
+  ac_save_IFS=$IFS
+  IFS=:
+  set x $ac_tag
+  IFS=$ac_save_IFS
+  shift
+  ac_file=$1
+  shift
+
+  case $ac_mode in
+  :L) ac_source=$1;;
+  :[FH])
+    ac_file_inputs=
+    for ac_f
+    do
+      case $ac_f in
+      -) ac_f="$ac_tmp/stdin";;
+      *) # Look for the file first in the build tree, then in the source tree
+	 # (if the path is not absolute).  The absolute path cannot be DOS-style,
+	 # because $ac_f cannot contain `:'.
+	 test -f "$ac_f" ||
+	   case $ac_f in
+	   [\\/$]*) false;;
+	   *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
+	   esac ||
+	   as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;;
+      esac
+      case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac
+      as_fn_append ac_file_inputs " '$ac_f'"
+    done
+
+    # Let's still pretend it is `configure' which instantiates (i.e., don't
+    # use $as_me), people would be surprised to read:
+    #    /* config.h.  Generated by config.status.  */
+    configure_input='Generated from '`
+	  $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g'
+	`' by configure.'
+    if test x"$ac_file" != x-; then
+      configure_input="$ac_file.  $configure_input"
+      { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5
+$as_echo "$as_me: creating $ac_file" >&6;}
+    fi
+    # Neutralize special characters interpreted by sed in replacement strings.
+    case $configure_input in #(
+    *\&* | *\|* | *\\* )
+       ac_sed_conf_input=`$as_echo "$configure_input" |
+       sed 's/[\\\\&|]/\\\\&/g'`;; #(
+    *) ac_sed_conf_input=$configure_input;;
+    esac
+
+    case $ac_tag in
+    *:-:* | *:-) cat >"$ac_tmp/stdin" \
+      || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;;
+    esac
+    ;;
+  esac
+
+  ac_dir=`$as_dirname -- "$ac_file" ||
+$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$ac_file" : 'X\(//\)[^/]' \| \
+	 X"$ac_file" : 'X\(//\)$' \| \
+	 X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$ac_file" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+  as_dir="$ac_dir"; as_fn_mkdir_p
+  ac_builddir=.
+
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+  ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
+
+case $srcdir in
+  .)  # We are building in place.
+    ac_srcdir=.
+    ac_top_srcdir=$ac_top_builddir_sub
+    ac_abs_top_srcdir=$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
+    ac_srcdir=$srcdir$ac_dir_suffix;
+    ac_top_srcdir=$srcdir
+    ac_abs_top_srcdir=$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+
+  case $ac_mode in
+  :F)
+  #
+  # CONFIG_FILE
+  #
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+# If the template does not know about datarootdir, expand it.
+# FIXME: This hack should be removed a few years after 2.60.
+ac_datarootdir_hack=; ac_datarootdir_seen=
+ac_sed_dataroot='
+/datarootdir/ {
+  p
+  q
+}
+/@datadir@/p
+/@docdir@/p
+/@infodir@/p
+/@localedir@/p
+/@mandir@/p'
+case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in
+*datarootdir*) ac_datarootdir_seen=yes;;
+*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)
+  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5
+$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+  ac_datarootdir_hack='
+  s&@datadir@&$datadir&g
+  s&@docdir@&$docdir&g
+  s&@infodir@&$infodir&g
+  s&@localedir@&$localedir&g
+  s&@mandir@&$mandir&g
+  s&\\\${datarootdir}&$datarootdir&g' ;;
+esac
+_ACEOF
+
+# Neutralize VPATH when `$srcdir' = `.'.
+# Shell code in configure.ac might set extrasub.
+# FIXME: do we really want to maintain this feature?
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+ac_sed_extra="$ac_vpsub
+$extrasub
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+:t
+/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
+s|@configure_input@|$ac_sed_conf_input|;t t
+s&@top_builddir@&$ac_top_builddir_sub&;t t
+s&@top_build_prefix@&$ac_top_build_prefix&;t t
+s&@srcdir@&$ac_srcdir&;t t
+s&@abs_srcdir@&$ac_abs_srcdir&;t t
+s&@top_srcdir@&$ac_top_srcdir&;t t
+s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t
+s&@builddir@&$ac_builddir&;t t
+s&@abs_builddir@&$ac_abs_builddir&;t t
+s&@abs_top_builddir@&$ac_abs_top_builddir&;t t
+$ac_datarootdir_hack
+"
+eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \
+  >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5
+
+test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
+  { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } &&
+  { ac_out=`sed -n '/^[	 ]*datarootdir[	 ]*:*=/p' \
+      "$ac_tmp/out"`; test -z "$ac_out"; } &&
+  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined.  Please make sure it is defined" >&5
+$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined.  Please make sure it is defined" >&2;}
+
+  rm -f "$ac_tmp/stdin"
+  case $ac_file in
+  -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";;
+  *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";;
+  esac \
+  || as_fn_error $? "could not create $ac_file" "$LINENO" 5
+ ;;
+
+
+
+  esac
+
+done # for ac_tag
+
+
+as_fn_exit 0
+_ACEOF
+ac_clean_files=$ac_clean_files_save
+
+test $ac_write_fail = 0 ||
+  as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5
+
+
+# configure is writing to config.log, and then calls config.status.
+# config.status does its own redirection, appending to config.log.
+# Unfortunately, on DOS this fails, as config.log is still kept open
+# by configure, so config.status won't be able to write to it; its
+# output is simply discarded.  So we exec the FD to /dev/null,
+# effectively closing config.log, so it can be properly (re)opened and
+# appended to by config.status.  When coming back to configure, we
+# need to make the FD available again.
+if test "$no_create" != yes; then
+  ac_cs_success=:
+  ac_config_status_args=
+  test "$silent" = yes &&
+    ac_config_status_args="$ac_config_status_args --quiet"
+  exec 5>/dev/null
+  $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false
+  exec 5>>config.log
+  # Use ||, not &&, to avoid exiting from the if with $? = 1, which
+  # would make configure fail if this is the last instruction.
+  $ac_cs_success || as_fn_exit 1
+fi
+if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5
+$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;}
+fi
+
+
diff --git a/configure.ac b/configure.ac
new file mode 100644
index 0000000..b108f58
--- /dev/null
+++ b/configure.ac
@@ -0,0 +1,195 @@
+dnl Jasjeet S. Sekhon <sekhon at berkeley.edu> http://sekhon.berkeley.edu
+dnl Current version: 2013-10-28
+dnl First version: 2006-09-17
+dnl Process this file with autoconf to produce a configure script.
+dnl autoconf configure.ac > configure
+
+dnl TODO: optimize options for clang, e.g, -O4
+
+dnl Note: to manually switch the compiler and link options one can use
+dnl MAKEFLAGS="CC=icc" R CMD SHLIB *.c* amongst other ways.  This 
+dnl script handles gcc well.  For the Intel compilers see makefile.icc
+dnl in the "extras" directory, and for Sun Studio 12 see makefile.sun.
+dnl Modify these makefiles for your environment.
+
+dnl Matching Version 4.8-0+ we now check out flags along with
+dnl RC(XX)FLAGS. Ripley noted an issue with -ffast-math and Fedora 16:
+dnl -ffast-math and -pedantic (which is an option that R adds) are
+dnl incompatible in that OS. Update this script to also check use with RCXXFLAGS
+dnl and test script updated with #include <cmath>.
+
+dnl Matching Version 3.6-0+ we switched to configure.ac instead of the
+dnl configure hack.
+
+dnl Matching Version 4.8-2: -ffriend-injection is no longer supported in recent versions of gcc
+dnl Matching Version 3.4.4+: we need to add the -ffriend-injection
+dnl argument for g++ versions 4.1+ because ARM-style name-injection of
+dnl friend declarations is no longer the default.  We check for the
+dnl flag directly instead of relying on gcc --version information because of 
+dnl backporting issues---e.g., Gentoo.
+
+dnl We also setup optimization flags.  This significantly improves performance.
+
+dnl On Windows configure does *not* need to be run.  On Windows,
+dnl Makevars.win should simply be used because we can assume that we are
+dnl using the mingw32 compiler
+
+dnl -fstrict-aliasing -freorder-blocks -fsched-interblock is added for OS X 
+dnl Already included in the Linux gcc -O2 option, but does no harm on Linux
+
+AC_INIT(Matching, 4.0.8+, sekhon at berkeley.edu)
+
+dnl Find the compilers to use
+: ${R_HOME=`R RHOME`}
+if test -z "${R_HOME}"; then
+  echo "could not determine R_HOME"
+  exit 1
+fi
+CC=`"${R_HOME}/bin/R" CMD config CC`
+CXX=`"${R_HOME}/bin/R" CMD config CXX`
+RCFLAGS=`"${R_HOME}/bin/R" CMD config CFLAGS`
+RCXXFLAGS=`"${R_HOME}/bin/R" CMD config CXXFLAGS`
+
+dnl MYCFLAGS0 should work on most compilers and MYCFLAGS1 should work on most GNU C compilers.  
+dnl MYCFLAGS2 may not (generally needs gcc 4.0+).   The last three options in MYCFLAGS2 are the OS X 
+dnl addons referenced above.
+
+MYCFLAGS0="-O3"
+MYCFLAGS1="-finline-functions -funroll-loops -fexpensive-optimizations"
+MYCFLAGS2="-funswitch-loops -fgcse-after-reload -fstrict-aliasing -freorder-blocks -fsched-interblock"
+
+dnl -funsafe-loop-optimizations for gcc 4.2+; the following doesn't work any better in any case
+dnl MYCFLAGS2="-funswitch-loops -fgcse-after-reload -fstrict-aliasing -freorder-blocks -fsched-interblock -mfpmath=sse,387 -fgcse -fgcse-after-reload -fgcse-lm -fgcse-sm -fsched-spec-load-dangerous -funsafe-loop-optimizations"
+
+
+
+MYCXXFLAGS0="-O3"
+MYCXXFLAGS1="-finline-functions -funroll-loops -fexpensive-optimizations"
+MYCXXFLAGS2="-funswitch-loops -fgcse-after-reload -fstrict-aliasing -freorder-blocks -fsched-interblock"
+
+dnl -funsafe-loop-optimizations for gcc 4.2+; the following doesn't work any better in any case
+dnl MYCXXFLAGS2="-funswitch-loops -fgcse-after-reload -fstrict-aliasing -freorder-blocks -fsched-interblock -mfpmath=sse,387 -fgcse -fgcse-after-reload -fgcse-lm -fgcse-sm -fsched-spec-load-dangerous -funsafe-loop-optimizations"
+
+
+AC_PROG_CC
+
+AC_MSG_CHECKING([whether $CC accepts $MYCFLAGS0])
+AC_LANG([C])
+CFLAGS="$MYCFLAGS0 $RCFLAGS"
+AC_COMPILE_IFELSE([AC_LANG_SOURCE([[char b[10];]])], [mycflags0_set=yes], [mycflags0_set=no])    
+
+dnl AC_COMPILE_IFELSE([[char b[10];]], [], [AC_MSG_ERROR([you lose])])
+dnl AC_COMPILE_IFELSE([AC_LANG_SOURCE([[char b[10];]])], [], [AC_MSG_ERROR([you lose])])
+
+AC_MSG_RESULT($mycflags0_set)    
+
+if test $mycflags0_set = no; then    
+   PKG_CLFAGS=""
+else
+   PKG_CFLAGS=$MYCFLAGS0
+fi
+
+AC_MSG_CHECKING([whether $CC accepts $MYCFLAGS1])
+AC_LANG([C])
+CFLAGS="$MYCFLAGS1 $RCFLAGS -pedantic"
+AC_COMPILE_IFELSE([AC_LANG_SOURCE([[char b[10];]])], [mycflags1_set=yes], [mycflags1_set=no])    
+AC_MSG_RESULT($mycflags1_set)    
+
+if test $mycflags1_set = yes; then    
+   PKG_CFLAGS="$PKG_CFLAGS $MYCFLAGS1"
+fi
+
+AC_MSG_CHECKING([whether $CC accepts $MYCFLAGS2])
+AC_LANG([C])
+CFLAGS="$MYCFLAGS2 $RCFLAGS"
+AC_COMPILE_IFELSE([AC_LANG_SOURCE([[char b[10];]])], [mycflags2_set=yes], [mycflags2_set=no])    
+AC_MSG_RESULT($mycflags2_set)    
+
+if test $mycflags2_set = yes; then    
+   PKG_CFLAGS="$PKG_CFLAGS $MYCFLAGS2"
+fi
+
+AC_PROG_CXX
+
+dnl if test $GXX = no; then
+dnl    AC_MSG_WARN([**** GNU g++ IS HIGHLY RECOMMENDED.  I will continue, but this may not work. ****])
+dnl fi
+
+AC_MSG_CHECKING([whether $CXX accepts $MYCXXFLAGS0])
+AC_LANG([C++])
+CXXFLAGS="$MYCXXFLAGS0 $RCXXFLAGS"
+AC_COMPILE_IFELSE([AC_LANG_SOURCE([[#include <cmath>
+                    int main() {
+                      std::sqrt(5.1);
+                      return 0;
+                    }]])], [mycxxflags0_set=yes], [mycxxflags0_set=no])    
+AC_MSG_RESULT($mycxxflags0_set)    
+
+if test $mycxxflags0_set = no; then    
+  PKG_CXXLFAGS=""
+else
+  PKG_CXXFLAGS=$MYCXXFLAGS0
+fi
+
+AC_MSG_CHECKING([whether $CXX accepts $MYCXXFLAGS1])
+AC_LANG([C++])
+CXXFLAGS="$MYCXXFLAGS1 $RCXXFLAGS -pedantic"
+AC_COMPILE_IFELSE([AC_LANG_SOURCE([[#include <cmath>
+                    int main() {
+                      std::sqrt(5.1);
+                      return 0;
+                    }]])], [mycxxflags1_set=yes], [mycxxflags1_set=no])    
+AC_MSG_RESULT($mycxxflags1_set)    
+
+AC_MSG_CHECKING([whether $CXX accepts $MYCXXFLAGS2])
+AC_LANG([C++])
+CXXFLAGS="$MYCXXFLAGS2 $RCXXFLAGS"
+AC_COMPILE_IFELSE([AC_LANG_SOURCE([[#include <cmath>
+                    int main() {
+                      std::sqrt(5.1);
+                      return 0;
+                    }]])], [mycxxflags2_set=yes], [mycxxflags2_set=no])    
+AC_MSG_RESULT($mycxxflags2_set)    
+
+if test $mycxxflags1_set = yes; then    
+   PKG_CXXFLAGS="$PKG_CXXFLAGS $MYCXXFLAGS1"
+fi
+
+if test $mycxxflags2_set = yes; then    
+   PKG_CXXFLAGS="$PKG_CXXFLAGS $MYCXXFLAGS2"
+fi
+
+dnl -ffrend-injection is no longer supported
+dnl AC_MSG_CHECKING([whether $CXX accepts -ffriend-injection])
+dnl AC_LANG([C++])
+dnl CXXFLAGS="-ffriend-injection $RCXXFLAGS"
+dnl AC_COMPILE_IFELSE([[char b[10];]], [ffriend_set=yes], [ffriend_set=no])
+dnl AC_MSG_RESULT($ffriend_set)
+
+dnl if test $ffriend_set = yes; then    
+dnl    PKG_CXXFLAGS="$PKG_CXXFLAGS -ffriend-injection"
+dnl fi
+
+dnl Are we on OSX?
+dnl OS X specific modifications are no longer needed: Oct 28, 2013
+dnl If so: use dmalloc (NO LONGER DONE) and don't compile our own cblas headers (still done).
+dnl AC_MSG_CHECKING([whether we are on Darwin])
+dnl UNAME=`uname -a`
+dnl echo $UNAME | grep -i Darwin > /dev/null 2>&1
+dnl if test "$?" = 0 ; then
+dnl  AC_MSG_RESULT(yes)
+dnl cp inst/extras/malloc.c src/malloc.c
+dnl  mv src/cblas_dgemm.c inst/extras
+dnl  mv src/cblas.h inst/extras
+dnl  mv src/cblas_dasum.c inst/extras
+dnl  mv src/cblas_dscal.c inst/extras
+dnl else
+dnl  AC_MSG_RESULT(no)
+dnl fi
+
+AC_SUBST(PKG_CFLAGS)
+AC_SUBST(PKG_CXXFLAGS)
+
+AC_CONFIG_FILES([src/Makevars])
+AC_OUTPUT
+
diff --git a/data/GerberGreenImai.rda b/data/GerberGreenImai.rda
new file mode 100644
index 0000000..a2e9f8c
Binary files /dev/null and b/data/GerberGreenImai.rda differ
diff --git a/data/lalonde.rda b/data/lalonde.rda
new file mode 100644
index 0000000..8efa1e5
Binary files /dev/null and b/data/lalonde.rda differ
diff --git a/demo/00Index b/demo/00Index
new file mode 100644
index 0000000..4cdee39
--- /dev/null
+++ b/demo/00Index
@@ -0,0 +1,6 @@
+AbadieImbens            Replication of Guido Imbens 'lalonde_exper_04feb2.m' file
+                        http://elsa.berkeley.edu/~imbens/estimators.shtml
+
+DehejiaWahba            Replication of Dehejia and Wahba (1999)
+
+GerberGreenImai         Matching model for estimating the causal effect of get-out-the-vote telephone calls on turnout
diff --git a/demo/AbadieImbens.R b/demo/AbadieImbens.R
new file mode 100644
index 0000000..1c07d35
--- /dev/null
+++ b/demo/AbadieImbens.R
@@ -0,0 +1,118 @@
+# Replication of Guido Imbens lalonde_exper_04feb2.m file
+# See http://elsa.berkeley.edu/~imbens/estimators.shtml
+#
+# Note that the implications of the 'exact' options differ between the
+# two programs
+
+data(lalonde)
+
+X  <- lalonde$age
+Z  <- X;             
+V  <- lalonde$educ;
+Y  <- lalonde$re78/1000;
+T  <- lalonde$treat;
+w.educ=exp((lalonde$educ-10.1)/2);
+
+res  <- matrix(nrow=1,ncol=3)
+
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=1,Var.calc=0,
+             sample=TRUE);
+summary(rr)
+
+res[1,]  <- cbind(1,rr$est,rr$se)
+
+
+X  <- cbind(lalonde$age, lalonde$educ, lalonde$re74, lalonde$re75)
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=1,Var.calc=0,
+             sample=TRUE);
+summary(rr)
+
+res  <- rbind(res,cbind(2,rr$est,rr$se))
+
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=3,BiasAdj=FALSE,Weight=1,Var.calc=0,
+             sample=TRUE);
+summary(rr)
+res  <- rbind(res,cbind(4,rr$est,rr$se))
+
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATT",M=1,BiasAdj=FALSE,Weight=1,Var.calc=0,
+             sample=TRUE);
+summary(rr)
+res  <- rbind(res,cbind(5,rr$est,rr$se))
+
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATC",M=1,BiasAdj=FALSE,Weight=1,Var.calc=0,
+             sample=TRUE);
+summary(rr)
+res  <- rbind(res,cbind(6,rr$est,rr$se))
+
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=2,Var.calc=0,
+             sample=TRUE);
+summary(rr)
+res  <- rbind(res,cbind(7,rr$est,rr$se))
+
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=3,Var.calc=0,
+             Weight.matrix=diag(4), sample=TRUE);
+summary(rr)
+res  <- rbind(res,cbind(8,rr$est,rr$se))
+
+
+rr  <- Match(Y=Y,Tr=T,X=X,Z=X,V=V,estimand="ATE",M=1,BiasAdj=TRUE,Weight=1,Var.calc=0,
+             sample=TRUE);
+summary(rr)
+res  <- rbind(res,cbind(9,rr$est,rr$se))
+
+Z  <- cbind(lalonde$married, lalonde$age)
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=TRUE,Weight=1,Var.calc=0,sample=TRUE);
+summary(rr)
+res  <- rbind(res,cbind(10,rr$est,rr$se))
+
+V  <- lalonde$age
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=1,Var.calc=0,exact=TRUE,
+             sample=TRUE);
+summary(rr)
+res  <- rbind(res,cbind(11,rr$est,rr$se))
+
+V  <- cbind(lalonde$married, lalonde$u74)
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=1,Var.calc=0,exact=TRUE,
+             sample=TRUE);
+summary(rr)
+res  <- rbind(res,cbind(12,rr$est,rr$se))
+
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=1,Var.calc=0,sample=FALSE);
+summary(rr)
+res  <- rbind(res,cbind(13,rr$est,rr$se))
+
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=1,Var.calc=3,sample=TRUE);
+summary(rr)
+res  <- rbind(res,cbind(14,rr$est,rr$se))
+
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=1,Var.calc=0,
+             weights=w.educ,sample=TRUE);
+summary(rr)
+res  <- rbind(res,cbind(15,rr$est,rr$se))
+
+
+V  <- lalonde$age
+Z  <- cbind(lalonde$married, lalonde$age)
+X  <- cbind(lalonde$age, lalonde$educ, lalonde$re74, lalonde$re75)
+weight  <- w.educ
+Weight.matrix  <- diag(4)
+
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,
+             sample=FALSE, M=3, estimand="ATT", BiasAdj=TRUE, Weight=3, exact=TRUE,Var.calc=3,
+             weights=w.educ, Weight.matrix=Weight.matrix);
+summary(rr)
+res  <- rbind(res,cbind(75,rr$est,rr$se))
+
+
+V  <- lalonde$married;
+Z  <- cbind(lalonde$age, lalonde$re75);
+X  <- cbind(lalonde$age, lalonde$educ, lalonde$re74);
+
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,
+             sample=TRUE, M=3, estimand="ATE", BiasAdj=TRUE, Weight=2, exact=TRUE,Var.calc=0,
+             weights=w.educ);
+summary(rr)
+res  <- rbind(res,cbind(76,rr$est,rr$se))
+
+cat("\nResults:\n")
+print(res)
diff --git a/demo/DehejiaWahba.R b/demo/DehejiaWahba.R
new file mode 100644
index 0000000..bb75b83
--- /dev/null
+++ b/demo/DehejiaWahba.R
@@ -0,0 +1,37 @@
+# Replication of Dehejia and Wahba psid3 model.  
+
+# Dehejia, Rajeev and Sadek Wahba. 1999.``Causal Effects in
+# Non-Experimental Studies: Re-Evaluating the # Evaluation of Training
+# Programs.''Journal of the American Statistical Association 94 (448):
+# 1053-1062.  
+
+set.seed(10391)
+data(lalonde)
+
+#
+# Estimate the propensity model
+#
+glm1  <- glm(treat~age + I(age^2) + educ + I(educ^2) + black +
+             hisp + married + nodegr + re74  + I(re74^2) + re75 + I(re75^2) +
+             u74 + u75, family=binomial, data=lalonde)
+
+#
+#save data objects
+#
+X  <- glm1$fitted
+Y  <- lalonde$re78
+Tr  <- lalonde$treat
+
+#
+# one-to-one matching with replacement (the "M=1" option).
+# Estimating the treatment effect on the treated (the "estimand" option which defaults ATT).
+#
+rr  <- Match(Y=Y,Tr=Tr,X=X,M=1);
+summary(rr)
+
+#
+# Let's check for balance
+#
+mb  <- MatchBalance(treat~age + I(age^2) + educ + I(educ^2) + black +
+                    hisp + married + nodegr + re74  + I(re74^2) + re75 + I(re75^2) +
+                    u74 + u75, data=lalonde, match.out=rr, nboots=100)
diff --git a/demo/GerberGreenImai.R b/demo/GerberGreenImai.R
new file mode 100644
index 0000000..cc3e786
--- /dev/null
+++ b/demo/GerberGreenImai.R
@@ -0,0 +1,31 @@
+#
+# Gerber, Alan S. and Donald P. Green. 2000. "The Effects of Canvassing, Telephone Calls, and
+# Direct Mail on Voter Turnout: A Field Experiment." American Political Science Review 94: 653-663.
+#
+# Imai, Kosuke. 2005. "Do Get-Out-The-Vote Calls Reduce Turnout? The Importance of 
+# Statistical Methods for Field Experiments".  American Political Science Review 99: 283-300.
+#
+
+set.seed(10391)
+data(GerberGreenImai)
+
+#replication of Imai's propensity score matching model
+pscore.glm<-glm(PHN.C1 ~ PERSONS + VOTE96.1 + NEW + MAJORPTY + AGE +
+                WARD + PERSONS:VOTE96.1 + PERSONS:NEW + AGE2, 
+                family=binomial(logit), data=GerberGreenImai)
+
+D<-GerberGreenImai$PHN.C1 #treatment phone calls
+Y<-GerberGreenImai$VOTED98 #outcome, turnout
+
+cat("\nTHIS MODEL FAILS TO BALANCE AGE\n")
+X  <- fitted(pscore.glm)
+
+#propensity score matching estimator
+r1  <- Match(Y=Y, Tr=D, X=X, M=3)
+summary(r1)
+
+#check for balance before and after matching
+mb1  <- MatchBalance(PHN.C1 ~ AGE + AGE2 + PERSONS + VOTE96.1 + NEW + MAJORPTY +
+                     WARD + I(PERSONS*VOTE96.1) + I(PERSONS*NEW), match.out=r1,
+                     data=GerberGreenImai)
+
diff --git a/inst/CITATION b/inst/CITATION
new file mode 100644
index 0000000..4437c4c
--- /dev/null
+++ b/inst/CITATION
@@ -0,0 +1,55 @@
+citHeader("To cite 'Matching' in publications use:")
+
+citEntry(
+  entry = "Article",
+  title        = "Multivariate and Propensity Score Matching Software with Automated Balance Optimization: The {Matching} Package for {R}",
+  author       = personList(as.person("Jasjeet S. Sekhon")),
+  journal      = "Journal of Statistical Software",
+  year         = "2011",
+  volume       = "42",
+  number       = "7",
+  pages        = "1--52",
+  url          = "http://www.jstatsoft.org/v42/i07/",
+
+  textVersion  =
+  paste("Jasjeet S. Sekhon (2011).",
+        "Multivariate and Propensity Score Matching Software with Automated Balance Optimization: The Matching Package for R.",
+        "Journal of Statistical Software, 42(7), 1-52.",
+        "URL http://www.jstatsoft.org/v42/i07/.")
+)
+
+citEntry(header="To refer to the theory on which this package is based:",
+  entry="Article",
+  title = "Genetic Matching for Estimating Causal Effects: A General Multivariate Matching Method for Achieving Balance in Observational Studies",
+  author  = personList(as.person("Alexis Diamond"),as.person("Jasjeet S. Sekhon")),
+  journal = "Review of Economics and Statistics",
+  volume = "95",
+  number = "3",
+  pages = "932--945",
+  year = "2013",
+  url  = "http://sekhon.berkeley.edu/papers/GenMatch.pdf", 
+
+  textVersion  =
+  paste("Alexis Diamond and Jasjeet S. Sekhon",
+        "Genetic Matching for Estimating Causal Effects: A General Multivariate Matching Method for Achieving Balance in Observational Studies.",
+        "Review of Economics and Statistics. 95 (3): 932--945. 2013.")
+)
+
+citEntry(header="Further developing the theory and practice:",
+  entry="Article",
+  title = "A Matching Method For Improving Covariate Balance in Cost-Effectiveness Analyses",
+  author = personList(as.person("Jasjeet Singh Sekhon"),as.person("Richard D. Grieve")),
+  journal      = "Health Economics",
+  volume = "21",
+  number = "6",
+  pages= "695--714",
+  year = "2012",
+
+  textVersion  =
+  paste("Jasjeet Singh Sekhon and Richard D. Grieve (2012).", 
+    "A Matching Method For Improving Covariate Balance in Cost-Effectiveness Analyses.",
+    "Health Economics, 21(6), 695-714."
+    )
+)
+
+citFooter("BibTeX entries for LaTeX users: use\n", sQuote('toBibtex(citation("Matching"))'))
diff --git a/inst/extras/ICC b/inst/extras/ICC
new file mode 100755
index 0000000..0f0d269
--- /dev/null
+++ b/inst/extras/ICC
@@ -0,0 +1,6 @@
+icc -I/usr/local/lib64/R/include -I/usr/local/lib64/R/include  -I/usr/local/include  -fast -O3 -align -fpic -c cblas_dgemm.c -o cblas_dgemm.o
+icc -I/usr/local/lib64/R/include -I/usr/local/lib64/R/include -I/usr/local/include -fast -O3 -align -fpic -c matching.cc -o matching.o
+icc -I/usr/local/lib64/R/include -I/usr/local/lib64/R/include -I/usr/local/include -fast -O3 -align -fpic -c scythematrix.cc -o scythematrix.o
+icc -shared -lstdc++ -L/usr/local/lib64 -o Matching.so cblas_dgemm.o matching.o scythematrix.o
+
+
diff --git a/inst/extras/Makevars.win.gcc3 b/inst/extras/Makevars.win.gcc3
new file mode 100644
index 0000000..7e40f10
--- /dev/null
+++ b/inst/extras/Makevars.win.gcc3
@@ -0,0 +1,3 @@
+PKG_CFLAGS = -finline-func -fweb -funit-at-a-time -ftracer -funswitch-loops -frename-registers -ffast-math -funroll-loops -fexpensive-optimizations 
+PKG_CXXFLAGS = -finline-func -fweb -funit-at-a-time -ftracer -funswitch-loops -frename-registers -ffast-math -funroll-loops -fexpensive-optimizations 
+PKG_LIBS = -lRblas
diff --git a/inst/extras/Makevars.win.gcc4 b/inst/extras/Makevars.win.gcc4
new file mode 100644
index 0000000..02dd31a
--- /dev/null
+++ b/inst/extras/Makevars.win.gcc4
@@ -0,0 +1,3 @@
+PKG_CFLAGS = -O3 -finline-functions -funswitch-loops -fgcse-after-reload -funroll-loops 
+PKG_CXXFLAGS = -O3 -finline-functions -funswitch-loops -fgcse-after-reload -funroll-loops -ffriend-injection
+PKG_LIBS = -lRblas
diff --git a/inst/extras/cblas.h b/inst/extras/cblas.h
new file mode 100644
index 0000000..9159ae6
--- /dev/null
+++ b/inst/extras/cblas.h
@@ -0,0 +1,16 @@
+#ifndef CBLAS_H
+#define CBLAS_H
+#endif
+#include <stddef.h>
+
+/*
+ * Enumerated and derived types
+ */
+#define CBLAS_INDEX size_t  /* this may vary between platforms */
+
+enum CBLAS_ORDER {CblasRowMajor=101, CblasColMajor=102};
+enum CBLAS_TRANSPOSE {CblasNoTrans=111, CblasTrans=112, CblasConjTrans=113};
+enum CBLAS_UPLO {CblasUpper=121, CblasLower=122};
+enum CBLAS_DIAG {CblasNonUnit=131, CblasUnit=132};
+enum CBLAS_SIDE {CblasLeft=141, CblasRight=142};
+
diff --git a/inst/extras/cblas_dasum.c b/inst/extras/cblas_dasum.c
new file mode 100644
index 0000000..707e4fc
--- /dev/null
+++ b/inst/extras/cblas_dasum.c
@@ -0,0 +1,26 @@
+/*
+ * cblas_dasum.c
+ *
+ * The program is a C interface to dasum.
+ * It calls the fortran wrapper before calling dasum.
+ *
+ * Written by Keita Teranishi.  2/11/1998
+ *
+ */
+
+#include <R.h>
+#include <R_ext/Applic.h> /* R blas declarations */
+
+#include "cblas.h"
+double cblas_dasum( const int N, const double *X, const int incX) 
+{
+   double asum;
+#ifdef F77_INT
+   F77_INT F77_N=N, F77_incX=incX;
+#else 
+   #define F77_N N
+   #define F77_incX incX
+#endif
+   asum = F77_CALL(dasum)( &F77_N, X, &F77_incX);
+   return asum;
+}
diff --git a/inst/extras/cblas_dgemm.c b/inst/extras/cblas_dgemm.c
new file mode 100644
index 0000000..4a5d0c0
--- /dev/null
+++ b/inst/extras/cblas_dgemm.c
@@ -0,0 +1,123 @@
+/*
+ *
+ * cblas_dgemm.c
+ * This program is a C interface to dgemm.
+ * Written by Keita Teranishi
+ * 4/8/1998
+ *
+ */
+
+#include <R.h>
+#include <R_ext/Applic.h> /* R blas declarations */
+
+#include "cblas.h"
+void cblas_dgemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA,
+                 const enum CBLAS_TRANSPOSE TransB, const int M, const int N,
+                 const int K, const double alpha, const double  *A,
+                 const int lda, const double  *B, const int ldb,
+                 const double beta, double  *C, const int ldc)
+{
+   char TA, TB;   
+#ifdef F77_CHAR
+   F77_CHAR F77_TA, F77_TB;
+#else
+   #define F77_TA &TA  
+   #define F77_TB &TB  
+#endif
+
+#ifdef F77_INT
+   F77_INT F77_M=M, F77_N=N, F77_K=K, F77_lda=lda, F77_ldb=ldb;
+   F77_INT F77_ldc=ldc;
+#else
+   #define F77_M M
+   #define F77_N N
+   #define F77_K K
+   #define F77_lda lda
+   #define F77_ldb ldb
+   #define F77_ldc ldc
+#endif
+
+   /* the follow two vars were originally in Carla's.h as ex-terns, but that runs into conflicts on system with a
+      preexisting cblas */
+   int CBLAS_CallFromC;
+   int RowMajorStrg;
+
+   RowMajorStrg = 0;
+   CBLAS_CallFromC = 1;
+
+   if( Order == CblasColMajor )
+   {
+      if(TransA == CblasTrans) TA='T';
+      else if ( TransA == CblasConjTrans ) TA='C';
+      else if ( TransA == CblasNoTrans )   TA='N';
+      else 
+      {
+	error("cblas_dgemm","Illegal TransA setting, %d\n", TransA);
+	/* cblas_xerbla(2, "cblas_dgemm","Illegal TransA setting, %d\n", TransA); */
+         CBLAS_CallFromC = 0;
+         RowMajorStrg = 0;
+         return;
+      }
+
+      if(TransB == CblasTrans) TB='T';
+      else if ( TransB == CblasConjTrans ) TB='C';
+      else if ( TransB == CblasNoTrans )   TB='N';
+      else 
+      {
+	error("cblas_dgemm","Illegal TransB setting, %d\n", TransB);
+	/* cblas_xerbla(3, "cblas_dgemm","Illegal TransB setting, %d\n", TransB); */
+         CBLAS_CallFromC = 0;
+         RowMajorStrg = 0;
+         return;
+      }
+
+      #ifdef F77_CHAR
+         F77_TA = C2F_CHAR(&TA);
+         F77_TB = C2F_CHAR(&TB);
+      #endif
+
+	 F77_CALL(dgemm)(F77_TA, F77_TB, &F77_M, &F77_N, &F77_K, &alpha, A,
+       &F77_lda, B, &F77_ldb, &beta, C, &F77_ldc);
+   } else if (Order == CblasRowMajor)
+   {
+      RowMajorStrg = 1;
+      if(TransA == CblasTrans) TB='T';
+      else if ( TransA == CblasConjTrans ) TB='C';
+      else if ( TransA == CblasNoTrans )   TB='N';
+      else 
+      {
+	error("cblas_dgemm","Illegal TransA setting, %d\n", TransA);
+	/* cblas_xerbla(2, "cblas_dgemm","Illegal TransA setting, %d\n", TransA); */
+         CBLAS_CallFromC = 0;
+         RowMajorStrg = 0;
+         return;
+      }
+      if(TransB == CblasTrans) TA='T';
+      else if ( TransB == CblasConjTrans ) TA='C';
+      else if ( TransB == CblasNoTrans )   TA='N';
+      else 
+      {
+	error("cblas_dgemm","Illegal TransB setting, %d\n", TransB);
+	/* cblas_xerbla(2, "cblas_dgemm","Illegal TransB setting, %d\n", TransB); */
+         CBLAS_CallFromC = 0;
+         RowMajorStrg = 0;
+         return;
+      }
+      #ifdef F77_CHAR
+         F77_TA = C2F_CHAR(&TA);
+         F77_TB = C2F_CHAR(&TB);
+      #endif
+
+	 F77_CALL(dgemm)(F77_TA, F77_TB, &F77_N, &F77_M, &F77_K, &alpha, B,
+			 &F77_ldb, A, &F77_lda, &beta, C, &F77_ldc);
+   } 
+   else  {
+     error("cblas_dgemm", "Illegal Order setting, %d\n", Order);
+     /* cblas_xerbla(1, "cblas_dgemm", "Illegal Order setting, %d\n", Order); */
+   }
+   CBLAS_CallFromC = 0;
+   RowMajorStrg = 0;
+   return;
+}
+
+
diff --git a/inst/extras/cblas_dscal.c b/inst/extras/cblas_dscal.c
new file mode 100644
index 0000000..4bf9c02
--- /dev/null
+++ b/inst/extras/cblas_dscal.c
@@ -0,0 +1,24 @@
+/*
+ * cblas_dscal.c
+ *
+ * The program is a C interface to dscal.
+ *
+ * Written by Keita Teranishi.  2/11/1998
+ *
+ */
+
+#include <R.h>
+#include <R_ext/Applic.h> /* R blas declarations */
+
+#include "cblas.h"
+void cblas_dscal( const int N, const double alpha, double *X, 
+                       const int incX)
+{
+#ifdef F77_INT
+   F77_INT F77_N=N, F77_incX=incX;
+#else 
+   #define F77_N N
+   #define F77_incX incX
+#endif
+   F77_CALL(dscal)( &F77_N, &alpha, X, &F77_incX);
+}
diff --git a/inst/extras/cblas_dsymm.c b/inst/extras/cblas_dsymm.c
new file mode 100644
index 0000000..33246c3
--- /dev/null
+++ b/inst/extras/cblas_dsymm.c
@@ -0,0 +1,116 @@
+/*
+ *
+ * cblas_dsymm.c
+ * This program is a C interface to dsymm.
+ * Written by Keita Teranishi
+ * 4/8/1998
+ *
+ */
+
+#include <R.h>
+#include <R_ext/Applic.h> /* R blas declarations */
+
+#include "cblas.h"
+void cblas_dsymm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side,
+                 const enum CBLAS_UPLO Uplo, const int M, const int N,
+                 const double alpha, const double  *A, const int lda,
+                 const double  *B, const int ldb, const double beta,
+                 double  *C, const int ldc)
+{
+   char SD, UL;   
+#ifdef F77_CHAR
+   F77_CHAR F77_SD, F77_UL;
+#else
+   #define F77_SD &SD  
+   #define F77_UL &UL  
+#endif
+
+#ifdef F77_INT
+   F77_INT F77_M=M, F77_N=N, F77_lda=lda, F77_ldb=ldb;
+   F77_INT F77_ldc=ldc;
+#else
+   #define F77_M M
+   #define F77_N N
+   #define F77_lda lda
+   #define F77_ldb ldb
+   #define F77_ldc ldc
+#endif
+
+   int CBLAS_CallFromC;
+   int RowMajorStrg;
+   RowMajorStrg = 0;
+   CBLAS_CallFromC = 1;
+
+   if( Order == CblasColMajor )
+   {
+      if( Side == CblasRight) SD='R';
+      else if ( Side == CblasLeft ) SD='L';
+      else 
+      {
+	error("cblas_dsymm: Illegal Side setting, %d\n", Side);
+	/* cblas_xerbla(2, "cblas_dsymm","Illegal Side setting, %d\n", Side);*/
+         CBLAS_CallFromC = 0;
+         RowMajorStrg = 0;
+         return;
+      }
+
+      if( Uplo == CblasUpper) UL='U';
+      else if ( Uplo == CblasLower ) UL='L';
+      else 
+      {
+	error("cblas_dsymm: Illegal Uplo setting, %d\n", Uplo);
+	/* cblas_xerbla(3, "cblas_dsymm","Illegal Uplo setting, %d\n", Uplo); */
+         CBLAS_CallFromC = 0;
+         RowMajorStrg = 0;
+         return;
+      }
+
+      #ifdef F77_CHAR
+         F77_UL = C2F_CHAR(&UL);
+         F77_SD = C2F_CHAR(&SD);
+      #endif
+
+	 F77_CALL(dsymm)(F77_SD, F77_UL, &F77_M, &F77_N, &alpha, A, &F77_lda,
+                      B, &F77_ldb, &beta, C, &F77_ldc);
+   } else if (Order == CblasRowMajor)
+   {
+      RowMajorStrg = 1;
+      if( Side == CblasRight) SD='L';
+      else if ( Side == CblasLeft ) SD='R';
+      else 
+      {
+	error("cblas_dsymm: Illegal Side setting, %d\n", Side);
+	/* cblas_xerbla(2, "cblas_dsymm","Illegal Side setting, %d\n", Side); */
+         CBLAS_CallFromC = 0;
+         RowMajorStrg = 0;
+         return;
+      }
+
+      if( Uplo == CblasUpper) UL='L';
+      else if ( Uplo == CblasLower ) UL='U';
+      else 
+      {
+	error("cblas_dsymm: Illegal Uplo setting, %d\n", Uplo);
+	/* cblas_xerbla(3, "cblas_dsymm","Illegal Uplo setting, %d\n", Uplo); */
+         CBLAS_CallFromC = 0;
+         RowMajorStrg = 0;
+         return;
+      }
+
+      #ifdef F77_CHAR
+         F77_UL = C2F_CHAR(&UL);
+         F77_SD = C2F_CHAR(&SD);
+      #endif
+
+	 F77_CALL(dsymm)(F77_SD, F77_UL, &F77_N, &F77_M, &alpha, A, &F77_lda, B,
+                 &F77_ldb, &beta, C, &F77_ldc);
+   } 
+   else 
+     {
+       error("cblas_dsymm: Illegal Order setting, %d\n", Order);
+       /* cblas_xerbla(1, "cblas_dsymm","Illegal Order setting, %d\n", Order);  */
+     }
+   CBLAS_CallFromC = 0;
+   RowMajorStrg = 0;
+   return;
+} 
diff --git a/inst/extras/cblas_dtrmm.c b/inst/extras/cblas_dtrmm.c
new file mode 100644
index 0000000..551bca6
--- /dev/null
+++ b/inst/extras/cblas_dtrmm.c
@@ -0,0 +1,161 @@
+/*
+ *
+ * cblas_dtrmm.c
+ * This program is a C interface to dtrmm.
+ * Written by Keita Teranishi
+ * 4/6/1998
+ *
+ */
+
+#include <R.h>
+#include <R_ext/Applic.h> /* R blas declarations */
+
+#include "cblas.h"
+void cblas_dtrmm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side,
+                 const enum CBLAS_UPLO Uplo, const  enum CBLAS_TRANSPOSE TransA,
+                 const enum CBLAS_DIAG Diag, const int M, const int N,
+                 const double alpha, const double  *A, const int lda,
+                 double  *B, const int ldb)
+{
+   char UL, TA, SD, DI;   
+#ifdef F77_CHAR
+   F77_CHAR F77_TA, F77_UL, F77_SD, F77_DI;
+#else
+   #define F77_TA &TA  
+   #define F77_UL &UL  
+   #define F77_SD &SD
+   #define F77_DI &DI
+#endif
+
+#ifdef F77_INT
+   F77_INT F77_M=M, F77_N=N, F77_lda=lda, F77_ldb=ldb;
+#else
+   #define F77_M M
+   #define F77_N N
+   #define F77_lda lda
+   #define F77_ldb ldb
+#endif
+   
+   int CBLAS_CallFromC;
+   int RowMajorStrg;
+   RowMajorStrg = 0;
+   CBLAS_CallFromC = 1;
+
+   if( Order == CblasColMajor )
+   {
+      if( Side == CblasRight) SD='R';
+      else if ( Side == CblasLeft ) SD='L';
+      else 
+      {
+	error("cblas_dtrmm: Illegal Side setting, %d\n", Side);
+	/* cblas_xerbla(2, "cblas_dtrmm","Illegal Side setting, %d\n", Side); */
+         CBLAS_CallFromC = 0;
+         RowMajorStrg = 0;
+         return;
+      }
+      if( Uplo == CblasUpper) UL='U';
+      else if ( Uplo == CblasLower ) UL='L';
+      else 
+      {
+	error("cblas_dtrmm: Illegal Uplo setting, %d\n", Uplo);
+	/* cblas_xerbla(3, "cblas_dtrmm","Illegal Uplo setting, %d\n", Uplo); */
+         CBLAS_CallFromC = 0;
+         RowMajorStrg = 0;
+         return;
+      }
+
+      if( TransA == CblasTrans) TA ='T';
+      else if ( TransA == CblasConjTrans ) TA='C';
+      else if ( TransA == CblasNoTrans )   TA='N';
+      else 
+      {
+	error("cblas_dtrmm: Illegal Trans setting, %d\n", TransA);
+	/* cblas_xerbla(4, "cblas_dtrmm","Illegal Trans setting, %d\n", TransA); */
+         CBLAS_CallFromC = 0;
+         RowMajorStrg = 0;
+         return;
+      }
+
+      if( Diag == CblasUnit ) DI='U';
+      else if ( Diag == CblasNonUnit ) DI='N';
+      else 
+      {
+	error("cblas_dtrmm: Illegal Diag setting, %d\n", Diag);
+	/* cblas_xerbla(5, "cblas_dtrmm","Illegal Diag setting, %d\n", Diag); */
+         CBLAS_CallFromC = 0;
+         RowMajorStrg = 0;
+         return;
+      }
+
+      #ifdef F77_CHAR
+         F77_UL = C2F_CHAR(&UL);
+         F77_TA = C2F_CHAR(&TA);
+         F77_SD = C2F_CHAR(&SD);
+         F77_DI = C2F_CHAR(&DI);
+      #endif
+
+	 F77_CALL(dtrmm)(F77_SD, F77_UL, F77_TA, F77_DI, &F77_M, &F77_N, &alpha, A, &F77_lda, B, &F77_ldb);
+   } else if (Order == CblasRowMajor)
+   {
+      RowMajorStrg = 1;
+      if( Side == CblasRight) SD='L';
+      else if ( Side == CblasLeft ) SD='R';
+      else 
+      {
+	error("cblas_dtrmm: Illegal Side setting, %d\n", Side);
+	/* cblas_xerbla(2, "cblas_dtrmm","Illegal Side setting, %d\n", Side); */
+         CBLAS_CallFromC = 0;
+         RowMajorStrg = 0;
+         return;
+      }
+
+      if( Uplo == CblasUpper) UL='L';
+      else if ( Uplo == CblasLower ) UL='U';
+      else 
+      {
+	error("cblas_dtrmm: Illegal Uplo setting, %d\n", Uplo);
+	/* cblas_xerbla(3, "cblas_dtrmm","Illegal Uplo setting, %d\n", Uplo); */
+         CBLAS_CallFromC = 0;
+         RowMajorStrg = 0;
+         return;
+      }
+
+      if( TransA == CblasTrans) TA ='T';
+      else if ( TransA == CblasConjTrans ) TA='C';
+      else if ( TransA == CblasNoTrans )   TA='N';
+      else 
+      {
+	error("cblas_dtrmm: Illegal Trans setting, %d\n", TransA);
+	/* cblas_xerbla(4, "cblas_dtrmm","Illegal Trans setting, %d\n", TransA); */
+         CBLAS_CallFromC = 0;
+         RowMajorStrg = 0;
+         return;
+      }
+
+      if( Diag == CblasUnit ) DI='U';
+      else if ( Diag == CblasNonUnit ) DI='N';
+      else 
+      {
+	error("cblas_dtrmm: Illegal Diag setting, %d\n", Diag);
+	/* cblas_xerbla(5, "cblas_dtrmm","Illegal Diag setting, %d\n", Diag); */
+         CBLAS_CallFromC = 0;
+         RowMajorStrg = 0;
+         return;
+      }
+
+      #ifdef F77_CHAR
+         F77_UL = C2F_CHAR(&UL);
+         F77_TA = C2F_CHAR(&TA);
+         F77_SD = C2F_CHAR(&SD);
+         F77_DI = C2F_CHAR(&DI);
+      #endif
+	 F77_CALL(dtrmm)(F77_SD, F77_UL, F77_TA, F77_DI, &F77_N, &F77_M, &alpha, A, &F77_lda, B, &F77_ldb);
+   } 
+   else {
+     error("cblas_dtrmm: Illegal Order setting, %d\n", Order);
+     /* cblas_xerbla(1, "cblas_dtrmm", "Illegal Order setting, %d\n", Order); */
+   }
+   CBLAS_CallFromC = 0;
+   RowMajorStrg = 0;
+   return;
+}
diff --git a/inst/extras/configure.old b/inst/extras/configure.old
new file mode 100644
index 0000000..7e5a8a7
--- /dev/null
+++ b/inst/extras/configure.old
@@ -0,0 +1,56 @@
+#!/bin/sh
+
+#Setup optimization flags.  This significantly improves performance.
+
+# Version 2.1-2+ We now use makevars on OS X all platforms instead of
+# the makefile because of build issues on OS X.  This requires moving
+# files around because we do not want our cblas wrappers compiled on
+# OS X, but we need to assume them for all other platforms.
+
+#On Windows this script does *not* need to be run.  On Windows,
+#Makevars.win should simply be used because we can assume that we are
+#using the mingw32 compiler
+
+# -fstrict-aliasing -freorder-blocks -fsched-interblock is added for OS X (already included in the Linux gcc -O2 option
+# does no harm on Linux
+
+#Matching Version 3.4.4+: we need to add the -ffriend-injection argument for g++
+#versions 4.1+ because ARM-style name-injection of friend declarations
+#is no longer the default.  
+
+CXX=`"${R_HOME}/bin/R" CMD config CXX`
+
+echo $CXX | grep g++ > /dev/null 2>&1
+if [ "$?" -eq "0" ]; then
+
+ CFLAGS="-O3 -finline-functions -funswitch-loops -fgcse-after-reload -ffast-math -funroll-loops -fexpensive-optimizations -fstrict-aliasing -freorder-blocks -fsched-interblock"
+
+ CXXFLAGS="-O3 -finline-functions -funswitch-loops -fgcse-after-reload -ffast-math -funroll-loops -fexpensive-optimizations -fstrict-aliasing -freorder-blocks -fsched-interblock"
+
+ VERSION=`$CXX --version`
+ echo $VERSION | grep "4.1.\|4.2." > /dev/null 2>&1
+ if [ "$?" -eq "0" ]; then
+
+ CXXFLAGS="-O3 -finline-functions -funswitch-loops -fgcse-after-reload -ffast-math -funroll-loops -fexpensive-optimizations -fstrict-aliasing -freorder-blocks -fsched-interblock -ffriend-injection"
+ fi
+
+ echo "PKG_CFLAGS=$CFLAGS" > src/Makevars
+ echo "PKG_CXXFLAGS=$CXXFLAGS" >> src/Makevars
+
+
+# are we on osx?
+# if so, don't compile our own cblas headers
+# and use dmalloc
+UNAME=`uname -a`
+echo $UNAME | grep Darwin > /dev/null 2>&1
+if [ "$?" -eq "0" ]; then
+ cp inst/extras/malloc.c src/malloc.c
+ mv src/cblas_dgemm.c inst/extras
+ mv src/cblas.h inst/extras
+fi
+
+fi
+
+#NOTE: On g5 machines with OS X the following CXXFLAGS generates
+#significantly faster code:
+#PKG_CXXFLAGS="-fast"
diff --git a/inst/extras/configure.win b/inst/extras/configure.win
new file mode 100755
index 0000000..a9f9583
--- /dev/null
+++ b/inst/extras/configure.win
@@ -0,0 +1,7 @@
+#
+# We have a different Makevars.win for gcc3 (R-2.5.x) and gcc4 (R-2.6)
+#
+
+if [ "$BUILD" = "GCC4" ]; then
+    mv inst/extras/Makevars.win.gcc4 src/Makevars.win
+fi
diff --git a/inst/extras/makefile.cblas b/inst/extras/makefile.cblas
new file mode 100644
index 0000000..b0be5a3
--- /dev/null
+++ b/inst/extras/makefile.cblas
@@ -0,0 +1,36 @@
+#gnumake
+#ifeq ($(CXX),g++)
+#CXXFLAGS = -O3 -ffast-math -funroll-loops -fexpensive-optimizations 
+#endif
+
+#bsdmake
+#.if $(CXX)==g++
+# CXXFLAGS = -O3 -ffast-math -funroll-loops -fexpensive-optimizations 
+#.endif
+
+SOURCES = matching.cc scythematrix.cc 
+
+HEADERS = matching.h scythematrix.h cblas.h
+#OBJS = $(SOURCES:.cc=.o cblas_dgemm.o)
+OBJS = matching.o scythematrix.o 
+
+PROGRAM = Matching${SHLIB_EXT}
+
+#$(PROGRAM):	$(OBJS) $(LIBS)
+#		$(SHLIB_CXXLD) $(DYLIB_LDFLAGS) $(OBJS) -o $(PROGRAM)
+#		@echo library $(PROGRAM) ready.
+
+ALL_CXXFLAGS = $(R_XTRA_CXXFLAGS) $(PKG_CXXFLAGS) $(CXXPICFLAGS) $(SHLIB_CXXFLAGS) $(CXXFLAGS)
+
+$(PROGRAM):	$(OBJS) 
+		$(SHLIB_CXXLD) $(SHLIB_CXXLDFLAGS) $(PKG_CXXLDFLAGS) $(ALL_CXXFLAGS) $(OBJS) -o $(PROGRAM)
+		@echo library $(PROGRAM) ready.
+
+clean:
+	rm -f core*
+	rm -f *.o
+
+
+
+
+
diff --git a/inst/extras/makefile.icc b/inst/extras/makefile.icc
new file mode 100644
index 0000000..489bdec
--- /dev/null
+++ b/inst/extras/makefile.icc
@@ -0,0 +1,44 @@
+CXX=icc -gcc-version=400 -static-libcxa -i-static
+CC=icc -gcc-version=400 -static-libcxa -i-static
+DYLIB_LD=icc -gcc-version=400 -static-libcxa -i-static
+SHLIB_CXXLD=icc -gcc-version=400 -lsvml -L /opt/intel/cc/9.1.038/lib -static-libcxa -i-static -lstdc++
+SHLIB_LD=icc -gcc-version=400 -lsvml -L /opt/intel/cc/9.1.038/lib -static-libcxa -i-static -lstdc++
+
+CXXFLAGS=-fast -static
+CFLAGS=-fast -static
+
+#CXXFLAGS=-O3 -no-prec-div -xP -openmp -static -parallel -rcd -pc32 -opt_report
+#CFLAGS=-O3 -no-prec-div -xP -openmp -static -parallel -opt_report
+
+#CXXFLAGS=-O3 -openmp -axN -ssp -fp-model fast=2 -funroll-loops -msse2 -ipo -no-prec-div -static -finline-functions 
+#CFLAGS=-O3 -openmp -axN -ssp -fp-model fast=2 funroll-loops -msse2 -ipo -no-prec-div -static -finline-functions
+
+#CXXFLAGS=-O3 -openmp -xP -ssp -funroll-loops -no-prec-div -static -finline-functions 
+#CFLAGS=-O3 -openmp -xP -ssp -funroll-loops -no-prec-div -static -finline-functions
+
+SOURCES = matching.cc scythematrix.cc 
+
+HEADERS = matching.h scythematrix.h 
+#OBJS = $(SOURCES:.cc=.o cblas_dgemm.o)
+OBJS = matching.o scythematrix.o 
+
+PROGRAM = Matching${SHLIB_EXT}
+
+#$(PROGRAM):	$(OBJS) $(LIBS)
+#		$(SHLIB_CXXLD) $(DYLIB_LDFLAGS) $(OBJS) -o $(PROGRAM)
+#		@echo library $(PROGRAM) ready.
+
+ALL_CXXFLAGS = $(R_XTRA_CXXFLAGS) $(PKG_CXXFLAGS) $(CXXPICFLAGS) $(SHLIB_CXXFLAGS) $(CXXFLAGS)
+
+$(PROGRAM):	$(OBJS) 
+		$(SHLIB_CXXLD) $(SHLIB_CXXLDFLAGS) $(PKG_CXXLDFLAGS) $(ALL_CXXFLAGS) $(OBJS) -o $(PROGRAM)
+		@echo library $(PROGRAM) ready.
+
+clean:
+	rm -f core*
+	rm -f *.o
+
+
+
+
+
diff --git a/inst/extras/makefile.in b/inst/extras/makefile.in
new file mode 100644
index 0000000..93c6683
--- /dev/null
+++ b/inst/extras/makefile.in
@@ -0,0 +1,36 @@
+#gnumake
+#ifeq ($(CXX),g++)
+#CXXFLAGS = -O3 -ffast-math -funroll-loops -fexpensive-optimizations 
+#endif
+
+#bsdmake
+#.if $(CXX)==g++
+# CXXFLAGS = -O3 -ffast-math -funroll-loops -fexpensive-optimizations 
+#.endif
+
+SOURCES = matching.cc scythematrix.cc cblas_dgemm.c
+
+HEADERS = matching.h scythematrix.h cblas.h
+#OBJS = $(SOURCES:.cc=.o cblas_dgemm.o)
+OBJS = matching.o scythematrix.o cblas_dgemm.o
+
+PROGRAM = Matching${SHLIB_EXT}
+
+#$(PROGRAM):	$(OBJS) $(LIBS)
+#		$(SHLIB_CXXLD) $(DYLIB_LDFLAGS) $(OBJS) -o $(PROGRAM)
+#		@echo library $(PROGRAM) ready.
+
+ALL_CXXFLAGS = $(R_XTRA_CXXFLAGS) $(PKG_CXXFLAGS) $(CXXPICFLAGS) $(SHLIB_CXXFLAGS) $(CXXFLAGS)
+
+$(PROGRAM):	$(OBJS) 
+		$(SHLIB_CXXLD) $(SHLIB_CXXLDFLAGS) $(PKG_CXXLDFLAGS) $(ALL_CXXFLAGS) $(OBJS) -o $(PROGRAM)
+		@echo library $(PROGRAM) ready.
+
+clean:
+	rm -f core*
+	rm -f *.o
+
+
+
+
+
diff --git a/inst/extras/makefile.osx.in b/inst/extras/makefile.osx.in
new file mode 100644
index 0000000..5c4af16
--- /dev/null
+++ b/inst/extras/makefile.osx.in
@@ -0,0 +1,36 @@
+#gnumake
+#ifeq ($(CXX),g++)
+#CXXFLAGS = -O3 -ffast-math -funroll-loops -fexpensive-optimizations 
+#endif
+
+#bsdmake
+#.if $(CXX)==g++
+# CXXFLAGS = -O3 -ffast-math -funroll-loops -fexpensive-optimizations 
+#.endif
+
+SOURCES = matching.cc scythematrix.cc malloc.c
+
+HEADERS = matching.h scythematrix.h 
+#OBJS = $(SOURCES:.cc=.o cblas_dgemm.o)
+OBJS = matching.o scythematrix.o malloc.o
+
+PROGRAM = Matching${SHLIB_EXT}
+
+#$(PROGRAM):	$(OBJS) $(LIBS)
+#		$(SHLIB_CXXLD) $(DYLIB_LDFLAGS) $(OBJS) -o $(PROGRAM)
+#		@echo library $(PROGRAM) ready.
+
+ALL_CXXFLAGS = $(R_XTRA_CXXFLAGS) $(PKG_CXXFLAGS) $(CXXPICFLAGS) $(SHLIB_CXXFLAGS) $(CXXFLAGS)
+
+$(PROGRAM):	$(OBJS) 
+		$(SHLIB_CXXLD) $(SHLIB_CXXLDFLAGS) $(PKG_CXXLDFLAGS) $(ALL_CXXFLAGS) $(OBJS) -o $(PROGRAM)
+		@echo library $(PROGRAM) ready.
+
+clean:
+	rm -f core*
+	rm -f *.o
+
+
+
+
+
diff --git a/inst/extras/makefile.sun b/inst/extras/makefile.sun
new file mode 100644
index 0000000..709c568
--- /dev/null
+++ b/inst/extras/makefile.sun
@@ -0,0 +1,44 @@
+CXX=/opt/sun/sunstudio12/bin/CC
+CC=/opt/sun/sunstudio12/bin/cc
+
+SHLIB_CXXLD=/opt/sun/sunstudio12/bin/CC -G -KPIC -lCrun -fast -lmtsk -mt 
+
+#Non-parallel options
+CXXFLAGS=-fast -KPIC -m64 -library=stlport4 -xipo -I/usr/local/lib64/R/include -I/usr/local/lib64/R/include  -I/usr/local/include
+CFLAGS=-fast -KPIC -m64 -xipo -I/usr/local/lib64/R/include -I/usr/local/lib64/R/include  -I/usr/local/include
+
+#setenv PARALLEL 2
+#set OMP_NUM_THREADS=2
+#/opt/sun/sunstudio12/lib/amd64
+#/opt/sun/sunstudio12/rtlibs/amd64
+#env LD_LIBRARY_PATH=/opt/sun/sunstudio12/rtlibs/amd64:/opt/sun/sunstudio12/lib/amd64
+#CXXFLAGS=-fast -KPIC -m64  -library=stlport4  -xtarget=opteron -xchip=opteron -xvector=simd -xprefetch -xprefetch_level=3   -xcache=64/64/2:1024/64/16 -xalias_level=compatible -xrestrict -xipo  -xarch=sse3a -xautopar -xloopinfo -xopenmp
+#CFLAGS=-fast -KPIC -m64  -xtarget=opteron -xchip=opteron -xvector=simd -xprefetch -xprefetch_level=3   -xcache=64/64/2:1024/64/16 -xalias_level=strong -xrestrict -xipo -xarch-sse3a -xautopar -xloopinfo  -xopenmp
+
+R_XTRA_CXXFLAGS=-I/usr/local/lib64/R/include -I/usr/local/lib64/R/include  -I/usr/local/include
+
+SOURCES = matching.cc scythematrix.cc cblas_dasum.c cblas_dgemm.c cblas_dscal.c
+
+HEADERS = matching.h scythematrix.h cblas_dasum.c cblas_dgemm.c cblas_dscal.c
+OBJS = matching.o scythematrix.o cblas_dasum.o cblas_dgemm.o cblas_dscal.o
+
+PROGRAM = Matching.so
+
+#$(PROGRAM):	$(OBJS) $(LIBS)
+#		$(SHLIB_CXXLD) $(DYLIB_LDFLAGS) $(OBJS) -o $(PROGRAM)
+#		@echo library $(PROGRAM) ready.
+
+ALL_CXXFLAGS = $(R_XTRA_CXXFLAGS) $(SHLIB_CXXFLAGS) $(CXXFLAGS)
+
+$(PROGRAM):	$(OBJS) 
+		$(SHLIB_CXXLD) $(ALL_CXXFLAGS) $(OBJS) -o $(PROGRAM)
+		@echo library $(PROGRAM) ready.
+
+clean:
+	rm -f core*
+	rm -f *.o
+
+
+
+
+
diff --git a/inst/extras/malloc.c b/inst/extras/malloc.c
new file mode 100644
index 0000000..809e19a
--- /dev/null
+++ b/inst/extras/malloc.c
@@ -0,0 +1,5061 @@
+/*
+  This is a version (aka dlmalloc) of malloc/free/realloc written by
+  Doug Lea and released to the public domain, as explained at
+  http://creativecommons.org/licenses/publicdomain.  Send questions,
+  comments, complaints, performance data, etc to dl at cs.oswego.edu
+
+* Version 2.8.3 Thu Sep 22 11:16:15 2005  Doug Lea  (dl at gee)
+
+   Note: There may be an updated version of this malloc obtainable at
+           ftp://gee.cs.oswego.edu/pub/misc/malloc.c
+         Check before installing!
+
+* Quickstart
+
+  This library is all in one file to simplify the most common usage:
+  ftp it, compile it (-O3), and link it into another program. All of
+  the compile-time options default to reasonable values for use on
+  most platforms.  You might later want to step through various
+  compile-time and dynamic tuning options.
+
+  For convenience, an include file for code using this malloc is at:
+     ftp://gee.cs.oswego.edu/pub/misc/malloc-2.8.3.h
+  You don't really need this .h file unless you call functions not
+  defined in your system include files.  The .h file contains only the
+  excerpts from this file needed for using this malloc on ANSI C/C++
+  systems, so long as you haven't changed compile-time options about
+  naming and tuning parameters.  If you do, then you can create your
+  own malloc.h that does include all settings by cutting at the point
+  indicated below. Note that you may already by default be using a C
+  library containing a malloc that is based on some version of this
+  malloc (for example in linux). You might still want to use the one
+  in this file to customize settings or to avoid overheads associated
+  with library versions.
+
+* Vital statistics:
+
+  Supported pointer/size_t representation:       4 or 8 bytes
+       size_t MUST be an unsigned type of the same width as
+       pointers. (If you are using an ancient system that declares
+       size_t as a signed type, or need it to be a different width
+       than pointers, you can use a previous release of this malloc
+       (e.g. 2.7.2) supporting these.)
+
+  Alignment:                                     8 bytes (default)
+       This suffices for nearly all current machines and C compilers.
+       However, you can define MALLOC_ALIGNMENT to be wider than this
+       if necessary (up to 128bytes), at the expense of using more space.
+
+  Minimum overhead per allocated chunk:   4 or  8 bytes (if 4byte sizes)
+                                          8 or 16 bytes (if 8byte sizes)
+       Each malloced chunk has a hidden word of overhead holding size
+       and status information, and additional cross-check word
+       if FOOTERS is defined.
+
+  Minimum allocated size: 4-byte ptrs:  16 bytes    (including overhead)
+                          8-byte ptrs:  32 bytes    (including overhead)
+
+       Even a request for zero bytes (i.e., malloc(0)) returns a
+       pointer to something of the minimum allocatable size.
+       The maximum overhead wastage (i.e., number of extra bytes
+       allocated than were requested in malloc) is less than or equal
+       to the minimum size, except for requests >= mmap_threshold that
+       are serviced via mmap(), where the worst case wastage is about
+       32 bytes plus the remainder from a system page (the minimal
+       mmap unit); typically 4096 or 8192 bytes.
+
+  Security: static-safe; optionally more or less
+       The "security" of malloc refers to the ability of malicious
+       code to accentuate the effects of errors (for example, freeing
+       space that is not currently malloc'ed or overwriting past the
+       ends of chunks) in code that calls malloc.  This malloc
+       guarantees not to modify any memory locations below the base of
+       heap, i.e., static variables, even in the presence of usage
+       errors.  The routines additionally detect most improper frees
+       and reallocs.  All this holds as long as the static bookkeeping
+       for malloc itself is not corrupted by some other means.  This
+       is only one aspect of security -- these checks do not, and
+       cannot, detect all possible programming errors.
+
+       If FOOTERS is defined nonzero, then each allocated chunk
+       carries an additional check word to verify that it was malloced
+       from its space.  These check words are the same within each
+       execution of a program using malloc, but differ across
+       executions, so externally crafted fake chunks cannot be
+       freed. This improves security by rejecting frees/reallocs that
+       could corrupt heap memory, in addition to the checks preventing
+       writes to statics that are always on.  This may further improve
+       security at the expense of time and space overhead.  (Note that
+       FOOTERS may also be worth using with MSPACES.)
+
+       By default detected errors cause the program to abort (calling
+       "abort()"). You can override this to instead proceed past
+       errors by defining PROCEED_ON_ERROR.  In this case, a bad free
+       has no effect, and a malloc that encounters a bad address
+       caused by user overwrites will ignore the bad address by
+       dropping pointers and indices to all known memory. This may
+       be appropriate for programs that should continue if at all
+       possible in the face of programming errors, although they may
+       run out of memory because dropped memory is never reclaimed.
+
+       If you don't like either of these options, you can define
+       CORRUPTION_ERROR_ACTION and USAGE_ERROR_ACTION to do anything
+       else. And if if you are sure that your program using malloc has
+       no errors or vulnerabilities, you can define INSECURE to 1,
+       which might (or might not) provide a small performance improvement.
+
+  Thread-safety: NOT thread-safe unless USE_LOCKS defined
+       When USE_LOCKS is defined, each public call to malloc, free,
+       etc is surrounded with either a pthread mutex or a win32
+       spinlock (depending on WIN32). This is not especially fast, and
+       can be a major bottleneck.  It is designed only to provide
+       minimal protection in concurrent environments, and to provide a
+       basis for extensions.  If you are using malloc in a concurrent
+       program, consider instead using ptmalloc, which is derived from
+       a version of this malloc. (See http://www.malloc.de).
+
+  System requirements: Any combination of MORECORE and/or MMAP/MUNMAP
+       This malloc can use unix sbrk or any emulation (invoked using
+       the CALL_MORECORE macro) and/or mmap/munmap or any emulation
+       (invoked using CALL_MMAP/CALL_MUNMAP) to get and release system
+       memory.  On most unix systems, it tends to work best if both
+       MORECORE and MMAP are enabled.  On Win32, it uses emulations
+       based on VirtualAlloc. It also uses common C library functions
+       like memset.
+
+  Compliance: I believe it is compliant with the Single Unix Specification
+       (See http://www.unix.org). Also SVID/XPG, ANSI C, and probably
+       others as well.
+
+* Overview of algorithms
+
+  This is not the fastest, most space-conserving, most portable, or
+  most tunable malloc ever written. However it is among the fastest
+  while also being among the most space-conserving, portable and
+  tunable.  Consistent balance across these factors results in a good
+  general-purpose allocator for malloc-intensive programs.
+
+  In most ways, this malloc is a best-fit allocator. Generally, it
+  chooses the best-fitting existing chunk for a request, with ties
+  broken in approximately least-recently-used order. (This strategy
+  normally maintains low fragmentation.) However, for requests less
+  than 256bytes, it deviates from best-fit when there is not an
+  exactly fitting available chunk by preferring to use space adjacent
+  to that used for the previous small request, as well as by breaking
+  ties in approximately most-recently-used order. (These enhance
+  locality of series of small allocations.)  And for very large requests
+  (>= 256Kb by default), it relies on system memory mapping
+  facilities, if supported.  (This helps avoid carrying around and
+  possibly fragmenting memory used only for large chunks.)
+
+  All operations (except malloc_stats and mallinfo) have execution
+  times that are bounded by a constant factor of the number of bits in
+  a size_t, not counting any clearing in calloc or copying in realloc,
+  or actions surrounding MORECORE and MMAP that have times
+  proportional to the number of non-contiguous regions returned by
+  system allocation routines, which is often just 1.
+
+  The implementation is not very modular and seriously overuses
+  macros. Perhaps someday all C compilers will do as good a job
+  inlining modular code as can now be done by brute-force expansion,
+  but now, enough of them seem not to.
+
+  Some compilers issue a lot of warnings about code that is
+  dead/unreachable only on some platforms, and also about intentional
+  uses of negation on unsigned types. All known cases of each can be
+  ignored.
+
+  For a longer but out of date high-level description, see
+     http://gee.cs.oswego.edu/dl/html/malloc.html
+
+* MSPACES
+  If MSPACES is defined, then in addition to malloc, free, etc.,
+  this file also defines mspace_malloc, mspace_free, etc. These
+  are versions of malloc routines that take an "mspace" argument
+  obtained using create_mspace, to control all internal bookkeeping.
+  If ONLY_MSPACES is defined, only these versions are compiled.
+  So if you would like to use this allocator for only some allocations,
+  and your system malloc for others, you can compile with
+  ONLY_MSPACES and then do something like...
+    static mspace mymspace = create_mspace(0,0); // for example
+    #define mymalloc(bytes)  mspace_malloc(mymspace, bytes)
+
+  (Note: If you only need one instance of an mspace, you can instead
+  use "USE_DL_PREFIX" to relabel the global malloc.)
+
+  You can similarly create thread-local allocators by storing
+  mspaces as thread-locals. For example:
+    static __thread mspace tlms = 0;
+    void*  tlmalloc(size_t bytes) {
+      if (tlms == 0) tlms = create_mspace(0, 0);
+      return mspace_malloc(tlms, bytes);
+    }
+    void  tlfree(void* mem) { mspace_free(tlms, mem); }
+
+  Unless FOOTERS is defined, each mspace is completely independent.
+  You cannot allocate from one and free to another (although
+  conformance is only weakly checked, so usage errors are not always
+  caught). If FOOTERS is defined, then each chunk carries around a tag
+  indicating its originating mspace, and frees are directed to their
+  originating spaces.
+
+ -------------------------  Compile-time options ---------------------------
+
+Be careful in setting #define values for numerical constants of type
+size_t. On some systems, literal values are not automatically extended
+to size_t precision unless they are explicitly casted.
+
+WIN32                    default: defined if _WIN32 defined
+  Defining WIN32 sets up defaults for MS environment and compilers.
+  Otherwise defaults are for unix.
+
+MALLOC_ALIGNMENT         default: (size_t)8
+  Controls the minimum alignment for malloc'ed chunks.  It must be a
+  power of two and at least 8, even on machines for which smaller
+  alignments would suffice. It may be defined as larger than this
+  though. Note however that code and data structures are optimized for
+  the case of 8-byte alignment.
+
+MSPACES                  default: 0 (false)
+  If true, compile in support for independent allocation spaces.
+  This is only supported if HAVE_MMAP is true.
+
+ONLY_MSPACES             default: 0 (false)
+  If true, only compile in mspace versions, not regular versions.
+
+USE_LOCKS                default: 0 (false)
+  Causes each call to each public routine to be surrounded with
+  pthread or WIN32 mutex lock/unlock. (If set true, this can be
+  overridden on a per-mspace basis for mspace versions.)
+
+FOOTERS                  default: 0
+  If true, provide extra checking and dispatching by placing
+  information in the footers of allocated chunks. This adds
+  space and time overhead.
+
+INSECURE                 default: 0
+  If true, omit checks for usage errors and heap space overwrites.
+
+USE_DL_PREFIX            default: NOT defined
+  Causes compiler to prefix all public routines with the string 'dl'.
+  This can be useful when you only want to use this malloc in one part
+  of a program, using your regular system malloc elsewhere.
+
+ABORT                    default: defined as abort()
+  Defines how to abort on failed checks.  On most systems, a failed
+  check cannot die with an "assert" or even print an informative
+  message, because the underlying print routines in turn call malloc,
+  which will fail again.  Generally, the best policy is to simply call
+  abort(). It's not very useful to do more than this because many
+  errors due to overwriting will show up as address faults (null, odd
+  addresses etc) rather than malloc-triggered checks, so will also
+  abort.  Also, most compilers know that abort() does not return, so
+  can better optimize code conditionally calling it.
+
+PROCEED_ON_ERROR           default: defined as 0 (false)
+  Controls whether detected bad addresses cause them to bypassed
+  rather than aborting. If set, detected bad arguments to free and
+  realloc are ignored. And all bookkeeping information is zeroed out
+  upon a detected overwrite of freed heap space, thus losing the
+  ability to ever return it from malloc again, but enabling the
+  application to proceed. If PROCEED_ON_ERROR is defined, the
+  static variable malloc_corruption_error_count is compiled in
+  and can be examined to see if errors have occurred. This option
+  generates slower code than the default abort policy.
+
+DEBUG                    default: NOT defined
+  The DEBUG setting is mainly intended for people trying to modify
+  this code or diagnose problems when porting to new platforms.
+  However, it may also be able to better isolate user errors than just
+  using runtime checks.  The assertions in the check routines spell
+  out in more detail the assumptions and invariants underlying the
+  algorithms.  The checking is fairly extensive, and will slow down
+  execution noticeably. Calling malloc_stats or mallinfo with DEBUG
+  set will attempt to check every non-mmapped allocated and free chunk
+  in the course of computing the summaries.
+
+ABORT_ON_ASSERT_FAILURE   default: defined as 1 (true)
+  Debugging assertion failures can be nearly impossible if your
+  version of the assert macro causes malloc to be called, which will
+  lead to a cascade of further failures, blowing the runtime stack.
+  ABORT_ON_ASSERT_FAILURE cause assertions failures to call abort(),
+  which will usually make debugging easier.
+
+MALLOC_FAILURE_ACTION     default: sets errno to ENOMEM, or no-op on win32
+  The action to take before "return 0" when malloc fails to be able to
+  return memory because there is none available.
+
+HAVE_MORECORE             default: 1 (true) unless win32 or ONLY_MSPACES
+  True if this system supports sbrk or an emulation of it.
+
+MORECORE                  default: sbrk
+  The name of the sbrk-style system routine to call to obtain more
+  memory.  See below for guidance on writing custom MORECORE
+  functions. The type of the argument to sbrk/MORECORE varies across
+  systems.  It cannot be size_t, because it supports negative
+  arguments, so it is normally the signed type of the same width as
+  size_t (sometimes declared as "intptr_t").  It doesn't much matter
+  though. Internally, we only call it with arguments less than half
+  the max value of a size_t, which should work across all reasonable
+  possibilities, although sometimes generating compiler warnings.  See
+  near the end of this file for guidelines for creating a custom
+  version of MORECORE.
+
+MORECORE_CONTIGUOUS       default: 1 (true)
+  If true, take advantage of fact that consecutive calls to MORECORE
+  with positive arguments always return contiguous increasing
+  addresses.  This is true of unix sbrk. It does not hurt too much to
+  set it true anyway, since malloc copes with non-contiguities.
+  Setting it false when definitely non-contiguous saves time
+  and possibly wasted space it would take to discover this though.
+
+MORECORE_CANNOT_TRIM      default: NOT defined
+  True if MORECORE cannot release space back to the system when given
+  negative arguments. This is generally necessary only if you are
+  using a hand-crafted MORECORE function that cannot handle negative
+  arguments.
+
+HAVE_MMAP                 default: 1 (true)
+  True if this system supports mmap or an emulation of it.  If so, and
+  HAVE_MORECORE is not true, MMAP is used for all system
+  allocation. If set and HAVE_MORECORE is true as well, MMAP is
+  primarily used to directly allocate very large blocks. It is also
+  used as a backup strategy in cases where MORECORE fails to provide
+  space from system. Note: A single call to MUNMAP is assumed to be
+  able to unmap memory that may have be allocated using multiple calls
+  to MMAP, so long as they are adjacent.
+
+HAVE_MREMAP               default: 1 on linux, else 0
+  If true realloc() uses mremap() to re-allocate large blocks and
+  extend or shrink allocation spaces.
+
+MMAP_CLEARS               default: 1 on unix
+  True if mmap clears memory so calloc doesn't need to. This is true
+  for standard unix mmap using /dev/zero.
+
+USE_BUILTIN_FFS            default: 0 (i.e., not used)
+  Causes malloc to use the builtin ffs() function to compute indices.
+  Some compilers may recognize and intrinsify ffs to be faster than the
+  supplied C version. Also, the case of x86 using gcc is special-cased
+  to an asm instruction, so is already as fast as it can be, and so
+  this setting has no effect. (On most x86s, the asm version is only
+  slightly faster than the C version.)
+
+malloc_getpagesize         default: derive from system includes, or 4096.
+  The system page size. To the extent possible, this malloc manages
+  memory from the system in page-size units.  This may be (and
+  usually is) a function rather than a constant. This is ignored
+  if WIN32, where page size is determined using getSystemInfo during
+  initialization.
+
+USE_DEV_RANDOM             default: 0 (i.e., not used)
+  Causes malloc to use /dev/random to initialize secure magic seed for
+  stamping footers. Otherwise, the current time is used.
+
+NO_MALLINFO                default: 0
+  If defined, don't compile "mallinfo". This can be a simple way
+  of dealing with mismatches between system declarations and
+  those in this file.
+
+MALLINFO_FIELD_TYPE        default: size_t
+  The type of the fields in the mallinfo struct. This was originally
+  defined as "int" in SVID etc, but is more usefully defined as
+  size_t. The value is used only if  HAVE_USR_INCLUDE_MALLOC_H is not set
+
+REALLOC_ZERO_BYTES_FREES    default: not defined
+  This should be set if a call to realloc with zero bytes should 
+  be the same as a call to free. Some people think it should. Otherwise, 
+  since this malloc returns a unique pointer for malloc(0), so does 
+  realloc(p, 0).
+
+LACKS_UNISTD_H, LACKS_FCNTL_H, LACKS_SYS_PARAM_H, LACKS_SYS_MMAN_H
+LACKS_STRINGS_H, LACKS_STRING_H, LACKS_SYS_TYPES_H,  LACKS_ERRNO_H
+LACKS_STDLIB_H                default: NOT defined unless on WIN32
+  Define these if your system does not have these header files.
+  You might need to manually insert some of the declarations they provide.
+
+DEFAULT_GRANULARITY        default: page size if MORECORE_CONTIGUOUS,
+                                system_info.dwAllocationGranularity in WIN32,
+                                otherwise 64K.
+      Also settable using mallopt(M_GRANULARITY, x)
+  The unit for allocating and deallocating memory from the system.  On
+  most systems with contiguous MORECORE, there is no reason to
+  make this more than a page. However, systems with MMAP tend to
+  either require or encourage larger granularities.  You can increase
+  this value to prevent system allocation functions to be called so
+  often, especially if they are slow.  The value must be at least one
+  page and must be a power of two.  Setting to 0 causes initialization
+  to either page size or win32 region size.  (Note: In previous
+  versions of malloc, the equivalent of this option was called
+  "TOP_PAD")
+
+DEFAULT_TRIM_THRESHOLD    default: 2MB
+      Also settable using mallopt(M_TRIM_THRESHOLD, x)
+  The maximum amount of unused top-most memory to keep before
+  releasing via malloc_trim in free().  Automatic trimming is mainly
+  useful in long-lived programs using contiguous MORECORE.  Because
+  trimming via sbrk can be slow on some systems, and can sometimes be
+  wasteful (in cases where programs immediately afterward allocate
+  more large chunks) the value should be high enough so that your
+  overall system performance would improve by releasing this much
+  memory.  As a rough guide, you might set to a value close to the
+  average size of a process (program) running on your system.
+  Releasing this much memory would allow such a process to run in
+  memory.  Generally, it is worth tuning trim thresholds when a
+  program undergoes phases where several large chunks are allocated
+  and released in ways that can reuse each other's storage, perhaps
+  mixed with phases where there are no such chunks at all. The trim
+  value must be greater than page size to have any useful effect.  To
+  disable trimming completely, you can set to MAX_SIZE_T. Note that the trick
+  some people use of mallocing a huge space and then freeing it at
+  program startup, in an attempt to reserve system memory, doesn't
+  have the intended effect under automatic trimming, since that memory
+  will immediately be returned to the system.
+
+DEFAULT_MMAP_THRESHOLD       default: 256K
+      Also settable using mallopt(M_MMAP_THRESHOLD, x)
+  The request size threshold for using MMAP to directly service a
+  request. Requests of at least this size that cannot be allocated
+  using already-existing space will be serviced via mmap.  (If enough
+  normal freed space already exists it is used instead.)  Using mmap
+  segregates relatively large chunks of memory so that they can be
+  individually obtained and released from the host system. A request
+  serviced through mmap is never reused by any other request (at least
+  not directly; the system may just so happen to remap successive
+  requests to the same locations).  Segregating space in this way has
+  the benefits that: Mmapped space can always be individually released
+  back to the system, which helps keep the system level memory demands
+  of a long-lived program low.  Also, mapped memory doesn't become
+  `locked' between other chunks, as can happen with normally allocated
+  chunks, which means that even trimming via malloc_trim would not
+  release them.  However, it has the disadvantage that the space
+  cannot be reclaimed, consolidated, and then used to service later
+  requests, as happens with normal chunks.  The advantages of mmap
+  nearly always outweigh disadvantages for "large" chunks, but the
+  value of "large" may vary across systems.  The default is an
+  empirically derived value that works well in most systems. You can
+  disable mmap by setting to MAX_SIZE_T.
+
+*/
+
+#ifndef WIN32
+#ifdef _WIN32
+#define WIN32 1
+#endif  /* _WIN32 */
+#endif  /* WIN32 */
+#ifdef WIN32
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#define HAVE_MMAP 1
+#define HAVE_MORECORE 0
+#define LACKS_UNISTD_H
+#define LACKS_SYS_PARAM_H
+#define LACKS_SYS_MMAN_H
+#define LACKS_STRING_H
+#define LACKS_STRINGS_H
+#define LACKS_SYS_TYPES_H
+#define LACKS_ERRNO_H
+#define MALLOC_FAILURE_ACTION
+#define MMAP_CLEARS 0 /* WINCE and some others apparently don't clear */
+#endif  /* WIN32 */
+
+#if defined(DARWIN) || defined(_DARWIN)
+/* Mac OSX docs advise not to use sbrk; it seems better to use mmap */
+#ifndef HAVE_MORECORE
+#define HAVE_MORECORE 0
+#define HAVE_MMAP 1
+#endif  /* HAVE_MORECORE */
+#endif  /* DARWIN */
+
+#ifndef LACKS_SYS_TYPES_H
+#include <sys/types.h>  /* For size_t */
+#endif  /* LACKS_SYS_TYPES_H */
+
+/* The maximum possible size_t value has all bits set */
+#define MAX_SIZE_T           (~(size_t)0)
+
+#ifndef ONLY_MSPACES
+#define ONLY_MSPACES 0
+#endif  /* ONLY_MSPACES */
+#ifndef MSPACES
+#if ONLY_MSPACES
+#define MSPACES 1
+#else   /* ONLY_MSPACES */
+#define MSPACES 0
+#endif  /* ONLY_MSPACES */
+#endif  /* MSPACES */
+#ifndef MALLOC_ALIGNMENT
+#define MALLOC_ALIGNMENT ((size_t)8U)
+#endif  /* MALLOC_ALIGNMENT */
+#ifndef FOOTERS
+#define FOOTERS 0
+#endif  /* FOOTERS */
+#ifndef ABORT
+#define ABORT  abort()
+#endif  /* ABORT */
+#ifndef ABORT_ON_ASSERT_FAILURE
+#define ABORT_ON_ASSERT_FAILURE 1
+#endif  /* ABORT_ON_ASSERT_FAILURE */
+#ifndef PROCEED_ON_ERROR
+#define PROCEED_ON_ERROR 0
+#endif  /* PROCEED_ON_ERROR */
+#ifndef USE_LOCKS
+#define USE_LOCKS 0
+#endif  /* USE_LOCKS */
+#ifndef INSECURE
+#define INSECURE 0
+#endif  /* INSECURE */
+#ifndef HAVE_MMAP
+#define HAVE_MMAP 1
+#endif  /* HAVE_MMAP */
+#ifndef MMAP_CLEARS
+#define MMAP_CLEARS 1
+#endif  /* MMAP_CLEARS */
+#ifndef HAVE_MREMAP
+#ifdef linux
+#define HAVE_MREMAP 1
+#else   /* linux */
+#define HAVE_MREMAP 0
+#endif  /* linux */
+#endif  /* HAVE_MREMAP */
+#ifndef MALLOC_FAILURE_ACTION
+#define MALLOC_FAILURE_ACTION  errno = ENOMEM;
+#endif  /* MALLOC_FAILURE_ACTION */
+#ifndef HAVE_MORECORE
+#if ONLY_MSPACES
+#define HAVE_MORECORE 0
+#else   /* ONLY_MSPACES */
+#define HAVE_MORECORE 1
+#endif  /* ONLY_MSPACES */
+#endif  /* HAVE_MORECORE */
+#if !HAVE_MORECORE
+#define MORECORE_CONTIGUOUS 0
+#else   /* !HAVE_MORECORE */
+#ifndef MORECORE
+#define MORECORE sbrk
+#endif  /* MORECORE */
+#ifndef MORECORE_CONTIGUOUS
+#define MORECORE_CONTIGUOUS 1
+#endif  /* MORECORE_CONTIGUOUS */
+#endif  /* HAVE_MORECORE */
+#ifndef DEFAULT_GRANULARITY
+#if MORECORE_CONTIGUOUS
+#define DEFAULT_GRANULARITY (0)  /* 0 means to compute in init_mparams */
+#else   /* MORECORE_CONTIGUOUS */
+#define DEFAULT_GRANULARITY ((size_t)64U * (size_t)1024U)
+#endif  /* MORECORE_CONTIGUOUS */
+#endif  /* DEFAULT_GRANULARITY */
+#ifndef DEFAULT_TRIM_THRESHOLD
+#ifndef MORECORE_CANNOT_TRIM
+#define DEFAULT_TRIM_THRESHOLD ((size_t)2U * (size_t)1024U * (size_t)1024U)
+#else   /* MORECORE_CANNOT_TRIM */
+#define DEFAULT_TRIM_THRESHOLD MAX_SIZE_T
+#endif  /* MORECORE_CANNOT_TRIM */
+#endif  /* DEFAULT_TRIM_THRESHOLD */
+#ifndef DEFAULT_MMAP_THRESHOLD
+#if HAVE_MMAP
+#define DEFAULT_MMAP_THRESHOLD ((size_t)256U * (size_t)1024U)
+#else   /* HAVE_MMAP */
+#define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T
+#endif  /* HAVE_MMAP */
+#endif  /* DEFAULT_MMAP_THRESHOLD */
+#ifndef USE_BUILTIN_FFS
+#define USE_BUILTIN_FFS 0
+#endif  /* USE_BUILTIN_FFS */
+#ifndef USE_DEV_RANDOM
+#define USE_DEV_RANDOM 0
+#endif  /* USE_DEV_RANDOM */
+#ifndef NO_MALLINFO
+#define NO_MALLINFO 0
+#endif  /* NO_MALLINFO */
+#ifndef MALLINFO_FIELD_TYPE
+#define MALLINFO_FIELD_TYPE size_t
+#endif  /* MALLINFO_FIELD_TYPE */
+
+/*
+  mallopt tuning options.  SVID/XPG defines four standard parameter
+  numbers for mallopt, normally defined in malloc.h.  None of these
+  are used in this malloc, so setting them has no effect. But this
+  malloc does support the following options.
+*/
+
+#define M_TRIM_THRESHOLD     (-1)
+#define M_GRANULARITY        (-2)
+#define M_MMAP_THRESHOLD     (-3)
+
+/* ------------------------ Mallinfo declarations ------------------------ */
+
+#if !NO_MALLINFO
+/*
+  This version of malloc supports the standard SVID/XPG mallinfo
+  routine that returns a struct containing usage properties and
+  statistics. It should work on any system that has a
+  /usr/include/malloc.h defining struct mallinfo.  The main
+  declaration needed is the mallinfo struct that is returned (by-copy)
+  by mallinfo().  The malloinfo struct contains a bunch of fields that
+  are not even meaningful in this version of malloc.  These fields are
+  are instead filled by mallinfo() with other numbers that might be of
+  interest.
+
+  HAVE_USR_INCLUDE_MALLOC_H should be set if you have a
+  /usr/include/malloc.h file that includes a declaration of struct
+  mallinfo.  If so, it is included; else a compliant version is
+  declared below.  These must be precisely the same for mallinfo() to
+  work.  The original SVID version of this struct, defined on most
+  systems with mallinfo, declares all fields as ints. But some others
+  define as unsigned long. If your system defines the fields using a
+  type of different width than listed here, you MUST #include your
+  system version and #define HAVE_USR_INCLUDE_MALLOC_H.
+*/
+
+/* #define HAVE_USR_INCLUDE_MALLOC_H */
+
+#ifdef HAVE_USR_INCLUDE_MALLOC_H
+#include "/usr/include/malloc.h"
+#else /* HAVE_USR_INCLUDE_MALLOC_H */
+
+struct mallinfo {
+  MALLINFO_FIELD_TYPE arena;    /* non-mmapped space allocated from system */
+  MALLINFO_FIELD_TYPE ordblks;  /* number of free chunks */
+  MALLINFO_FIELD_TYPE smblks;   /* always 0 */
+  MALLINFO_FIELD_TYPE hblks;    /* always 0 */
+  MALLINFO_FIELD_TYPE hblkhd;   /* space in mmapped regions */
+  MALLINFO_FIELD_TYPE usmblks;  /* maximum total allocated space */
+  MALLINFO_FIELD_TYPE fsmblks;  /* always 0 */
+  MALLINFO_FIELD_TYPE uordblks; /* total allocated space */
+  MALLINFO_FIELD_TYPE fordblks; /* total free space */
+  MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */
+};
+
+#endif /* HAVE_USR_INCLUDE_MALLOC_H */
+#endif /* NO_MALLINFO */
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+#if !ONLY_MSPACES
+
+/* ------------------- Declarations of public routines ------------------- */
+
+#ifndef USE_DL_PREFIX
+#define dlcalloc               calloc
+#define dlfree                 free
+#define dlmalloc               malloc
+#define dlmemalign             memalign
+#define dlrealloc              realloc
+#define dlvalloc               valloc
+#define dlpvalloc              pvalloc
+#define dlmallinfo             mallinfo
+#define dlmallopt              mallopt
+#define dlmalloc_trim          malloc_trim
+#define dlmalloc_stats         malloc_stats
+#define dlmalloc_usable_size   malloc_usable_size
+#define dlmalloc_footprint     malloc_footprint
+#define dlmalloc_max_footprint malloc_max_footprint
+#define dlindependent_calloc   independent_calloc
+#define dlindependent_comalloc independent_comalloc
+#endif /* USE_DL_PREFIX */
+
+
+/*
+  malloc(size_t n)
+  Returns a pointer to a newly allocated chunk of at least n bytes, or
+  null if no space is available, in which case errno is set to ENOMEM
+  on ANSI C systems.
+
+  If n is zero, malloc returns a minimum-sized chunk. (The minimum
+  size is 16 bytes on most 32bit systems, and 32 bytes on 64bit
+  systems.)  Note that size_t is an unsigned type, so calls with
+  arguments that would be negative if signed are interpreted as
+  requests for huge amounts of space, which will often fail. The
+  maximum supported value of n differs across systems, but is in all
+  cases less than the maximum representable value of a size_t.
+*/
+void* dlmalloc(size_t);
+
+/*
+  free(void* p)
+  Releases the chunk of memory pointed to by p, that had been previously
+  allocated using malloc or a related routine such as realloc.
+  It has no effect if p is null. If p was not malloced or already
+  freed, free(p) will by default cause the current program to abort.
+*/
+void  dlfree(void*);
+
+/*
+  calloc(size_t n_elements, size_t element_size);
+  Returns a pointer to n_elements * element_size bytes, with all locations
+  set to zero.
+*/
+void* dlcalloc(size_t, size_t);
+
+/*
+  realloc(void* p, size_t n)
+  Returns a pointer to a chunk of size n that contains the same data
+  as does chunk p up to the minimum of (n, p's size) bytes, or null
+  if no space is available.
+
+  The returned pointer may or may not be the same as p. The algorithm
+  prefers extending p in most cases when possible, otherwise it
+  employs the equivalent of a malloc-copy-free sequence.
+
+  If p is null, realloc is equivalent to malloc.
+
+  If space is not available, realloc returns null, errno is set (if on
+  ANSI) and p is NOT freed.
+
+  if n is for fewer bytes than already held by p, the newly unused
+  space is lopped off and freed if possible.  realloc with a size
+  argument of zero (re)allocates a minimum-sized chunk.
+
+  The old unix realloc convention of allowing the last-free'd chunk
+  to be used as an argument to realloc is not supported.
+*/
+
+void* dlrealloc(void*, size_t);
+
+/*
+  memalign(size_t alignment, size_t n);
+  Returns a pointer to a newly allocated chunk of n bytes, aligned
+  in accord with the alignment argument.
+
+  The alignment argument should be a power of two. If the argument is
+  not a power of two, the nearest greater power is used.
+  8-byte alignment is guaranteed by normal malloc calls, so don't
+  bother calling memalign with an argument of 8 or less.
+
+  Overreliance on memalign is a sure way to fragment space.
+*/
+void* dlmemalign(size_t, size_t);
+
+/*
+  valloc(size_t n);
+  Equivalent to memalign(pagesize, n), where pagesize is the page
+  size of the system. If the pagesize is unknown, 4096 is used.
+*/
+void* dlvalloc(size_t);
+
+/*
+  mallopt(int parameter_number, int parameter_value)
+  Sets tunable parameters The format is to provide a
+  (parameter-number, parameter-value) pair.  mallopt then sets the
+  corresponding parameter to the argument value if it can (i.e., so
+  long as the value is meaningful), and returns 1 if successful else
+  0.  SVID/XPG/ANSI defines four standard param numbers for mallopt,
+  normally defined in malloc.h.  None of these are use in this malloc,
+  so setting them has no effect. But this malloc also supports other
+  options in mallopt. See below for details.  Briefly, supported
+  parameters are as follows (listed defaults are for "typical"
+  configurations).
+
+  Symbol            param #  default    allowed param values
+  M_TRIM_THRESHOLD     -1   2*1024*1024   any   (MAX_SIZE_T disables)
+  M_GRANULARITY        -2     page size   any power of 2 >= page size
+  M_MMAP_THRESHOLD     -3      256*1024   any   (or 0 if no MMAP support)
+*/
+int dlmallopt(int, int);
+
+/*
+  malloc_footprint();
+  Returns the number of bytes obtained from the system.  The total
+  number of bytes allocated by malloc, realloc etc., is less than this
+  value. Unlike mallinfo, this function returns only a precomputed
+  result, so can be called frequently to monitor memory consumption.
+  Even if locks are otherwise defined, this function does not use them,
+  so results might not be up to date.
+*/
+size_t dlmalloc_footprint(void);
+
+/*
+  malloc_max_footprint();
+  Returns the maximum number of bytes obtained from the system. This
+  value will be greater than current footprint if deallocated space
+  has been reclaimed by the system. The peak number of bytes allocated
+  by malloc, realloc etc., is less than this value. Unlike mallinfo,
+  this function returns only a precomputed result, so can be called
+  frequently to monitor memory consumption.  Even if locks are
+  otherwise defined, this function does not use them, so results might
+  not be up to date.
+*/
+size_t dlmalloc_max_footprint(void);
+
+#if !NO_MALLINFO
+/*
+  mallinfo()
+  Returns (by copy) a struct containing various summary statistics:
+
+  arena:     current total non-mmapped bytes allocated from system
+  ordblks:   the number of free chunks
+  smblks:    always zero.
+  hblks:     current number of mmapped regions
+  hblkhd:    total bytes held in mmapped regions
+  usmblks:   the maximum total allocated space. This will be greater
+                than current total if trimming has occurred.
+  fsmblks:   always zero
+  uordblks:  current total allocated space (normal or mmapped)
+  fordblks:  total free space
+  keepcost:  the maximum number of bytes that could ideally be released
+               back to system via malloc_trim. ("ideally" means that
+               it ignores page restrictions etc.)
+
+  Because these fields are ints, but internal bookkeeping may
+  be kept as longs, the reported values may wrap around zero and
+  thus be inaccurate.
+*/
+struct mallinfo dlmallinfo(void);
+#endif /* NO_MALLINFO */
+
+/*
+  independent_calloc(size_t n_elements, size_t element_size, void* chunks[]);
+
+  independent_calloc is similar to calloc, but instead of returning a
+  single cleared space, it returns an array of pointers to n_elements
+  independent elements that can hold contents of size elem_size, each
+  of which starts out cleared, and can be independently freed,
+  realloc'ed etc. The elements are guaranteed to be adjacently
+  allocated (this is not guaranteed to occur with multiple callocs or
+  mallocs), which may also improve cache locality in some
+  applications.
+
+  The "chunks" argument is optional (i.e., may be null, which is
+  probably the most typical usage). If it is null, the returned array
+  is itself dynamically allocated and should also be freed when it is
+  no longer needed. Otherwise, the chunks array must be of at least
+  n_elements in length. It is filled in with the pointers to the
+  chunks.
+
+  In either case, independent_calloc returns this pointer array, or
+  null if the allocation failed.  If n_elements is zero and "chunks"
+  is null, it returns a chunk representing an array with zero elements
+  (which should be freed if not wanted).
+
+  Each element must be individually freed when it is no longer
+  needed. If you'd like to instead be able to free all at once, you
+  should instead use regular calloc and assign pointers into this
+  space to represent elements.  (In this case though, you cannot
+  independently free elements.)
+
+  independent_calloc simplifies and speeds up implementations of many
+  kinds of pools.  It may also be useful when constructing large data
+  structures that initially have a fixed number of fixed-sized nodes,
+  but the number is not known at compile time, and some of the nodes
+  may later need to be freed. For example:
+
+  struct Node { int item; struct Node* next; };
+
+  struct Node* build_list() {
+    struct Node** pool;
+    int n = read_number_of_nodes_needed();
+    if (n <= 0) return 0;
+    pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0);
+    if (pool == 0) die();
+    // organize into a linked list...
+    struct Node* first = pool[0];
+    for (i = 0; i < n-1; ++i)
+      pool[i]->next = pool[i+1];
+    free(pool);     // Can now free the array (or not, if it is needed later)
+    return first;
+  }
+*/
+void** dlindependent_calloc(size_t, size_t, void**);
+
+/*
+  independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);
+
+  independent_comalloc allocates, all at once, a set of n_elements
+  chunks with sizes indicated in the "sizes" array.    It returns
+  an array of pointers to these elements, each of which can be
+  independently freed, realloc'ed etc. The elements are guaranteed to
+  be adjacently allocated (this is not guaranteed to occur with
+  multiple callocs or mallocs), which may also improve cache locality
+  in some applications.
+
+  The "chunks" argument is optional (i.e., may be null). If it is null
+  the returned array is itself dynamically allocated and should also
+  be freed when it is no longer needed. Otherwise, the chunks array
+  must be of at least n_elements in length. It is filled in with the
+  pointers to the chunks.
+
+  In either case, independent_comalloc returns this pointer array, or
+  null if the allocation failed.  If n_elements is zero and chunks is
+  null, it returns a chunk representing an array with zero elements
+  (which should be freed if not wanted).
+
+  Each element must be individually freed when it is no longer
+  needed. If you'd like to instead be able to free all at once, you
+  should instead use a single regular malloc, and assign pointers at
+  particular offsets in the aggregate space. (In this case though, you
+  cannot independently free elements.)
+
+  independent_comallac differs from independent_calloc in that each
+  element may have a different size, and also that it does not
+  automatically clear elements.
+
+  independent_comalloc can be used to speed up allocation in cases
+  where several structs or objects must always be allocated at the
+  same time.  For example:
+
+  struct Head { ... }
+  struct Foot { ... }
+
+  void send_message(char* msg) {
+    int msglen = strlen(msg);
+    size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) };
+    void* chunks[3];
+    if (independent_comalloc(3, sizes, chunks) == 0)
+      die();
+    struct Head* head = (struct Head*)(chunks[0]);
+    char*        body = (char*)(chunks[1]);
+    struct Foot* foot = (struct Foot*)(chunks[2]);
+    // ...
+  }
+
+  In general though, independent_comalloc is worth using only for
+  larger values of n_elements. For small values, you probably won't
+  detect enough difference from series of malloc calls to bother.
+
+  Overuse of independent_comalloc can increase overall memory usage,
+  since it cannot reuse existing noncontiguous small chunks that
+  might be available for some of the elements.
+*/
+void** dlindependent_comalloc(size_t, size_t*, void**);
+
+
+/*
+  pvalloc(size_t n);
+  Equivalent to valloc(minimum-page-that-holds(n)), that is,
+  round up n to nearest pagesize.
+ */
+void*  dlpvalloc(size_t);
+
+/*
+  malloc_trim(size_t pad);
+
+  If possible, gives memory back to the system (via negative arguments
+  to sbrk) if there is unused memory at the `high' end of the malloc
+  pool or in unused MMAP segments. You can call this after freeing
+  large blocks of memory to potentially reduce the system-level memory
+  requirements of a program. However, it cannot guarantee to reduce
+  memory. Under some allocation patterns, some large free blocks of
+  memory will be locked between two used chunks, so they cannot be
+  given back to the system.
+
+  The `pad' argument to malloc_trim represents the amount of free
+  trailing space to leave untrimmed. If this argument is zero, only
+  the minimum amount of memory to maintain internal data structures
+  will be left. Non-zero arguments can be supplied to maintain enough
+  trailing space to service future expected allocations without having
+  to re-obtain memory from the system.
+
+  Malloc_trim returns 1 if it actually released any memory, else 0.
+*/
+int  dlmalloc_trim(size_t);
+
+/*
+  malloc_usable_size(void* p);
+
+  Returns the number of bytes you can actually use in
+  an allocated chunk, which may be more than you requested (although
+  often not) due to alignment and minimum size constraints.
+  You can use this many bytes without worrying about
+  overwriting other allocated objects. This is not a particularly great
+  programming practice. malloc_usable_size can be more useful in
+  debugging and assertions, for example:
+
+  p = malloc(n);
+  assert(malloc_usable_size(p) >= 256);
+*/
+size_t dlmalloc_usable_size(void*);
+
+/*
+  malloc_stats();
+  Prints on stderr the amount of space obtained from the system (both
+  via sbrk and mmap), the maximum amount (which may be more than
+  current if malloc_trim and/or munmap got called), and the current
+  number of bytes allocated via malloc (or realloc, etc) but not yet
+  freed. Note that this is the number of bytes allocated, not the
+  number requested. It will be larger than the number requested
+  because of alignment and bookkeeping overhead. Because it includes
+  alignment wastage as being in use, this figure may be greater than
+  zero even when no user-level chunks are allocated.
+
+  The reported current and maximum system memory can be inaccurate if
+  a program makes other calls to system memory allocation functions
+  (normally sbrk) outside of malloc.
+
+  malloc_stats prints only the most commonly interesting statistics.
+  More information can be obtained by calling mallinfo.
+*/
+void  dlmalloc_stats(void);
+
+#endif /* ONLY_MSPACES */
+
+#if MSPACES
+
+/*
+  mspace is an opaque type representing an independent
+  region of space that supports mspace_malloc, etc.
+*/
+typedef void* mspace;
+
+/*
+  create_mspace creates and returns a new independent space with the
+  given initial capacity, or, if 0, the default granularity size.  It
+  returns null if there is no system memory available to create the
+  space.  If argument locked is non-zero, the space uses a separate
+  lock to control access. The capacity of the space will grow
+  dynamically as needed to service mspace_malloc requests.  You can
+  control the sizes of incremental increases of this space by
+  compiling with a different DEFAULT_GRANULARITY or dynamically
+  setting with mallopt(M_GRANULARITY, value).
+*/
+mspace create_mspace(size_t capacity, int locked);
+
+/*
+  destroy_mspace destroys the given space, and attempts to return all
+  of its memory back to the system, returning the total number of
+  bytes freed. After destruction, the results of access to all memory
+  used by the space become undefined.
+*/
+size_t destroy_mspace(mspace msp);
+
+/*
+  create_mspace_with_base uses the memory supplied as the initial base
+  of a new mspace. Part (less than 128*sizeof(size_t) bytes) of this
+  space is used for bookkeeping, so the capacity must be at least this
+  large. (Otherwise 0 is returned.) When this initial space is
+  exhausted, additional memory will be obtained from the system.
+  Destroying this space will deallocate all additionally allocated
+  space (if possible) but not the initial base.
+*/
+mspace create_mspace_with_base(void* base, size_t capacity, int locked);
+
+/*
+  mspace_malloc behaves as malloc, but operates within
+  the given space.
+*/
+void* mspace_malloc(mspace msp, size_t bytes);
+
+/*
+  mspace_free behaves as free, but operates within
+  the given space.
+
+  If compiled with FOOTERS==1, mspace_free is not actually needed.
+  free may be called instead of mspace_free because freed chunks from
+  any space are handled by their originating spaces.
+*/
+void mspace_free(mspace msp, void* mem);
+
+/*
+  mspace_realloc behaves as realloc, but operates within
+  the given space.
+
+  If compiled with FOOTERS==1, mspace_realloc is not actually
+  needed.  realloc may be called instead of mspace_realloc because
+  realloced chunks from any space are handled by their originating
+  spaces.
+*/
+void* mspace_realloc(mspace msp, void* mem, size_t newsize);
+
+/*
+  mspace_calloc behaves as calloc, but operates within
+  the given space.
+*/
+void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size);
+
+/*
+  mspace_memalign behaves as memalign, but operates within
+  the given space.
+*/
+void* mspace_memalign(mspace msp, size_t alignment, size_t bytes);
+
+/*
+  mspace_independent_calloc behaves as independent_calloc, but
+  operates within the given space.
+*/
+void** mspace_independent_calloc(mspace msp, size_t n_elements,
+                                 size_t elem_size, void* chunks[]);
+
+/*
+  mspace_independent_comalloc behaves as independent_comalloc, but
+  operates within the given space.
+*/
+void** mspace_independent_comalloc(mspace msp, size_t n_elements,
+                                   size_t sizes[], void* chunks[]);
+
+/*
+  mspace_footprint() returns the number of bytes obtained from the
+  system for this space.
+*/
+size_t mspace_footprint(mspace msp);
+
+/*
+  mspace_max_footprint() returns the peak number of bytes obtained from the
+  system for this space.
+*/
+size_t mspace_max_footprint(mspace msp);
+
+
+#if !NO_MALLINFO
+/*
+  mspace_mallinfo behaves as mallinfo, but reports properties of
+  the given space.
+*/
+struct mallinfo mspace_mallinfo(mspace msp);
+#endif /* NO_MALLINFO */
+
+/*
+  mspace_malloc_stats behaves as malloc_stats, but reports
+  properties of the given space.
+*/
+void mspace_malloc_stats(mspace msp);
+
+/*
+  mspace_trim behaves as malloc_trim, but
+  operates within the given space.
+*/
+int mspace_trim(mspace msp, size_t pad);
+
+/*
+  An alias for mallopt.
+*/
+int mspace_mallopt(int, int);
+
+#endif /* MSPACES */
+
+#ifdef __cplusplus
+};  /* end of extern "C" */
+#endif /* __cplusplus */
+
+/*
+  ========================================================================
+  To make a fully customizable malloc.h header file, cut everything
+  above this line, put into file malloc.h, edit to suit, and #include it
+  on the next line, as well as in programs that use this malloc.
+  ========================================================================
+*/
+
+/* #include "malloc.h" */
+
+/*------------------------------ internal #includes ---------------------- */
+
+#ifdef WIN32
+#pragma warning( disable : 4146 ) /* no "unsigned" warnings */
+#endif /* WIN32 */
+
+#include <stdio.h>       /* for printing in malloc_stats */
+
+#ifndef LACKS_ERRNO_H
+#include <errno.h>       /* for MALLOC_FAILURE_ACTION */
+#endif /* LACKS_ERRNO_H */
+#if FOOTERS
+#include <time.h>        /* for magic initialization */
+#endif /* FOOTERS */
+#ifndef LACKS_STDLIB_H
+#include <stdlib.h>      /* for abort() */
+#endif /* LACKS_STDLIB_H */
+#ifdef DEBUG
+#if ABORT_ON_ASSERT_FAILURE
+#define assert(x) if(!(x)) ABORT
+#else /* ABORT_ON_ASSERT_FAILURE */
+#include <assert.h>
+#endif /* ABORT_ON_ASSERT_FAILURE */
+#else  /* DEBUG */
+#define assert(x)
+#endif /* DEBUG */
+#ifndef LACKS_STRING_H
+#include <string.h>      /* for memset etc */
+#endif  /* LACKS_STRING_H */
+#if USE_BUILTIN_FFS
+#ifndef LACKS_STRINGS_H
+#include <strings.h>     /* for ffs */
+#endif /* LACKS_STRINGS_H */
+#endif /* USE_BUILTIN_FFS */
+#if HAVE_MMAP
+#ifndef LACKS_SYS_MMAN_H
+#include <sys/mman.h>    /* for mmap */
+#endif /* LACKS_SYS_MMAN_H */
+#ifndef LACKS_FCNTL_H
+#include <fcntl.h>
+#endif /* LACKS_FCNTL_H */
+#endif /* HAVE_MMAP */
+#if HAVE_MORECORE
+#ifndef LACKS_UNISTD_H
+#include <unistd.h>     /* for sbrk */
+#else /* LACKS_UNISTD_H */
+#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
+extern void*     sbrk(ptrdiff_t);
+#endif /* FreeBSD etc */
+#endif /* LACKS_UNISTD_H */
+#endif /* HAVE_MMAP */
+
+#ifndef WIN32
+#ifndef malloc_getpagesize
+#  ifdef _SC_PAGESIZE         /* some SVR4 systems omit an underscore */
+#    ifndef _SC_PAGE_SIZE
+#      define _SC_PAGE_SIZE _SC_PAGESIZE
+#    endif
+#  endif
+#  ifdef _SC_PAGE_SIZE
+#    define malloc_getpagesize sysconf(_SC_PAGE_SIZE)
+#  else
+#    if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE)
+       extern size_t getpagesize();
+#      define malloc_getpagesize getpagesize()
+#    else
+#      ifdef WIN32 /* use supplied emulation of getpagesize */
+#        define malloc_getpagesize getpagesize()
+#      else
+#        ifndef LACKS_SYS_PARAM_H
+#          include <sys/param.h>
+#        endif
+#        ifdef EXEC_PAGESIZE
+#          define malloc_getpagesize EXEC_PAGESIZE
+#        else
+#          ifdef NBPG
+#            ifndef CLSIZE
+#              define malloc_getpagesize NBPG
+#            else
+#              define malloc_getpagesize (NBPG * CLSIZE)
+#            endif
+#          else
+#            ifdef NBPC
+#              define malloc_getpagesize NBPC
+#            else
+#              ifdef PAGESIZE
+#                define malloc_getpagesize PAGESIZE
+#              else /* just guess */
+#                define malloc_getpagesize ((size_t)4096U)
+#              endif
+#            endif
+#          endif
+#        endif
+#      endif
+#    endif
+#  endif
+#endif
+#endif
+
+/* ------------------- size_t and alignment properties -------------------- */
+
+/* The byte and bit size of a size_t */
+#define SIZE_T_SIZE         (sizeof(size_t))
+#define SIZE_T_BITSIZE      (sizeof(size_t) << 3)
+
+/* Some constants coerced to size_t */
+/* Annoying but necessary to avoid errors on some plaftorms */
+#define SIZE_T_ZERO         ((size_t)0)
+#define SIZE_T_ONE          ((size_t)1)
+#define SIZE_T_TWO          ((size_t)2)
+#define TWO_SIZE_T_SIZES    (SIZE_T_SIZE<<1)
+#define FOUR_SIZE_T_SIZES   (SIZE_T_SIZE<<2)
+#define SIX_SIZE_T_SIZES    (FOUR_SIZE_T_SIZES+TWO_SIZE_T_SIZES)
+#define HALF_MAX_SIZE_T     (MAX_SIZE_T / 2U)
+
+/* The bit mask value corresponding to MALLOC_ALIGNMENT */
+#define CHUNK_ALIGN_MASK    (MALLOC_ALIGNMENT - SIZE_T_ONE)
+
+/* True if address a has acceptable alignment */
+#define is_aligned(A)       (((size_t)((A)) & (CHUNK_ALIGN_MASK)) == 0)
+
+/* the number of bytes to offset an address to align it */
+#define align_offset(A)\
+ ((((size_t)(A) & CHUNK_ALIGN_MASK) == 0)? 0 :\
+  ((MALLOC_ALIGNMENT - ((size_t)(A) & CHUNK_ALIGN_MASK)) & CHUNK_ALIGN_MASK))
+
+/* -------------------------- MMAP preliminaries ------------------------- */
+
+/*
+   If HAVE_MORECORE or HAVE_MMAP are false, we just define calls and
+   checks to fail so compiler optimizer can delete code rather than
+   using so many "#if"s.
+*/
+
+
+/* MORECORE and MMAP must return MFAIL on failure */
+#define MFAIL                ((void*)(MAX_SIZE_T))
+#define CMFAIL               ((char*)(MFAIL)) /* defined for convenience */
+
+#if !HAVE_MMAP
+#define IS_MMAPPED_BIT       (SIZE_T_ZERO)
+#define USE_MMAP_BIT         (SIZE_T_ZERO)
+#define CALL_MMAP(s)         MFAIL
+#define CALL_MUNMAP(a, s)    (-1)
+#define DIRECT_MMAP(s)       MFAIL
+
+#else /* HAVE_MMAP */
+#define IS_MMAPPED_BIT       (SIZE_T_ONE)
+#define USE_MMAP_BIT         (SIZE_T_ONE)
+
+#ifndef WIN32
+#define CALL_MUNMAP(a, s)    munmap((a), (s))
+#define MMAP_PROT            (PROT_READ|PROT_WRITE)
+#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
+#define MAP_ANONYMOUS        MAP_ANON
+#endif /* MAP_ANON */
+#ifdef MAP_ANONYMOUS
+#define MMAP_FLAGS           (MAP_PRIVATE|MAP_ANONYMOUS)
+#define CALL_MMAP(s)         mmap(0, (s), MMAP_PROT, MMAP_FLAGS, -1, 0)
+#else /* MAP_ANONYMOUS */
+/*
+   Nearly all versions of mmap support MAP_ANONYMOUS, so the following
+   is unlikely to be needed, but is supplied just in case.
+*/
+#define MMAP_FLAGS           (MAP_PRIVATE)
+static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */
+#define CALL_MMAP(s) ((dev_zero_fd < 0) ? \
+           (dev_zero_fd = open("/dev/zero", O_RDWR), \
+            mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) : \
+            mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0))
+#endif /* MAP_ANONYMOUS */
+
+#define DIRECT_MMAP(s)       CALL_MMAP(s)
+#else /* WIN32 */
+
+/* Win32 MMAP via VirtualAlloc */
+static void* win32mmap(size_t size) {
+  void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
+  return (ptr != 0)? ptr: MFAIL;
+}
+
+/* For direct MMAP, use MEM_TOP_DOWN to minimize interference */
+static void* win32direct_mmap(size_t size) {
+  void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN,
+                           PAGE_READWRITE);
+  return (ptr != 0)? ptr: MFAIL;
+}
+
+/* This function supports releasing coalesed segments */
+static int win32munmap(void* ptr, size_t size) {
+  MEMORY_BASIC_INFORMATION minfo;
+  char* cptr = ptr;
+  while (size) {
+    if (VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0)
+      return -1;
+    if (minfo.BaseAddress != cptr || minfo.AllocationBase != cptr ||
+        minfo.State != MEM_COMMIT || minfo.RegionSize > size)
+      return -1;
+    if (VirtualFree(cptr, 0, MEM_RELEASE) == 0)
+      return -1;
+    cptr += minfo.RegionSize;
+    size -= minfo.RegionSize;
+  }
+  return 0;
+}
+
+#define CALL_MMAP(s)         win32mmap(s)
+#define CALL_MUNMAP(a, s)    win32munmap((a), (s))
+#define DIRECT_MMAP(s)       win32direct_mmap(s)
+#endif /* WIN32 */
+#endif /* HAVE_MMAP */
+
+#if HAVE_MMAP && HAVE_MREMAP
+#define CALL_MREMAP(addr, osz, nsz, mv) mremap((addr), (osz), (nsz), (mv))
+#else  /* HAVE_MMAP && HAVE_MREMAP */
+#define CALL_MREMAP(addr, osz, nsz, mv) MFAIL
+#endif /* HAVE_MMAP && HAVE_MREMAP */
+
+#if HAVE_MORECORE
+#define CALL_MORECORE(S)     MORECORE(S)
+#else  /* HAVE_MORECORE */
+#define CALL_MORECORE(S)     MFAIL
+#endif /* HAVE_MORECORE */
+
+/* mstate bit set if continguous morecore disabled or failed */
+#define USE_NONCONTIGUOUS_BIT (4U)
+
+/* segment bit set in create_mspace_with_base */
+#define EXTERN_BIT            (8U)
+
+
+/* --------------------------- Lock preliminaries ------------------------ */
+
+#if USE_LOCKS
+
+/*
+  When locks are defined, there are up to two global locks:
+
+  * If HAVE_MORECORE, morecore_mutex protects sequences of calls to
+    MORECORE.  In many cases sys_alloc requires two calls, that should
+    not be interleaved with calls by other threads.  This does not
+    protect against direct calls to MORECORE by other threads not
+    using this lock, so there is still code to cope the best we can on
+    interference.
+
+  * magic_init_mutex ensures that mparams.magic and other
+    unique mparams values are initialized only once.
+*/
+
+#ifndef WIN32
+/* By default use posix locks */
+#include <pthread.h>
+#define MLOCK_T pthread_mutex_t
+#define INITIAL_LOCK(l)      pthread_mutex_init(l, NULL)
+#define ACQUIRE_LOCK(l)      pthread_mutex_lock(l)
+#define RELEASE_LOCK(l)      pthread_mutex_unlock(l)
+
+#if HAVE_MORECORE
+static MLOCK_T morecore_mutex = PTHREAD_MUTEX_INITIALIZER;
+#endif /* HAVE_MORECORE */
+
+static MLOCK_T magic_init_mutex = PTHREAD_MUTEX_INITIALIZER;
+
+#else /* WIN32 */
+/*
+   Because lock-protected regions have bounded times, and there
+   are no recursive lock calls, we can use simple spinlocks.
+*/
+
+#define MLOCK_T long
+static int win32_acquire_lock (MLOCK_T *sl) {
+  for (;;) {
+#ifdef InterlockedCompareExchangePointer
+    if (!InterlockedCompareExchange(sl, 1, 0))
+      return 0;
+#else  /* Use older void* version */
+    if (!InterlockedCompareExchange((void**)sl, (void*)1, (void*)0))
+      return 0;
+#endif /* InterlockedCompareExchangePointer */
+    Sleep (0);
+  }
+}
+
+static void win32_release_lock (MLOCK_T *sl) {
+  InterlockedExchange (sl, 0);
+}
+
+#define INITIAL_LOCK(l)      *(l)=0
+#define ACQUIRE_LOCK(l)      win32_acquire_lock(l)
+#define RELEASE_LOCK(l)      win32_release_lock(l)
+#if HAVE_MORECORE
+static MLOCK_T morecore_mutex;
+#endif /* HAVE_MORECORE */
+static MLOCK_T magic_init_mutex;
+#endif /* WIN32 */
+
+#define USE_LOCK_BIT               (2U)
+#else  /* USE_LOCKS */
+#define USE_LOCK_BIT               (0U)
+#define INITIAL_LOCK(l)
+#endif /* USE_LOCKS */
+
+#if USE_LOCKS && HAVE_MORECORE
+#define ACQUIRE_MORECORE_LOCK()    ACQUIRE_LOCK(&morecore_mutex);
+#define RELEASE_MORECORE_LOCK()    RELEASE_LOCK(&morecore_mutex);
+#else /* USE_LOCKS && HAVE_MORECORE */
+#define ACQUIRE_MORECORE_LOCK()
+#define RELEASE_MORECORE_LOCK()
+#endif /* USE_LOCKS && HAVE_MORECORE */
+
+#if USE_LOCKS
+#define ACQUIRE_MAGIC_INIT_LOCK()  ACQUIRE_LOCK(&magic_init_mutex);
+#define RELEASE_MAGIC_INIT_LOCK()  RELEASE_LOCK(&magic_init_mutex);
+#else  /* USE_LOCKS */
+#define ACQUIRE_MAGIC_INIT_LOCK()
+#define RELEASE_MAGIC_INIT_LOCK()
+#endif /* USE_LOCKS */
+
+
+/* -----------------------  Chunk representations ------------------------ */
+
+/*
+  (The following includes lightly edited explanations by Colin Plumb.)
+
+  The malloc_chunk declaration below is misleading (but accurate and
+  necessary).  It declares a "view" into memory allowing access to
+  necessary fields at known offsets from a given base.
+
+  Chunks of memory are maintained using a `boundary tag' method as
+  originally described by Knuth.  (See the paper by Paul Wilson
+  ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a survey of such
+  techniques.)  Sizes of free chunks are stored both in the front of
+  each chunk and at the end.  This makes consolidating fragmented
+  chunks into bigger chunks fast.  The head fields also hold bits
+  representing whether chunks are free or in use.
+
+  Here are some pictures to make it clearer.  They are "exploded" to
+  show that the state of a chunk can be thought of as extending from
+  the high 31 bits of the head field of its header through the
+  prev_foot and PINUSE_BIT bit of the following chunk header.
+
+  A chunk that's in use looks like:
+
+   chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+           | Size of previous chunk (if P = 1)                             |
+           +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+         +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|
+         | Size of this chunk                                         1| +-+
+   mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+         |                                                               |
+         +-                                                             -+
+         |                                                               |
+         +-                                                             -+
+         |                                                               :
+         +-      size - sizeof(size_t) available payload bytes          -+
+         :                                                               |
+ chunk-> +-                                                             -+
+         |                                                               |
+         +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1|
+       | Size of next chunk (may or may not be in use)               | +-+
+ mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+
+    And if it's free, it looks like this:
+
+   chunk-> +-                                                             -+
+           | User payload (must be in use, or we would have merged!)       |
+           +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+         +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|
+         | Size of this chunk                                         0| +-+
+   mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+         | Next pointer                                                  |
+         +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+         | Prev pointer                                                  |
+         +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+         |                                                               :
+         +-      size - sizeof(struct chunk) unused bytes               -+
+         :                                                               |
+ chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+         | Size of this chunk                                            |
+         +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0|
+       | Size of next chunk (must be in use, or we would have merged)| +-+
+ mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+       |                                                               :
+       +- User payload                                                -+
+       :                                                               |
+       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+                                                                     |0|
+                                                                     +-+
+  Note that since we always merge adjacent free chunks, the chunks
+  adjacent to a free chunk must be in use.
+
+  Given a pointer to a chunk (which can be derived trivially from the
+  payload pointer) we can, in O(1) time, find out whether the adjacent
+  chunks are free, and if so, unlink them from the lists that they
+  are on and merge them with the current chunk.
+
+  Chunks always begin on even word boundaries, so the mem portion
+  (which is returned to the user) is also on an even word boundary, and
+  thus at least double-word aligned.
+
+  The P (PINUSE_BIT) bit, stored in the unused low-order bit of the
+  chunk size (which is always a multiple of two words), is an in-use
+  bit for the *previous* chunk.  If that bit is *clear*, then the
+  word before the current chunk size contains the previous chunk
+  size, and can be used to find the front of the previous chunk.
+  The very first chunk allocated always has this bit set, preventing
+  access to non-existent (or non-owned) memory. If pinuse is set for
+  any given chunk, then you CANNOT determine the size of the
+  previous chunk, and might even get a memory addressing fault when
+  trying to do so.
+
+  The C (CINUSE_BIT) bit, stored in the unused second-lowest bit of
+  the chunk size redundantly records whether the current chunk is
+  inuse. This redundancy enables usage checks within free and realloc,
+  and reduces indirection when freeing and consolidating chunks.
+
+  Each freshly allocated chunk must have both cinuse and pinuse set.
+  That is, each allocated chunk borders either a previously allocated
+  and still in-use chunk, or the base of its memory arena. This is
+  ensured by making all allocations from the the `lowest' part of any
+  found chunk.  Further, no free chunk physically borders another one,
+  so each free chunk is known to be preceded and followed by either
+  inuse chunks or the ends of memory.
+
+  Note that the `foot' of the current chunk is actually represented
+  as the prev_foot of the NEXT chunk. This makes it easier to
+  deal with alignments etc but can be very confusing when trying
+  to extend or adapt this code.
+
+  The exceptions to all this are
+
+     1. The special chunk `top' is the top-most available chunk (i.e.,
+        the one bordering the end of available memory). It is treated
+        specially.  Top is never included in any bin, is used only if
+        no other chunk is available, and is released back to the
+        system if it is very large (see M_TRIM_THRESHOLD).  In effect,
+        the top chunk is treated as larger (and thus less well
+        fitting) than any other available chunk.  The top chunk
+        doesn't update its trailing size field since there is no next
+        contiguous chunk that would have to index off it. However,
+        space is still allocated for it (TOP_FOOT_SIZE) to enable
+        separation or merging when space is extended.
+
+     3. Chunks allocated via mmap, which have the lowest-order bit
+        (IS_MMAPPED_BIT) set in their prev_foot fields, and do not set
+        PINUSE_BIT in their head fields.  Because they are allocated
+        one-by-one, each must carry its own prev_foot field, which is
+        also used to hold the offset this chunk has within its mmapped
+        region, which is needed to preserve alignment. Each mmapped
+        chunk is trailed by the first two fields of a fake next-chunk
+        for sake of usage checks.
+
+*/
+
+struct malloc_chunk {
+  size_t               prev_foot;  /* Size of previous chunk (if free).  */
+  size_t               head;       /* Size and inuse bits. */
+  struct malloc_chunk* fd;         /* double links -- used only if free. */
+  struct malloc_chunk* bk;
+};
+
+typedef struct malloc_chunk  mchunk;
+typedef struct malloc_chunk* mchunkptr;
+typedef struct malloc_chunk* sbinptr;  /* The type of bins of chunks */
+typedef unsigned int bindex_t;         /* Described below */
+typedef unsigned int binmap_t;         /* Described below */
+typedef unsigned int flag_t;           /* The type of various bit flag sets */
+
+/* ------------------- Chunks sizes and alignments ----------------------- */
+
+#define MCHUNK_SIZE         (sizeof(mchunk))
+
+#if FOOTERS
+#define CHUNK_OVERHEAD      (TWO_SIZE_T_SIZES)
+#else /* FOOTERS */
+#define CHUNK_OVERHEAD      (SIZE_T_SIZE)
+#endif /* FOOTERS */
+
+/* MMapped chunks need a second word of overhead ... */
+#define MMAP_CHUNK_OVERHEAD (TWO_SIZE_T_SIZES)
+/* ... and additional padding for fake next-chunk at foot */
+#define MMAP_FOOT_PAD       (FOUR_SIZE_T_SIZES)
+
+/* The smallest size we can malloc is an aligned minimal chunk */
+#define MIN_CHUNK_SIZE\
+  ((MCHUNK_SIZE + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
+
+/* conversion from malloc headers to user pointers, and back */
+#define chunk2mem(p)        ((void*)((char*)(p)       + TWO_SIZE_T_SIZES))
+#define mem2chunk(mem)      ((mchunkptr)((char*)(mem) - TWO_SIZE_T_SIZES))
+/* chunk associated with aligned address A */
+#define align_as_chunk(A)   (mchunkptr)((A) + align_offset(chunk2mem(A)))
+
+/* Bounds on request (not chunk) sizes. */
+#define MAX_REQUEST         ((-MIN_CHUNK_SIZE) << 2)
+#define MIN_REQUEST         (MIN_CHUNK_SIZE - CHUNK_OVERHEAD - SIZE_T_ONE)
+
+/* pad request bytes into a usable size */
+#define pad_request(req) \
+   (((req) + CHUNK_OVERHEAD + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
+
+/* pad request, checking for minimum (but not maximum) */
+#define request2size(req) \
+  (((req) < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(req))
+
+
+/* ------------------ Operations on head and foot fields ----------------- */
+
+/*
+  The head field of a chunk is or'ed with PINUSE_BIT when previous
+  adjacent chunk in use, and or'ed with CINUSE_BIT if this chunk is in
+  use. If the chunk was obtained with mmap, the prev_foot field has
+  IS_MMAPPED_BIT set, otherwise holding the offset of the base of the
+  mmapped region to the base of the chunk.
+*/
+
+#define PINUSE_BIT          (SIZE_T_ONE)
+#define CINUSE_BIT          (SIZE_T_TWO)
+#define INUSE_BITS          (PINUSE_BIT|CINUSE_BIT)
+
+/* Head value for fenceposts */
+#define FENCEPOST_HEAD      (INUSE_BITS|SIZE_T_SIZE)
+
+/* extraction of fields from head words */
+#define cinuse(p)           ((p)->head & CINUSE_BIT)
+#define pinuse(p)           ((p)->head & PINUSE_BIT)
+#define chunksize(p)        ((p)->head & ~(INUSE_BITS))
+
+#define clear_pinuse(p)     ((p)->head &= ~PINUSE_BIT)
+#define clear_cinuse(p)     ((p)->head &= ~CINUSE_BIT)
+
+/* Treat space at ptr +/- offset as a chunk */
+#define chunk_plus_offset(p, s)  ((mchunkptr)(((char*)(p)) + (s)))
+#define chunk_minus_offset(p, s) ((mchunkptr)(((char*)(p)) - (s)))
+
+/* Ptr to next or previous physical malloc_chunk. */
+#define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->head & ~INUSE_BITS)))
+#define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_foot) ))
+
+/* extract next chunk's pinuse bit */
+#define next_pinuse(p)  ((next_chunk(p)->head) & PINUSE_BIT)
+
+/* Get/set size at footer */
+#define get_foot(p, s)  (((mchunkptr)((char*)(p) + (s)))->prev_foot)
+#define set_foot(p, s)  (((mchunkptr)((char*)(p) + (s)))->prev_foot = (s))
+
+/* Set size, pinuse bit, and foot */
+#define set_size_and_pinuse_of_free_chunk(p, s)\
+  ((p)->head = (s|PINUSE_BIT), set_foot(p, s))
+
+/* Set size, pinuse bit, foot, and clear next pinuse */
+#define set_free_with_pinuse(p, s, n)\
+  (clear_pinuse(n), set_size_and_pinuse_of_free_chunk(p, s))
+
+#define is_mmapped(p)\
+  (!((p)->head & PINUSE_BIT) && ((p)->prev_foot & IS_MMAPPED_BIT))
+
+/* Get the internal overhead associated with chunk p */
+#define overhead_for(p)\
+ (is_mmapped(p)? MMAP_CHUNK_OVERHEAD : CHUNK_OVERHEAD)
+
+/* Return true if malloced space is not necessarily cleared */
+#if MMAP_CLEARS
+#define calloc_must_clear(p) (!is_mmapped(p))
+#else /* MMAP_CLEARS */
+#define calloc_must_clear(p) (1)
+#endif /* MMAP_CLEARS */
+
+/* ---------------------- Overlaid data structures ----------------------- */
+
+/*
+  When chunks are not in use, they are treated as nodes of either
+  lists or trees.
+
+  "Small"  chunks are stored in circular doubly-linked lists, and look
+  like this:
+
+    chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |             Size of previous chunk                            |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+    `head:' |             Size of chunk, in bytes                         |P|
+      mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |             Forward pointer to next chunk in list             |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |             Back pointer to previous chunk in list            |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |             Unused space (may be 0 bytes long)                .
+            .                                                               .
+            .                                                               |
+nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+    `foot:' |             Size of chunk, in bytes                           |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+
+  Larger chunks are kept in a form of bitwise digital trees (aka
+  tries) keyed on chunksizes.  Because malloc_tree_chunks are only for
+  free chunks greater than 256 bytes, their size doesn't impose any
+  constraints on user chunk sizes.  Each node looks like:
+
+    chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |             Size of previous chunk                            |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+    `head:' |             Size of chunk, in bytes                         |P|
+      mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |             Forward pointer to next chunk of same size        |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |             Back pointer to previous chunk of same size       |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |             Pointer to left child (child[0])                  |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |             Pointer to right child (child[1])                 |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |             Pointer to parent                                 |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |             bin index of this chunk                           |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |             Unused space                                      .
+            .                                                               |
+nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+    `foot:' |             Size of chunk, in bytes                           |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+
+  Each tree holding treenodes is a tree of unique chunk sizes.  Chunks
+  of the same size are arranged in a circularly-linked list, with only
+  the oldest chunk (the next to be used, in our FIFO ordering)
+  actually in the tree.  (Tree members are distinguished by a non-null
+  parent pointer.)  If a chunk with the same size an an existing node
+  is inserted, it is linked off the existing node using pointers that
+  work in the same way as fd/bk pointers of small chunks.
+
+  Each tree contains a power of 2 sized range of chunk sizes (the
+  smallest is 0x100 <= x < 0x180), which is is divided in half at each
+  tree level, with the chunks in the smaller half of the range (0x100
+  <= x < 0x140 for the top nose) in the left subtree and the larger
+  half (0x140 <= x < 0x180) in the right subtree.  This is, of course,
+  done by inspecting individual bits.
+
+  Using these rules, each node's left subtree contains all smaller
+  sizes than its right subtree.  However, the node at the root of each
+  subtree has no particular ordering relationship to either.  (The
+  dividing line between the subtree sizes is based on trie relation.)
+  If we remove the last chunk of a given size from the interior of the
+  tree, we need to replace it with a leaf node.  The tree ordering
+  rules permit a node to be replaced by any leaf below it.
+
+  The smallest chunk in a tree (a common operation in a best-fit
+  allocator) can be found by walking a path to the leftmost leaf in
+  the tree.  Unlike a usual binary tree, where we follow left child
+  pointers until we reach a null, here we follow the right child
+  pointer any time the left one is null, until we reach a leaf with
+  both child pointers null. The smallest chunk in the tree will be
+  somewhere along that path.
+
+  The worst case number of steps to add, find, or remove a node is
+  bounded by the number of bits differentiating chunks within
+  bins. Under current bin calculations, this ranges from 6 up to 21
+  (for 32 bit sizes) or up to 53 (for 64 bit sizes). The typical case
+  is of course much better.
+*/
+
+struct malloc_tree_chunk {
+  /* The first four fields must be compatible with malloc_chunk */
+  size_t                    prev_foot;
+  size_t                    head;
+  struct malloc_tree_chunk* fd;
+  struct malloc_tree_chunk* bk;
+
+  struct malloc_tree_chunk* child[2];
+  struct malloc_tree_chunk* parent;
+  bindex_t                  index;
+};
+
+typedef struct malloc_tree_chunk  tchunk;
+typedef struct malloc_tree_chunk* tchunkptr;
+typedef struct malloc_tree_chunk* tbinptr; /* The type of bins of trees */
+
+/* A little helper macro for trees */
+#define leftmost_child(t) ((t)->child[0] != 0? (t)->child[0] : (t)->child[1])
+
+/* ----------------------------- Segments -------------------------------- */
+
+/*
+  Each malloc space may include non-contiguous segments, held in a
+  list headed by an embedded malloc_segment record representing the
+  top-most space. Segments also include flags holding properties of
+  the space. Large chunks that are directly allocated by mmap are not
+  included in this list. They are instead independently created and
+  destroyed without otherwise keeping track of them.
+
+  Segment management mainly comes into play for spaces allocated by
+  MMAP.  Any call to MMAP might or might not return memory that is
+  adjacent to an existing segment.  MORECORE normally contiguously
+  extends the current space, so this space is almost always adjacent,
+  which is simpler and faster to deal with. (This is why MORECORE is
+  used preferentially to MMAP when both are available -- see
+  sys_alloc.)  When allocating using MMAP, we don't use any of the
+  hinting mechanisms (inconsistently) supported in various
+  implementations of unix mmap, or distinguish reserving from
+  committing memory. Instead, we just ask for space, and exploit
+  contiguity when we get it.  It is probably possible to do
+  better than this on some systems, but no general scheme seems
+  to be significantly better.
+
+  Management entails a simpler variant of the consolidation scheme
+  used for chunks to reduce fragmentation -- new adjacent memory is
+  normally prepended or appended to an existing segment. However,
+  there are limitations compared to chunk consolidation that mostly
+  reflect the fact that segment processing is relatively infrequent
+  (occurring only when getting memory from system) and that we
+  don't expect to have huge numbers of segments:
+
+  * Segments are not indexed, so traversal requires linear scans.  (It
+    would be possible to index these, but is not worth the extra
+    overhead and complexity for most programs on most platforms.)
+  * New segments are only appended to old ones when holding top-most
+    memory; if they cannot be prepended to others, they are held in
+    different segments.
+
+  Except for the top-most segment of an mstate, each segment record
+  is kept at the tail of its segment. Segments are added by pushing
+  segment records onto the list headed by &mstate.seg for the
+  containing mstate.
+
+  Segment flags control allocation/merge/deallocation policies:
+  * If EXTERN_BIT set, then we did not allocate this segment,
+    and so should not try to deallocate or merge with others.
+    (This currently holds only for the initial segment passed
+    into create_mspace_with_base.)
+  * If IS_MMAPPED_BIT set, the segment may be merged with
+    other surrounding mmapped segments and trimmed/de-allocated
+    using munmap.
+  * If neither bit is set, then the segment was obtained using
+    MORECORE so can be merged with surrounding MORECORE'd segments
+    and deallocated/trimmed using MORECORE with negative arguments.
+*/
+
+struct malloc_segment {
+  char*        base;             /* base address */
+  size_t       size;             /* allocated size */
+  struct malloc_segment* next;   /* ptr to next segment */
+  flag_t       sflags;           /* mmap and extern flag */
+};
+
+#define is_mmapped_segment(S)  ((S)->sflags & IS_MMAPPED_BIT)
+#define is_extern_segment(S)   ((S)->sflags & EXTERN_BIT)
+
+typedef struct malloc_segment  msegment;
+typedef struct malloc_segment* msegmentptr;
+
+/* ---------------------------- malloc_state ----------------------------- */
+
+/*
+   A malloc_state holds all of the bookkeeping for a space.
+   The main fields are:
+
+  Top
+    The topmost chunk of the currently active segment. Its size is
+    cached in topsize.  The actual size of topmost space is
+    topsize+TOP_FOOT_SIZE, which includes space reserved for adding
+    fenceposts and segment records if necessary when getting more
+    space from the system.  The size at which to autotrim top is
+    cached from mparams in trim_check, except that it is disabled if
+    an autotrim fails.
+
+  Designated victim (dv)
+    This is the preferred chunk for servicing small requests that
+    don't have exact fits.  It is normally the chunk split off most
+    recently to service another small request.  Its size is cached in
+    dvsize. The link fields of this chunk are not maintained since it
+    is not kept in a bin.
+
+  SmallBins
+    An array of bin headers for free chunks.  These bins hold chunks
+    with sizes less than MIN_LARGE_SIZE bytes. Each bin contains
+    chunks of all the same size, spaced 8 bytes apart.  To simplify
+    use in double-linked lists, each bin header acts as a malloc_chunk
+    pointing to the real first node, if it exists (else pointing to
+    itself).  This avoids special-casing for headers.  But to avoid
+    waste, we allocate only the fd/bk pointers of bins, and then use
+    repositioning tricks to treat these as the fields of a chunk.
+
+  TreeBins
+    Treebins are pointers to the roots of trees holding a range of
+    sizes. There are 2 equally spaced treebins for each power of two
+    from TREE_SHIFT to TREE_SHIFT+16. The last bin holds anything
+    larger.
+
+  Bin maps
+    There is one bit map for small bins ("smallmap") and one for
+    treebins ("treemap).  Each bin sets its bit when non-empty, and
+    clears the bit when empty.  Bit operations are then used to avoid
+    bin-by-bin searching -- nearly all "search" is done without ever
+    looking at bins that won't be selected.  The bit maps
+    conservatively use 32 bits per map word, even if on 64bit system.
+    For a good description of some of the bit-based techniques used
+    here, see Henry S. Warren Jr's book "Hacker's Delight" (and
+    supplement at http://hackersdelight.org/). Many of these are
+    intended to reduce the branchiness of paths through malloc etc, as
+    well as to reduce the number of memory locations read or written.
+
+  Segments
+    A list of segments headed by an embedded malloc_segment record
+    representing the initial space.
+
+  Address check support
+    The least_addr field is the least address ever obtained from
+    MORECORE or MMAP. Attempted frees and reallocs of any address less
+    than this are trapped (unless INSECURE is defined).
+
+  Magic tag
+    A cross-check field that should always hold same value as mparams.magic.
+
+  Flags
+    Bits recording whether to use MMAP, locks, or contiguous MORECORE
+
+  Statistics
+    Each space keeps track of current and maximum system memory
+    obtained via MORECORE or MMAP.
+
+  Locking
+    If USE_LOCKS is defined, the "mutex" lock is acquired and released
+    around every public call using this mspace.
+*/
+
+/* Bin types, widths and sizes */
+#define NSMALLBINS        (32U)
+#define NTREEBINS         (32U)
+#define SMALLBIN_SHIFT    (3U)
+#define SMALLBIN_WIDTH    (SIZE_T_ONE << SMALLBIN_SHIFT)
+#define TREEBIN_SHIFT     (8U)
+#define MIN_LARGE_SIZE    (SIZE_T_ONE << TREEBIN_SHIFT)
+#define MAX_SMALL_SIZE    (MIN_LARGE_SIZE - SIZE_T_ONE)
+#define MAX_SMALL_REQUEST (MAX_SMALL_SIZE - CHUNK_ALIGN_MASK - CHUNK_OVERHEAD)
+
+struct malloc_state {
+  binmap_t   smallmap;
+  binmap_t   treemap;
+  size_t     dvsize;
+  size_t     topsize;
+  char*      least_addr;
+  mchunkptr  dv;
+  mchunkptr  top;
+  size_t     trim_check;
+  size_t     magic;
+  mchunkptr  smallbins[(NSMALLBINS+1)*2];
+  tbinptr    treebins[NTREEBINS];
+  size_t     footprint;
+  size_t     max_footprint;
+  flag_t     mflags;
+#if USE_LOCKS
+  MLOCK_T    mutex;     /* locate lock among fields that rarely change */
+#endif /* USE_LOCKS */
+  msegment   seg;
+};
+
+typedef struct malloc_state*    mstate;
+
+/* ------------- Global malloc_state and malloc_params ------------------- */
+
+/*
+  malloc_params holds global properties, including those that can be
+  dynamically set using mallopt. There is a single instance, mparams,
+  initialized in init_mparams.
+*/
+
+struct malloc_params {
+  size_t magic;
+  size_t page_size;
+  size_t granularity;
+  size_t mmap_threshold;
+  size_t trim_threshold;
+  flag_t default_mflags;
+};
+
+static struct malloc_params mparams;
+
+/* The global malloc_state used for all non-"mspace" calls */
+static struct malloc_state _gm_;
+#define gm                 (&_gm_)
+#define is_global(M)       ((M) == &_gm_)
+#define is_initialized(M)  ((M)->top != 0)
+
+/* -------------------------- system alloc setup ------------------------- */
+
+/* Operations on mflags */
+
+#define use_lock(M)           ((M)->mflags &   USE_LOCK_BIT)
+#define enable_lock(M)        ((M)->mflags |=  USE_LOCK_BIT)
+#define disable_lock(M)       ((M)->mflags &= ~USE_LOCK_BIT)
+
+#define use_mmap(M)           ((M)->mflags &   USE_MMAP_BIT)
+#define enable_mmap(M)        ((M)->mflags |=  USE_MMAP_BIT)
+#define disable_mmap(M)       ((M)->mflags &= ~USE_MMAP_BIT)
+
+#define use_noncontiguous(M)  ((M)->mflags &   USE_NONCONTIGUOUS_BIT)
+#define disable_contiguous(M) ((M)->mflags |=  USE_NONCONTIGUOUS_BIT)
+
+#define set_lock(M,L)\
+ ((M)->mflags = (L)?\
+  ((M)->mflags | USE_LOCK_BIT) :\
+  ((M)->mflags & ~USE_LOCK_BIT))
+
+/* page-align a size */
+#define page_align(S)\
+ (((S) + (mparams.page_size)) & ~(mparams.page_size - SIZE_T_ONE))
+
+/* granularity-align a size */
+#define granularity_align(S)\
+  (((S) + (mparams.granularity)) & ~(mparams.granularity - SIZE_T_ONE))
+
+#define is_page_aligned(S)\
+   (((size_t)(S) & (mparams.page_size - SIZE_T_ONE)) == 0)
+#define is_granularity_aligned(S)\
+   (((size_t)(S) & (mparams.granularity - SIZE_T_ONE)) == 0)
+
+/*  True if segment S holds address A */
+#define segment_holds(S, A)\
+  ((char*)(A) >= S->base && (char*)(A) < S->base + S->size)
+
+/* Return segment holding given address */
+static msegmentptr segment_holding(mstate m, char* addr) {
+  msegmentptr sp = &m->seg;
+  for (;;) {
+    if (addr >= sp->base && addr < sp->base + sp->size)
+      return sp;
+    if ((sp = sp->next) == 0)
+      return 0;
+  }
+}
+
+/* Return true if segment contains a segment link */
+static int has_segment_link(mstate m, msegmentptr ss) {
+  msegmentptr sp = &m->seg;
+  for (;;) {
+    if ((char*)sp >= ss->base && (char*)sp < ss->base + ss->size)
+      return 1;
+    if ((sp = sp->next) == 0)
+      return 0;
+  }
+}
+
+#ifndef MORECORE_CANNOT_TRIM
+#define should_trim(M,s)  ((s) > (M)->trim_check)
+#else  /* MORECORE_CANNOT_TRIM */
+#define should_trim(M,s)  (0)
+#endif /* MORECORE_CANNOT_TRIM */
+
+/*
+  TOP_FOOT_SIZE is padding at the end of a segment, including space
+  that may be needed to place segment records and fenceposts when new
+  noncontiguous segments are added.
+*/
+#define TOP_FOOT_SIZE\
+  (align_offset(chunk2mem(0))+pad_request(sizeof(struct malloc_segment))+MIN_CHUNK_SIZE)
+
+
+/* -------------------------------  Hooks -------------------------------- */
+
+/*
+  PREACTION should be defined to return 0 on success, and nonzero on
+  failure. If you are not using locking, you can redefine these to do
+  anything you like.
+*/
+
+#if USE_LOCKS
+
+/* Ensure locks are initialized */
+#define GLOBALLY_INITIALIZE() (mparams.page_size == 0 && init_mparams())
+
+#define PREACTION(M)  ((GLOBALLY_INITIALIZE() || use_lock(M))? ACQUIRE_LOCK(&(M)->mutex) : 0)
+#define POSTACTION(M) { if (use_lock(M)) RELEASE_LOCK(&(M)->mutex); }
+#else /* USE_LOCKS */
+
+#ifndef PREACTION
+#define PREACTION(M) (0)
+#endif  /* PREACTION */
+
+#ifndef POSTACTION
+#define POSTACTION(M)
+#endif  /* POSTACTION */
+
+#endif /* USE_LOCKS */
+
+/*
+  CORRUPTION_ERROR_ACTION is triggered upon detected bad addresses.
+  USAGE_ERROR_ACTION is triggered on detected bad frees and
+  reallocs. The argument p is an address that might have triggered the
+  fault. It is ignored by the two predefined actions, but might be
+  useful in custom actions that try to help diagnose errors.
+*/
+
+#if PROCEED_ON_ERROR
+
+/* A count of the number of corruption errors causing resets */
+int malloc_corruption_error_count;
+
+/* default corruption action */
+static void reset_on_error(mstate m);
+
+#define CORRUPTION_ERROR_ACTION(m)  reset_on_error(m)
+#define USAGE_ERROR_ACTION(m, p)
+
+#else /* PROCEED_ON_ERROR */
+
+#ifndef CORRUPTION_ERROR_ACTION
+#define CORRUPTION_ERROR_ACTION(m) ABORT
+#endif /* CORRUPTION_ERROR_ACTION */
+
+#ifndef USAGE_ERROR_ACTION
+#define USAGE_ERROR_ACTION(m,p) ABORT
+#endif /* USAGE_ERROR_ACTION */
+
+#endif /* PROCEED_ON_ERROR */
+
+/* -------------------------- Debugging setup ---------------------------- */
+
+#if ! DEBUG
+
+#define check_free_chunk(M,P)
+#define check_inuse_chunk(M,P)
+#define check_malloced_chunk(M,P,N)
+#define check_mmapped_chunk(M,P)
+#define check_malloc_state(M)
+#define check_top_chunk(M,P)
+
+#else /* DEBUG */
+#define check_free_chunk(M,P)       do_check_free_chunk(M,P)
+#define check_inuse_chunk(M,P)      do_check_inuse_chunk(M,P)
+#define check_top_chunk(M,P)        do_check_top_chunk(M,P)
+#define check_malloced_chunk(M,P,N) do_check_malloced_chunk(M,P,N)
+#define check_mmapped_chunk(M,P)    do_check_mmapped_chunk(M,P)
+#define check_malloc_state(M)       do_check_malloc_state(M)
+
+static void   do_check_any_chunk(mstate m, mchunkptr p);
+static void   do_check_top_chunk(mstate m, mchunkptr p);
+static void   do_check_mmapped_chunk(mstate m, mchunkptr p);
+static void   do_check_inuse_chunk(mstate m, mchunkptr p);
+static void   do_check_free_chunk(mstate m, mchunkptr p);
+static void   do_check_malloced_chunk(mstate m, void* mem, size_t s);
+static void   do_check_tree(mstate m, tchunkptr t);
+static void   do_check_treebin(mstate m, bindex_t i);
+static void   do_check_smallbin(mstate m, bindex_t i);
+static void   do_check_malloc_state(mstate m);
+static int    bin_find(mstate m, mchunkptr x);
+static size_t traverse_and_check(mstate m);
+#endif /* DEBUG */
+
+/* ---------------------------- Indexing Bins ---------------------------- */
+
+#define is_small(s)         (((s) >> SMALLBIN_SHIFT) < NSMALLBINS)
+#define small_index(s)      ((s)  >> SMALLBIN_SHIFT)
+#define small_index2size(i) ((i)  << SMALLBIN_SHIFT)
+#define MIN_SMALL_INDEX     (small_index(MIN_CHUNK_SIZE))
+
+/* addressing by index. See above about smallbin repositioning */
+#define smallbin_at(M, i)   ((sbinptr)((char*)&((M)->smallbins[(i)<<1])))
+#define treebin_at(M,i)     (&((M)->treebins[i]))
+
+/* assign tree index for size S to variable I */
+#if defined(__GNUC__) && defined(i386)
+#define compute_tree_index(S, I)\
+{\
+  size_t X = S >> TREEBIN_SHIFT;\
+  if (X == 0)\
+    I = 0;\
+  else if (X > 0xFFFF)\
+    I = NTREEBINS-1;\
+  else {\
+    unsigned int K;\
+    __asm__("bsrl %1,%0\n\t" : "=r" (K) : "rm"  (X));\
+    I =  (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\
+  }\
+}
+#else /* GNUC */
+#define compute_tree_index(S, I)\
+{\
+  size_t X = S >> TREEBIN_SHIFT;\
+  if (X == 0)\
+    I = 0;\
+  else if (X > 0xFFFF)\
+    I = NTREEBINS-1;\
+  else {\
+    unsigned int Y = (unsigned int)X;\
+    unsigned int N = ((Y - 0x100) >> 16) & 8;\
+    unsigned int K = (((Y <<= N) - 0x1000) >> 16) & 4;\
+    N += K;\
+    N += K = (((Y <<= K) - 0x4000) >> 16) & 2;\
+    K = 14 - N + ((Y <<= K) >> 15);\
+    I = (K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1));\
+  }\
+}
+#endif /* GNUC */
+
+/* Bit representing maximum resolved size in a treebin at i */
+#define bit_for_tree_index(i) \
+   (i == NTREEBINS-1)? (SIZE_T_BITSIZE-1) : (((i) >> 1) + TREEBIN_SHIFT - 2)
+
+/* Shift placing maximum resolved bit in a treebin at i as sign bit */
+#define leftshift_for_tree_index(i) \
+   ((i == NTREEBINS-1)? 0 : \
+    ((SIZE_T_BITSIZE-SIZE_T_ONE) - (((i) >> 1) + TREEBIN_SHIFT - 2)))
+
+/* The size of the smallest chunk held in bin with index i */
+#define minsize_for_tree_index(i) \
+   ((SIZE_T_ONE << (((i) >> 1) + TREEBIN_SHIFT)) |  \
+   (((size_t)((i) & SIZE_T_ONE)) << (((i) >> 1) + TREEBIN_SHIFT - 1)))
+
+
+/* ------------------------ Operations on bin maps ----------------------- */
+
+/* bit corresponding to given index */
+#define idx2bit(i)              ((binmap_t)(1) << (i))
+
+/* Mark/Clear bits with given index */
+#define mark_smallmap(M,i)      ((M)->smallmap |=  idx2bit(i))
+#define clear_smallmap(M,i)     ((M)->smallmap &= ~idx2bit(i))
+#define smallmap_is_marked(M,i) ((M)->smallmap &   idx2bit(i))
+
+#define mark_treemap(M,i)       ((M)->treemap  |=  idx2bit(i))
+#define clear_treemap(M,i)      ((M)->treemap  &= ~idx2bit(i))
+#define treemap_is_marked(M,i)  ((M)->treemap  &   idx2bit(i))
+
+/* index corresponding to given bit */
+
+#if defined(__GNUC__) && defined(i386)
+#define compute_bit2idx(X, I)\
+{\
+  unsigned int J;\
+  __asm__("bsfl %1,%0\n\t" : "=r" (J) : "rm" (X));\
+  I = (bindex_t)J;\
+}
+
+#else /* GNUC */
+#if  USE_BUILTIN_FFS
+#define compute_bit2idx(X, I) I = ffs(X)-1
+
+#else /* USE_BUILTIN_FFS */
+#define compute_bit2idx(X, I)\
+{\
+  unsigned int Y = X - 1;\
+  unsigned int K = Y >> (16-4) & 16;\
+  unsigned int N = K;        Y >>= K;\
+  N += K = Y >> (8-3) &  8;  Y >>= K;\
+  N += K = Y >> (4-2) &  4;  Y >>= K;\
+  N += K = Y >> (2-1) &  2;  Y >>= K;\
+  N += K = Y >> (1-0) &  1;  Y >>= K;\
+  I = (bindex_t)(N + Y);\
+}
+#endif /* USE_BUILTIN_FFS */
+#endif /* GNUC */
+
+/* isolate the least set bit of a bitmap */
+#define least_bit(x)         ((x) & -(x))
+
+/* mask with all bits to left of least bit of x on */
+#define left_bits(x)         ((x<<1) | -(x<<1))
+
+/* mask with all bits to left of or equal to least bit of x on */
+#define same_or_left_bits(x) ((x) | -(x))
+
+
+/* ----------------------- Runtime Check Support ------------------------- */
+
+/*
+  For security, the main invariant is that malloc/free/etc never
+  writes to a static address other than malloc_state, unless static
+  malloc_state itself has been corrupted, which cannot occur via
+  malloc (because of these checks). In essence this means that we
+  believe all pointers, sizes, maps etc held in malloc_state, but
+  check all of those linked or offsetted from other embedded data
+  structures.  These checks are interspersed with main code in a way
+  that tends to minimize their run-time cost.
+
+  When FOOTERS is defined, in addition to range checking, we also
+  verify footer fields of inuse chunks, which can be used guarantee
+  that the mstate controlling malloc/free is intact.  This is a
+  streamlined version of the approach described by William Robertson
+  et al in "Run-time Detection of Heap-based Overflows" LISA'03
+  http://www.usenix.org/events/lisa03/tech/robertson.html The footer
+  of an inuse chunk holds the xor of its mstate and a random seed,
+  that is checked upon calls to free() and realloc().  This is
+  (probablistically) unguessable from outside the program, but can be
+  computed by any code successfully malloc'ing any chunk, so does not
+  itself provide protection against code that has already broken
+  security through some other means.  Unlike Robertson et al, we
+  always dynamically check addresses of all offset chunks (previous,
+  next, etc). This turns out to be cheaper than relying on hashes.
+*/
+
+#if !INSECURE
+/* Check if address a is at least as high as any from MORECORE or MMAP */
+#define ok_address(M, a) ((char*)(a) >= (M)->least_addr)
+/* Check if address of next chunk n is higher than base chunk p */
+#define ok_next(p, n)    ((char*)(p) < (char*)(n))
+/* Check if p has its cinuse bit on */
+#define ok_cinuse(p)     cinuse(p)
+/* Check if p has its pinuse bit on */
+#define ok_pinuse(p)     pinuse(p)
+
+#else /* !INSECURE */
+#define ok_address(M, a) (1)
+#define ok_next(b, n)    (1)
+#define ok_cinuse(p)     (1)
+#define ok_pinuse(p)     (1)
+#endif /* !INSECURE */
+
+#if (FOOTERS && !INSECURE)
+/* Check if (alleged) mstate m has expected magic field */
+#define ok_magic(M)      ((M)->magic == mparams.magic)
+#else  /* (FOOTERS && !INSECURE) */
+#define ok_magic(M)      (1)
+#endif /* (FOOTERS && !INSECURE) */
+
+
+/* In gcc, use __builtin_expect to minimize impact of checks */
+#if !INSECURE
+#if defined(__GNUC__) && __GNUC__ >= 3
+#define RTCHECK(e)  __builtin_expect(e, 1)
+#else /* GNUC */
+#define RTCHECK(e)  (e)
+#endif /* GNUC */
+#else /* !INSECURE */
+#define RTCHECK(e)  (1)
+#endif /* !INSECURE */
+
+/* macros to set up inuse chunks with or without footers */
+
+#if !FOOTERS
+
+#define mark_inuse_foot(M,p,s)
+
+/* Set cinuse bit and pinuse bit of next chunk */
+#define set_inuse(M,p,s)\
+  ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\
+  ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)
+
+/* Set cinuse and pinuse of this chunk and pinuse of next chunk */
+#define set_inuse_and_pinuse(M,p,s)\
+  ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
+  ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)
+
+/* Set size, cinuse and pinuse bit of this chunk */
+#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\
+  ((p)->head = (s|PINUSE_BIT|CINUSE_BIT))
+
+#else /* FOOTERS */
+
+/* Set foot of inuse chunk to be xor of mstate and seed */
+#define mark_inuse_foot(M,p,s)\
+  (((mchunkptr)((char*)(p) + (s)))->prev_foot = ((size_t)(M) ^ mparams.magic))
+
+#define get_mstate_for(p)\
+  ((mstate)(((mchunkptr)((char*)(p) +\
+    (chunksize(p))))->prev_foot ^ mparams.magic))
+
+#define set_inuse(M,p,s)\
+  ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\
+  (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT), \
+  mark_inuse_foot(M,p,s))
+
+#define set_inuse_and_pinuse(M,p,s)\
+  ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
+  (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT),\
+ mark_inuse_foot(M,p,s))
+
+#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\
+  ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
+  mark_inuse_foot(M, p, s))
+
+#endif /* !FOOTERS */
+
+/* ---------------------------- setting mparams -------------------------- */
+
+/* Initialize mparams */
+static int init_mparams(void) {
+  if (mparams.page_size == 0) {
+    size_t s;
+
+    mparams.mmap_threshold = DEFAULT_MMAP_THRESHOLD;
+    mparams.trim_threshold = DEFAULT_TRIM_THRESHOLD;
+#if MORECORE_CONTIGUOUS
+    mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT;
+#else  /* MORECORE_CONTIGUOUS */
+    mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT|USE_NONCONTIGUOUS_BIT;
+#endif /* MORECORE_CONTIGUOUS */
+
+#if (FOOTERS && !INSECURE)
+    {
+#if USE_DEV_RANDOM
+      int fd;
+      unsigned char buf[sizeof(size_t)];
+      /* Try to use /dev/urandom, else fall back on using time */
+      if ((fd = open("/dev/urandom", O_RDONLY)) >= 0 &&
+          read(fd, buf, sizeof(buf)) == sizeof(buf)) {
+        s = *((size_t *) buf);
+        close(fd);
+      }
+      else
+#endif /* USE_DEV_RANDOM */
+        s = (size_t)(time(0) ^ (size_t)0x55555555U);
+
+      s |= (size_t)8U;    /* ensure nonzero */
+      s &= ~(size_t)7U;   /* improve chances of fault for bad values */
+
+    }
+#else /* (FOOTERS && !INSECURE) */
+    s = (size_t)0x58585858U;
+#endif /* (FOOTERS && !INSECURE) */
+    ACQUIRE_MAGIC_INIT_LOCK();
+    if (mparams.magic == 0) {
+      mparams.magic = s;
+      /* Set up lock for main malloc area */
+      INITIAL_LOCK(&gm->mutex);
+      gm->mflags = mparams.default_mflags;
+    }
+    RELEASE_MAGIC_INIT_LOCK();
+
+#ifndef WIN32
+    mparams.page_size = malloc_getpagesize;
+    mparams.granularity = ((DEFAULT_GRANULARITY != 0)?
+                           DEFAULT_GRANULARITY : mparams.page_size);
+#else /* WIN32 */
+    {
+      SYSTEM_INFO system_info;
+      GetSystemInfo(&system_info);
+      mparams.page_size = system_info.dwPageSize;
+      mparams.granularity = system_info.dwAllocationGranularity;
+    }
+#endif /* WIN32 */
+
+    /* Sanity-check configuration:
+       size_t must be unsigned and as wide as pointer type.
+       ints must be at least 4 bytes.
+       alignment must be at least 8.
+       Alignment, min chunk size, and page size must all be powers of 2.
+    */
+    if ((sizeof(size_t) != sizeof(char*)) ||
+        (MAX_SIZE_T < MIN_CHUNK_SIZE)  ||
+        (sizeof(int) < 4)  ||
+        (MALLOC_ALIGNMENT < (size_t)8U) ||
+        ((MALLOC_ALIGNMENT    & (MALLOC_ALIGNMENT-SIZE_T_ONE))    != 0) ||
+        ((MCHUNK_SIZE         & (MCHUNK_SIZE-SIZE_T_ONE))         != 0) ||
+        ((mparams.granularity & (mparams.granularity-SIZE_T_ONE)) != 0) ||
+        ((mparams.page_size   & (mparams.page_size-SIZE_T_ONE))   != 0))
+      ABORT;
+  }
+  return 0;
+}
+
+/* support for mallopt */
+static int change_mparam(int param_number, int value) {
+  size_t val = (size_t)value;
+  init_mparams();
+  switch(param_number) {
+  case M_TRIM_THRESHOLD:
+    mparams.trim_threshold = val;
+    return 1;
+  case M_GRANULARITY:
+    if (val >= mparams.page_size && ((val & (val-1)) == 0)) {
+      mparams.granularity = val;
+      return 1;
+    }
+    else
+      return 0;
+  case M_MMAP_THRESHOLD:
+    mparams.mmap_threshold = val;
+    return 1;
+  default:
+    return 0;
+  }
+}
+
+#if DEBUG
+/* ------------------------- Debugging Support --------------------------- */
+
+/* Check properties of any chunk, whether free, inuse, mmapped etc  */
+static void do_check_any_chunk(mstate m, mchunkptr p) {
+  assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
+  assert(ok_address(m, p));
+}
+
+/* Check properties of top chunk */
+static void do_check_top_chunk(mstate m, mchunkptr p) {
+  msegmentptr sp = segment_holding(m, (char*)p);
+  size_t  sz = chunksize(p);
+  assert(sp != 0);
+  assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
+  assert(ok_address(m, p));
+  assert(sz == m->topsize);
+  assert(sz > 0);
+  assert(sz == ((sp->base + sp->size) - (char*)p) - TOP_FOOT_SIZE);
+  assert(pinuse(p));
+  assert(!next_pinuse(p));
+}
+
+/* Check properties of (inuse) mmapped chunks */
+static void do_check_mmapped_chunk(mstate m, mchunkptr p) {
+  size_t  sz = chunksize(p);
+  size_t len = (sz + (p->prev_foot & ~IS_MMAPPED_BIT) + MMAP_FOOT_PAD);
+  assert(is_mmapped(p));
+  assert(use_mmap(m));
+  assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
+  assert(ok_address(m, p));
+  assert(!is_small(sz));
+  assert((len & (mparams.page_size-SIZE_T_ONE)) == 0);
+  assert(chunk_plus_offset(p, sz)->head == FENCEPOST_HEAD);
+  assert(chunk_plus_offset(p, sz+SIZE_T_SIZE)->head == 0);
+}
+
+/* Check properties of inuse chunks */
+static void do_check_inuse_chunk(mstate m, mchunkptr p) {
+  do_check_any_chunk(m, p);
+  assert(cinuse(p));
+  assert(next_pinuse(p));
+  /* If not pinuse and not mmapped, previous chunk has OK offset */
+  assert(is_mmapped(p) || pinuse(p) || next_chunk(prev_chunk(p)) == p);
+  if (is_mmapped(p))
+    do_check_mmapped_chunk(m, p);
+}
+
+/* Check properties of free chunks */
+static void do_check_free_chunk(mstate m, mchunkptr p) {
+  size_t sz = p->head & ~(PINUSE_BIT|CINUSE_BIT);
+  mchunkptr next = chunk_plus_offset(p, sz);
+  do_check_any_chunk(m, p);
+  assert(!cinuse(p));
+  assert(!next_pinuse(p));
+  assert (!is_mmapped(p));
+  if (p != m->dv && p != m->top) {
+    if (sz >= MIN_CHUNK_SIZE) {
+      assert((sz & CHUNK_ALIGN_MASK) == 0);
+      assert(is_aligned(chunk2mem(p)));
+      assert(next->prev_foot == sz);
+      assert(pinuse(p));
+      assert (next == m->top || cinuse(next));
+      assert(p->fd->bk == p);
+      assert(p->bk->fd == p);
+    }
+    else  /* markers are always of size SIZE_T_SIZE */
+      assert(sz == SIZE_T_SIZE);
+  }
+}
+
+/* Check properties of malloced chunks at the point they are malloced */
+static void do_check_malloced_chunk(mstate m, void* mem, size_t s) {
+  if (mem != 0) {
+    mchunkptr p = mem2chunk(mem);
+    size_t sz = p->head & ~(PINUSE_BIT|CINUSE_BIT);
+    do_check_inuse_chunk(m, p);
+    assert((sz & CHUNK_ALIGN_MASK) == 0);
+    assert(sz >= MIN_CHUNK_SIZE);
+    assert(sz >= s);
+    /* unless mmapped, size is less than MIN_CHUNK_SIZE more than request */
+    assert(is_mmapped(p) || sz < (s + MIN_CHUNK_SIZE));
+  }
+}
+
+/* Check a tree and its subtrees.  */
+static void do_check_tree(mstate m, tchunkptr t) {
+  tchunkptr head = 0;
+  tchunkptr u = t;
+  bindex_t tindex = t->index;
+  size_t tsize = chunksize(t);
+  bindex_t idx;
+  compute_tree_index(tsize, idx);
+  assert(tindex == idx);
+  assert(tsize >= MIN_LARGE_SIZE);
+  assert(tsize >= minsize_for_tree_index(idx));
+  assert((idx == NTREEBINS-1) || (tsize < minsize_for_tree_index((idx+1))));
+
+  do { /* traverse through chain of same-sized nodes */
+    do_check_any_chunk(m, ((mchunkptr)u));
+    assert(u->index == tindex);
+    assert(chunksize(u) == tsize);
+    assert(!cinuse(u));
+    assert(!next_pinuse(u));
+    assert(u->fd->bk == u);
+    assert(u->bk->fd == u);
+    if (u->parent == 0) {
+      assert(u->child[0] == 0);
+      assert(u->child[1] == 0);
+    }
+    else {
+      assert(head == 0); /* only one node on chain has parent */
+      head = u;
+      assert(u->parent != u);
+      assert (u->parent->child[0] == u ||
+              u->parent->child[1] == u ||
+              *((tbinptr*)(u->parent)) == u);
+      if (u->child[0] != 0) {
+        assert(u->child[0]->parent == u);
+        assert(u->child[0] != u);
+        do_check_tree(m, u->child[0]);
+      }
+      if (u->child[1] != 0) {
+        assert(u->child[1]->parent == u);
+        assert(u->child[1] != u);
+        do_check_tree(m, u->child[1]);
+      }
+      if (u->child[0] != 0 && u->child[1] != 0) {
+        assert(chunksize(u->child[0]) < chunksize(u->child[1]));
+      }
+    }
+    u = u->fd;
+  } while (u != t);
+  assert(head != 0);
+}
+
+/*  Check all the chunks in a treebin.  */
+static void do_check_treebin(mstate m, bindex_t i) {
+  tbinptr* tb = treebin_at(m, i);
+  tchunkptr t = *tb;
+  int empty = (m->treemap & (1U << i)) == 0;
+  if (t == 0)
+    assert(empty);
+  if (!empty)
+    do_check_tree(m, t);
+}
+
+/*  Check all the chunks in a smallbin.  */
+static void do_check_smallbin(mstate m, bindex_t i) {
+  sbinptr b = smallbin_at(m, i);
+  mchunkptr p = b->bk;
+  unsigned int empty = (m->smallmap & (1U << i)) == 0;
+  if (p == b)
+    assert(empty);
+  if (!empty) {
+    for (; p != b; p = p->bk) {
+      size_t size = chunksize(p);
+      mchunkptr q;
+      /* each chunk claims to be free */
+      do_check_free_chunk(m, p);
+      /* chunk belongs in bin */
+      assert(small_index(size) == i);
+      assert(p->bk == b || chunksize(p->bk) == chunksize(p));
+      /* chunk is followed by an inuse chunk */
+      q = next_chunk(p);
+      if (q->head != FENCEPOST_HEAD)
+        do_check_inuse_chunk(m, q);
+    }
+  }
+}
+
+/* Find x in a bin. Used in other check functions. */
+static int bin_find(mstate m, mchunkptr x) {
+  size_t size = chunksize(x);
+  if (is_small(size)) {
+    bindex_t sidx = small_index(size);
+    sbinptr b = smallbin_at(m, sidx);
+    if (smallmap_is_marked(m, sidx)) {
+      mchunkptr p = b;
+      do {
+        if (p == x)
+          return 1;
+      } while ((p = p->fd) != b);
+    }
+  }
+  else {
+    bindex_t tidx;
+    compute_tree_index(size, tidx);
+    if (treemap_is_marked(m, tidx)) {
+      tchunkptr t = *treebin_at(m, tidx);
+      size_t sizebits = size << leftshift_for_tree_index(tidx);
+      while (t != 0 && chunksize(t) != size) {
+        t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1];
+        sizebits <<= 1;
+      }
+      if (t != 0) {
+        tchunkptr u = t;
+        do {
+          if (u == (tchunkptr)x)
+            return 1;
+        } while ((u = u->fd) != t);
+      }
+    }
+  }
+  return 0;
+}
+
+/* Traverse each chunk and check it; return total */
+static size_t traverse_and_check(mstate m) {
+  size_t sum = 0;
+  if (is_initialized(m)) {
+    msegmentptr s = &m->seg;
+    sum += m->topsize + TOP_FOOT_SIZE;
+    while (s != 0) {
+      mchunkptr q = align_as_chunk(s->base);
+      mchunkptr lastq = 0;
+      assert(pinuse(q));
+      while (segment_holds(s, q) &&
+             q != m->top && q->head != FENCEPOST_HEAD) {
+        sum += chunksize(q);
+        if (cinuse(q)) {
+          assert(!bin_find(m, q));
+          do_check_inuse_chunk(m, q);
+        }
+        else {
+          assert(q == m->dv || bin_find(m, q));
+          assert(lastq == 0 || cinuse(lastq)); /* Not 2 consecutive free */
+          do_check_free_chunk(m, q);
+        }
+        lastq = q;
+        q = next_chunk(q);
+      }
+      s = s->next;
+    }
+  }
+  return sum;
+}
+
+/* Check all properties of malloc_state. */
+static void do_check_malloc_state(mstate m) {
+  bindex_t i;
+  size_t total;
+  /* check bins */
+  for (i = 0; i < NSMALLBINS; ++i)
+    do_check_smallbin(m, i);
+  for (i = 0; i < NTREEBINS; ++i)
+    do_check_treebin(m, i);
+
+  if (m->dvsize != 0) { /* check dv chunk */
+    do_check_any_chunk(m, m->dv);
+    assert(m->dvsize == chunksize(m->dv));
+    assert(m->dvsize >= MIN_CHUNK_SIZE);
+    assert(bin_find(m, m->dv) == 0);
+  }
+
+  if (m->top != 0) {   /* check top chunk */
+    do_check_top_chunk(m, m->top);
+    assert(m->topsize == chunksize(m->top));
+    assert(m->topsize > 0);
+    assert(bin_find(m, m->top) == 0);
+  }
+
+  total = traverse_and_check(m);
+  assert(total <= m->footprint);
+  assert(m->footprint <= m->max_footprint);
+}
+#endif /* DEBUG */
+
+/* ----------------------------- statistics ------------------------------ */
+
+#if !NO_MALLINFO
+static struct mallinfo internal_mallinfo(mstate m) {
+  struct mallinfo nm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+  if (!PREACTION(m)) {
+    check_malloc_state(m);
+    if (is_initialized(m)) {
+      size_t nfree = SIZE_T_ONE; /* top always free */
+      size_t mfree = m->topsize + TOP_FOOT_SIZE;
+      size_t sum = mfree;
+      msegmentptr s = &m->seg;
+      while (s != 0) {
+        mchunkptr q = align_as_chunk(s->base);
+        while (segment_holds(s, q) &&
+               q != m->top && q->head != FENCEPOST_HEAD) {
+          size_t sz = chunksize(q);
+          sum += sz;
+          if (!cinuse(q)) {
+            mfree += sz;
+            ++nfree;
+          }
+          q = next_chunk(q);
+        }
+        s = s->next;
+      }
+
+      nm.arena    = sum;
+      nm.ordblks  = nfree;
+      nm.hblkhd   = m->footprint - sum;
+      nm.usmblks  = m->max_footprint;
+      nm.uordblks = m->footprint - mfree;
+      nm.fordblks = mfree;
+      nm.keepcost = m->topsize;
+    }
+
+    POSTACTION(m);
+  }
+  return nm;
+}
+#endif /* !NO_MALLINFO */
+
+static void internal_malloc_stats(mstate m) {
+  if (!PREACTION(m)) {
+    size_t maxfp = 0;
+    size_t fp = 0;
+    size_t used = 0;
+    check_malloc_state(m);
+    if (is_initialized(m)) {
+      msegmentptr s = &m->seg;
+      maxfp = m->max_footprint;
+      fp = m->footprint;
+      used = fp - (m->topsize + TOP_FOOT_SIZE);
+
+      while (s != 0) {
+        mchunkptr q = align_as_chunk(s->base);
+        while (segment_holds(s, q) &&
+               q != m->top && q->head != FENCEPOST_HEAD) {
+          if (!cinuse(q))
+            used -= chunksize(q);
+          q = next_chunk(q);
+        }
+        s = s->next;
+      }
+    }
+
+    fprintf(stderr, "max system bytes = %10lu\n", (unsigned long)(maxfp));
+    fprintf(stderr, "system bytes     = %10lu\n", (unsigned long)(fp));
+    fprintf(stderr, "in use bytes     = %10lu\n", (unsigned long)(used));
+
+    POSTACTION(m);
+  }
+}
+
+/* ----------------------- Operations on smallbins ----------------------- */
+
+/*
+  Various forms of linking and unlinking are defined as macros.  Even
+  the ones for trees, which are very long but have very short typical
+  paths.  This is ugly but reduces reliance on inlining support of
+  compilers.
+*/
+
+/* Link a free chunk into a smallbin  */
+#define insert_small_chunk(M, P, S) {\
+  bindex_t I  = small_index(S);\
+  mchunkptr B = smallbin_at(M, I);\
+  mchunkptr F = B;\
+  assert(S >= MIN_CHUNK_SIZE);\
+  if (!smallmap_is_marked(M, I))\
+    mark_smallmap(M, I);\
+  else if (RTCHECK(ok_address(M, B->fd)))\
+    F = B->fd;\
+  else {\
+    CORRUPTION_ERROR_ACTION(M);\
+  }\
+  B->fd = P;\
+  F->bk = P;\
+  P->fd = F;\
+  P->bk = B;\
+}
+
+/* Unlink a chunk from a smallbin  */
+#define unlink_small_chunk(M, P, S) {\
+  mchunkptr F = P->fd;\
+  mchunkptr B = P->bk;\
+  bindex_t I = small_index(S);\
+  assert(P != B);\
+  assert(P != F);\
+  assert(chunksize(P) == small_index2size(I));\
+  if (F == B)\
+    clear_smallmap(M, I);\
+  else if (RTCHECK((F == smallbin_at(M,I) || ok_address(M, F)) &&\
+                   (B == smallbin_at(M,I) || ok_address(M, B)))) {\
+    F->bk = B;\
+    B->fd = F;\
+  }\
+  else {\
+    CORRUPTION_ERROR_ACTION(M);\
+  }\
+}
+
+/* Unlink the first chunk from a smallbin */
+#define unlink_first_small_chunk(M, B, P, I) {\
+  mchunkptr F = P->fd;\
+  assert(P != B);\
+  assert(P != F);\
+  assert(chunksize(P) == small_index2size(I));\
+  if (B == F)\
+    clear_smallmap(M, I);\
+  else if (RTCHECK(ok_address(M, F))) {\
+    B->fd = F;\
+    F->bk = B;\
+  }\
+  else {\
+    CORRUPTION_ERROR_ACTION(M);\
+  }\
+}
+
+/* Replace dv node, binning the old one */
+/* Used only when dvsize known to be small */
+#define replace_dv(M, P, S) {\
+  size_t DVS = M->dvsize;\
+  if (DVS != 0) {\
+    mchunkptr DV = M->dv;\
+    assert(is_small(DVS));\
+    insert_small_chunk(M, DV, DVS);\
+  }\
+  M->dvsize = S;\
+  M->dv = P;\
+}
+
+/* ------------------------- Operations on trees ------------------------- */
+
+/* Insert chunk into tree */
+#define insert_large_chunk(M, X, S) {\
+  tbinptr* H;\
+  bindex_t I;\
+  compute_tree_index(S, I);\
+  H = treebin_at(M, I);\
+  X->index = I;\
+  X->child[0] = X->child[1] = 0;\
+  if (!treemap_is_marked(M, I)) {\
+    mark_treemap(M, I);\
+    *H = X;\
+    X->parent = (tchunkptr)H;\
+    X->fd = X->bk = X;\
+  }\
+  else {\
+    tchunkptr T = *H;\
+    size_t K = S << leftshift_for_tree_index(I);\
+    for (;;) {\
+      if (chunksize(T) != S) {\
+        tchunkptr* C = &(T->child[(K >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]);\
+        K <<= 1;\
+        if (*C != 0)\
+          T = *C;\
+        else if (RTCHECK(ok_address(M, C))) {\
+          *C = X;\
+          X->parent = T;\
+          X->fd = X->bk = X;\
+          break;\
+        }\
+        else {\
+          CORRUPTION_ERROR_ACTION(M);\
+          break;\
+        }\
+      }\
+      else {\
+        tchunkptr F = T->fd;\
+        if (RTCHECK(ok_address(M, T) && ok_address(M, F))) {\
+          T->fd = F->bk = X;\
+          X->fd = F;\
+          X->bk = T;\
+          X->parent = 0;\
+          break;\
+        }\
+        else {\
+          CORRUPTION_ERROR_ACTION(M);\
+          break;\
+        }\
+      }\
+    }\
+  }\
+}
+
+/*
+  Unlink steps:
+
+  1. If x is a chained node, unlink it from its same-sized fd/bk links
+     and choose its bk node as its replacement.
+  2. If x was the last node of its size, but not a leaf node, it must
+     be replaced with a leaf node (not merely one with an open left or
+     right), to make sure that lefts and rights of descendents
+     correspond properly to bit masks.  We use the rightmost descendent
+     of x.  We could use any other leaf, but this is easy to locate and
+     tends to counteract removal of leftmosts elsewhere, and so keeps
+     paths shorter than minimally guaranteed.  This doesn't loop much
+     because on average a node in a tree is near the bottom.
+  3. If x is the base of a chain (i.e., has parent links) relink
+     x's parent and children to x's replacement (or null if none).
+*/
+
+#define unlink_large_chunk(M, X) {\
+  tchunkptr XP = X->parent;\
+  tchunkptr R;\
+  if (X->bk != X) {\
+    tchunkptr F = X->fd;\
+    R = X->bk;\
+    if (RTCHECK(ok_address(M, F))) {\
+      F->bk = R;\
+      R->fd = F;\
+    }\
+    else {\
+      CORRUPTION_ERROR_ACTION(M);\
+    }\
+  }\
+  else {\
+    tchunkptr* RP;\
+    if (((R = *(RP = &(X->child[1]))) != 0) ||\
+        ((R = *(RP = &(X->child[0]))) != 0)) {\
+      tchunkptr* CP;\
+      while ((*(CP = &(R->child[1])) != 0) ||\
+             (*(CP = &(R->child[0])) != 0)) {\
+        R = *(RP = CP);\
+      }\
+      if (RTCHECK(ok_address(M, RP)))\
+        *RP = 0;\
+      else {\
+        CORRUPTION_ERROR_ACTION(M);\
+      }\
+    }\
+  }\
+  if (XP != 0) {\
+    tbinptr* H = treebin_at(M, X->index);\
+    if (X == *H) {\
+      if ((*H = R) == 0) \
+        clear_treemap(M, X->index);\
+    }\
+    else if (RTCHECK(ok_address(M, XP))) {\
+      if (XP->child[0] == X) \
+        XP->child[0] = R;\
+      else \
+        XP->child[1] = R;\
+    }\
+    else\
+      CORRUPTION_ERROR_ACTION(M);\
+    if (R != 0) {\
+      if (RTCHECK(ok_address(M, R))) {\
+        tchunkptr C0, C1;\
+        R->parent = XP;\
+        if ((C0 = X->child[0]) != 0) {\
+          if (RTCHECK(ok_address(M, C0))) {\
+            R->child[0] = C0;\
+            C0->parent = R;\
+          }\
+          else\
+            CORRUPTION_ERROR_ACTION(M);\
+        }\
+        if ((C1 = X->child[1]) != 0) {\
+          if (RTCHECK(ok_address(M, C1))) {\
+            R->child[1] = C1;\
+            C1->parent = R;\
+          }\
+          else\
+            CORRUPTION_ERROR_ACTION(M);\
+        }\
+      }\
+      else\
+        CORRUPTION_ERROR_ACTION(M);\
+    }\
+  }\
+}
+
+/* Relays to large vs small bin operations */
+
+#define insert_chunk(M, P, S)\
+  if (is_small(S)) insert_small_chunk(M, P, S)\
+  else { tchunkptr TP = (tchunkptr)(P); insert_large_chunk(M, TP, S); }
+
+#define unlink_chunk(M, P, S)\
+  if (is_small(S)) unlink_small_chunk(M, P, S)\
+  else { tchunkptr TP = (tchunkptr)(P); unlink_large_chunk(M, TP); }
+
+
+/* Relays to internal calls to malloc/free from realloc, memalign etc */
+
+#if ONLY_MSPACES
+#define internal_malloc(m, b) mspace_malloc(m, b)
+#define internal_free(m, mem) mspace_free(m,mem);
+#else /* ONLY_MSPACES */
+#if MSPACES
+#define internal_malloc(m, b)\
+   (m == gm)? dlmalloc(b) : mspace_malloc(m, b)
+#define internal_free(m, mem)\
+   if (m == gm) dlfree(mem); else mspace_free(m,mem);
+#else /* MSPACES */
+#define internal_malloc(m, b) dlmalloc(b)
+#define internal_free(m, mem) dlfree(mem)
+#endif /* MSPACES */
+#endif /* ONLY_MSPACES */
+
+/* -----------------------  Direct-mmapping chunks ----------------------- */
+
+/*
+  Directly mmapped chunks are set up with an offset to the start of
+  the mmapped region stored in the prev_foot field of the chunk. This
+  allows reconstruction of the required argument to MUNMAP when freed,
+  and also allows adjustment of the returned chunk to meet alignment
+  requirements (especially in memalign).  There is also enough space
+  allocated to hold a fake next chunk of size SIZE_T_SIZE to maintain
+  the PINUSE bit so frees can be checked.
+*/
+
+/* Malloc using mmap */
+static void* mmap_alloc(mstate m, size_t nb) {
+  size_t mmsize = granularity_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
+  if (mmsize > nb) {     /* Check for wrap around 0 */
+    char* mm = (char*)(DIRECT_MMAP(mmsize));
+    if (mm != CMFAIL) {
+      size_t offset = align_offset(chunk2mem(mm));
+      size_t psize = mmsize - offset - MMAP_FOOT_PAD;
+      mchunkptr p = (mchunkptr)(mm + offset);
+      p->prev_foot = offset | IS_MMAPPED_BIT;
+      (p)->head = (psize|CINUSE_BIT);
+      mark_inuse_foot(m, p, psize);
+      chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD;
+      chunk_plus_offset(p, psize+SIZE_T_SIZE)->head = 0;
+
+      if (mm < m->least_addr)
+        m->least_addr = mm;
+      if ((m->footprint += mmsize) > m->max_footprint)
+        m->max_footprint = m->footprint;
+      assert(is_aligned(chunk2mem(p)));
+      check_mmapped_chunk(m, p);
+      return chunk2mem(p);
+    }
+  }
+  return 0;
+}
+
+/* Realloc using mmap */
+static mchunkptr mmap_resize(mstate m, mchunkptr oldp, size_t nb) {
+  size_t oldsize = chunksize(oldp);
+  if (is_small(nb)) /* Can't shrink mmap regions below small size */
+    return 0;
+  /* Keep old chunk if big enough but not too big */
+  if (oldsize >= nb + SIZE_T_SIZE &&
+      (oldsize - nb) <= (mparams.granularity << 1))
+    return oldp;
+  else {
+    size_t offset = oldp->prev_foot & ~IS_MMAPPED_BIT;
+    size_t oldmmsize = oldsize + offset + MMAP_FOOT_PAD;
+    size_t newmmsize = granularity_align(nb + SIX_SIZE_T_SIZES +
+                                         CHUNK_ALIGN_MASK);
+    char* cp = (char*)CALL_MREMAP((char*)oldp - offset,
+                                  oldmmsize, newmmsize, 1);
+    if (cp != CMFAIL) {
+      mchunkptr newp = (mchunkptr)(cp + offset);
+      size_t psize = newmmsize - offset - MMAP_FOOT_PAD;
+      newp->head = (psize|CINUSE_BIT);
+      mark_inuse_foot(m, newp, psize);
+      chunk_plus_offset(newp, psize)->head = FENCEPOST_HEAD;
+      chunk_plus_offset(newp, psize+SIZE_T_SIZE)->head = 0;
+
+      if (cp < m->least_addr)
+        m->least_addr = cp;
+      if ((m->footprint += newmmsize - oldmmsize) > m->max_footprint)
+        m->max_footprint = m->footprint;
+      check_mmapped_chunk(m, newp);
+      return newp;
+    }
+  }
+  return 0;
+}
+
+/* -------------------------- mspace management -------------------------- */
+
+/* Initialize top chunk and its size */
+static void init_top(mstate m, mchunkptr p, size_t psize) {
+  /* Ensure alignment */
+  size_t offset = align_offset(chunk2mem(p));
+  p = (mchunkptr)((char*)p + offset);
+  psize -= offset;
+
+  m->top = p;
+  m->topsize = psize;
+  p->head = psize | PINUSE_BIT;
+  /* set size of fake trailing chunk holding overhead space only once */
+  chunk_plus_offset(p, psize)->head = TOP_FOOT_SIZE;
+  m->trim_check = mparams.trim_threshold; /* reset on each update */
+}
+
+/* Initialize bins for a new mstate that is otherwise zeroed out */
+static void init_bins(mstate m) {
+  /* Establish circular links for smallbins */
+  bindex_t i;
+  for (i = 0; i < NSMALLBINS; ++i) {
+    sbinptr bin = smallbin_at(m,i);
+    bin->fd = bin->bk = bin;
+  }
+}
+
+#if PROCEED_ON_ERROR
+
+/* default corruption action */
+static void reset_on_error(mstate m) {
+  int i;
+  ++malloc_corruption_error_count;
+  /* Reinitialize fields to forget about all memory */
+  m->smallbins = m->treebins = 0;
+  m->dvsize = m->topsize = 0;
+  m->seg.base = 0;
+  m->seg.size = 0;
+  m->seg.next = 0;
+  m->top = m->dv = 0;
+  for (i = 0; i < NTREEBINS; ++i)
+    *treebin_at(m, i) = 0;
+  init_bins(m);
+}
+#endif /* PROCEED_ON_ERROR */
+
+/* Allocate chunk and prepend remainder with chunk in successor base. */
+static void* prepend_alloc(mstate m, char* newbase, char* oldbase,
+                           size_t nb) {
+  mchunkptr p = align_as_chunk(newbase);
+  mchunkptr oldfirst = align_as_chunk(oldbase);
+  size_t psize = (char*)oldfirst - (char*)p;
+  mchunkptr q = chunk_plus_offset(p, nb);
+  size_t qsize = psize - nb;
+  set_size_and_pinuse_of_inuse_chunk(m, p, nb);
+
+  assert((char*)oldfirst > (char*)q);
+  assert(pinuse(oldfirst));
+  assert(qsize >= MIN_CHUNK_SIZE);
+
+  /* consolidate remainder with first chunk of old base */
+  if (oldfirst == m->top) {
+    size_t tsize = m->topsize += qsize;
+    m->top = q;
+    q->head = tsize | PINUSE_BIT;
+    check_top_chunk(m, q);
+  }
+  else if (oldfirst == m->dv) {
+    size_t dsize = m->dvsize += qsize;
+    m->dv = q;
+    set_size_and_pinuse_of_free_chunk(q, dsize);
+  }
+  else {
+    if (!cinuse(oldfirst)) {
+      size_t nsize = chunksize(oldfirst);
+      unlink_chunk(m, oldfirst, nsize);
+      oldfirst = chunk_plus_offset(oldfirst, nsize);
+      qsize += nsize;
+    }
+    set_free_with_pinuse(q, qsize, oldfirst);
+    insert_chunk(m, q, qsize);
+    check_free_chunk(m, q);
+  }
+
+  check_malloced_chunk(m, chunk2mem(p), nb);
+  return chunk2mem(p);
+}
+
+
+/* Add a segment to hold a new noncontiguous region */
+static void add_segment(mstate m, char* tbase, size_t tsize, flag_t mmapped) {
+  /* Determine locations and sizes of segment, fenceposts, old top */
+  char* old_top = (char*)m->top;
+  msegmentptr oldsp = segment_holding(m, old_top);
+  char* old_end = oldsp->base + oldsp->size;
+  size_t ssize = pad_request(sizeof(struct malloc_segment));
+  char* rawsp = old_end - (ssize + FOUR_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
+  size_t offset = align_offset(chunk2mem(rawsp));
+  char* asp = rawsp + offset;
+  char* csp = (asp < (old_top + MIN_CHUNK_SIZE))? old_top : asp;
+  mchunkptr sp = (mchunkptr)csp;
+  msegmentptr ss = (msegmentptr)(chunk2mem(sp));
+  mchunkptr tnext = chunk_plus_offset(sp, ssize);
+  mchunkptr p = tnext;
+  int nfences = 0;
+
+  /* reset top to new space */
+  init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE);
+
+  /* Set up segment record */
+  assert(is_aligned(ss));
+  set_size_and_pinuse_of_inuse_chunk(m, sp, ssize);
+  *ss = m->seg; /* Push current record */
+  m->seg.base = tbase;
+  m->seg.size = tsize;
+  m->seg.sflags = mmapped;
+  m->seg.next = ss;
+
+  /* Insert trailing fenceposts */
+  for (;;) {
+    mchunkptr nextp = chunk_plus_offset(p, SIZE_T_SIZE);
+    p->head = FENCEPOST_HEAD;
+    ++nfences;
+    if ((char*)(&(nextp->head)) < old_end)
+      p = nextp;
+    else
+      break;
+  }
+  assert(nfences >= 2);
+
+  /* Insert the rest of old top into a bin as an ordinary free chunk */
+  if (csp != old_top) {
+    mchunkptr q = (mchunkptr)old_top;
+    size_t psize = csp - old_top;
+    mchunkptr tn = chunk_plus_offset(q, psize);
+    set_free_with_pinuse(q, psize, tn);
+    insert_chunk(m, q, psize);
+  }
+
+  check_top_chunk(m, m->top);
+}
+
+/* -------------------------- System allocation -------------------------- */
+
+/* Get memory from system using MORECORE or MMAP */
+static void* sys_alloc(mstate m, size_t nb) {
+  char* tbase = CMFAIL;
+  size_t tsize = 0;
+  flag_t mmap_flag = 0;
+
+  init_mparams();
+
+  /* Directly map large chunks */
+  if (use_mmap(m) && nb >= mparams.mmap_threshold) {
+    void* mem = mmap_alloc(m, nb);
+    if (mem != 0)
+      return mem;
+  }
+
+  /*
+    Try getting memory in any of three ways (in most-preferred to
+    least-preferred order):
+    1. A call to MORECORE that can normally contiguously extend memory.
+       (disabled if not MORECORE_CONTIGUOUS or not HAVE_MORECORE or
+       or main space is mmapped or a previous contiguous call failed)
+    2. A call to MMAP new space (disabled if not HAVE_MMAP).
+       Note that under the default settings, if MORECORE is unable to
+       fulfill a request, and HAVE_MMAP is true, then mmap is
+       used as a noncontiguous system allocator. This is a useful backup
+       strategy for systems with holes in address spaces -- in this case
+       sbrk cannot contiguously expand the heap, but mmap may be able to
+       find space.
+    3. A call to MORECORE that cannot usually contiguously extend memory.
+       (disabled if not HAVE_MORECORE)
+  */
+
+  if (MORECORE_CONTIGUOUS && !use_noncontiguous(m)) {
+    char* br = CMFAIL;
+    msegmentptr ss = (m->top == 0)? 0 : segment_holding(m, (char*)m->top);
+    size_t asize = 0;
+    ACQUIRE_MORECORE_LOCK();
+
+    if (ss == 0) {  /* First time through or recovery */
+      char* base = (char*)CALL_MORECORE(0);
+      if (base != CMFAIL) {
+        asize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE);
+        /* Adjust to end on a page boundary */
+        if (!is_page_aligned(base))
+          asize += (page_align((size_t)base) - (size_t)base);
+        /* Can't call MORECORE if size is negative when treated as signed */
+        if (asize < HALF_MAX_SIZE_T &&
+            (br = (char*)(CALL_MORECORE(asize))) == base) {
+          tbase = base;
+          tsize = asize;
+        }
+      }
+    }
+    else {
+      /* Subtract out existing available top space from MORECORE request. */
+      asize = granularity_align(nb - m->topsize + TOP_FOOT_SIZE + SIZE_T_ONE);
+      /* Use mem here only if it did continuously extend old space */
+      if (asize < HALF_MAX_SIZE_T &&
+          (br = (char*)(CALL_MORECORE(asize))) == ss->base+ss->size) {
+        tbase = br;
+        tsize = asize;
+      }
+    }
+
+    if (tbase == CMFAIL) {    /* Cope with partial failure */
+      if (br != CMFAIL) {    /* Try to use/extend the space we did get */
+        if (asize < HALF_MAX_SIZE_T &&
+            asize < nb + TOP_FOOT_SIZE + SIZE_T_ONE) {
+          size_t esize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE - asize);
+          if (esize < HALF_MAX_SIZE_T) {
+            char* end = (char*)CALL_MORECORE(esize);
+            if (end != CMFAIL)
+              asize += esize;
+            else {            /* Can't use; try to release */
+              CALL_MORECORE(-asize);
+              br = CMFAIL;
+            }
+          }
+        }
+      }
+      if (br != CMFAIL) {    /* Use the space we did get */
+        tbase = br;
+        tsize = asize;
+      }
+      else
+        disable_contiguous(m); /* Don't try contiguous path in the future */
+    }
+
+    RELEASE_MORECORE_LOCK();
+  }
+
+  if (HAVE_MMAP && tbase == CMFAIL) {  /* Try MMAP */
+    size_t req = nb + TOP_FOOT_SIZE + SIZE_T_ONE;
+    size_t rsize = granularity_align(req);
+    if (rsize > nb) { /* Fail if wraps around zero */
+      char* mp = (char*)(CALL_MMAP(rsize));
+      if (mp != CMFAIL) {
+        tbase = mp;
+        tsize = rsize;
+        mmap_flag = IS_MMAPPED_BIT;
+      }
+    }
+  }
+
+  if (HAVE_MORECORE && tbase == CMFAIL) { /* Try noncontiguous MORECORE */
+    size_t asize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE);
+    if (asize < HALF_MAX_SIZE_T) {
+      char* br = CMFAIL;
+      char* end = CMFAIL;
+      ACQUIRE_MORECORE_LOCK();
+      br = (char*)(CALL_MORECORE(asize));
+      end = (char*)(CALL_MORECORE(0));
+      RELEASE_MORECORE_LOCK();
+      if (br != CMFAIL && end != CMFAIL && br < end) {
+        size_t ssize = end - br;
+        if (ssize > nb + TOP_FOOT_SIZE) {
+          tbase = br;
+          tsize = ssize;
+        }
+      }
+    }
+  }
+
+  if (tbase != CMFAIL) {
+
+    if ((m->footprint += tsize) > m->max_footprint)
+      m->max_footprint = m->footprint;
+
+    if (!is_initialized(m)) { /* first-time initialization */
+      m->seg.base = m->least_addr = tbase;
+      m->seg.size = tsize;
+      m->seg.sflags = mmap_flag;
+      m->magic = mparams.magic;
+      init_bins(m);
+      if (is_global(m)) 
+        init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE);
+      else {
+        /* Offset top by embedded malloc_state */
+        mchunkptr mn = next_chunk(mem2chunk(m));
+        init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) -TOP_FOOT_SIZE);
+      }
+    }
+
+    else {
+      /* Try to merge with an existing segment */
+      msegmentptr sp = &m->seg;
+      while (sp != 0 && tbase != sp->base + sp->size)
+        sp = sp->next;
+      if (sp != 0 &&
+          !is_extern_segment(sp) &&
+          (sp->sflags & IS_MMAPPED_BIT) == mmap_flag &&
+          segment_holds(sp, m->top)) { /* append */
+        sp->size += tsize;
+        init_top(m, m->top, m->topsize + tsize);
+      }
+      else {
+        if (tbase < m->least_addr)
+          m->least_addr = tbase;
+        sp = &m->seg;
+        while (sp != 0 && sp->base != tbase + tsize)
+          sp = sp->next;
+        if (sp != 0 &&
+            !is_extern_segment(sp) &&
+            (sp->sflags & IS_MMAPPED_BIT) == mmap_flag) {
+          char* oldbase = sp->base;
+          sp->base = tbase;
+          sp->size += tsize;
+          return prepend_alloc(m, tbase, oldbase, nb);
+        }
+        else
+          add_segment(m, tbase, tsize, mmap_flag);
+      }
+    }
+
+    if (nb < m->topsize) { /* Allocate from new or extended top space */
+      size_t rsize = m->topsize -= nb;
+      mchunkptr p = m->top;
+      mchunkptr r = m->top = chunk_plus_offset(p, nb);
+      r->head = rsize | PINUSE_BIT;
+      set_size_and_pinuse_of_inuse_chunk(m, p, nb);
+      check_top_chunk(m, m->top);
+      check_malloced_chunk(m, chunk2mem(p), nb);
+      return chunk2mem(p);
+    }
+  }
+
+  MALLOC_FAILURE_ACTION;
+  return 0;
+}
+
+/* -----------------------  system deallocation -------------------------- */
+
+/* Unmap and unlink any mmapped segments that don't contain used chunks */
+static size_t release_unused_segments(mstate m) {
+  size_t released = 0;
+  msegmentptr pred = &m->seg;
+  msegmentptr sp = pred->next;
+  while (sp != 0) {
+    char* base = sp->base;
+    size_t size = sp->size;
+    msegmentptr next = sp->next;
+    if (is_mmapped_segment(sp) && !is_extern_segment(sp)) {
+      mchunkptr p = align_as_chunk(base);
+      size_t psize = chunksize(p);
+      /* Can unmap if first chunk holds entire segment and not pinned */
+      if (!cinuse(p) && (char*)p + psize >= base + size - TOP_FOOT_SIZE) {
+        tchunkptr tp = (tchunkptr)p;
+        assert(segment_holds(sp, (char*)sp));
+        if (p == m->dv) {
+          m->dv = 0;
+          m->dvsize = 0;
+        }
+        else {
+          unlink_large_chunk(m, tp);
+        }
+        if (CALL_MUNMAP(base, size) == 0) {
+          released += size;
+          m->footprint -= size;
+          /* unlink obsoleted record */
+          sp = pred;
+          sp->next = next;
+        }
+        else { /* back out if cannot unmap */
+          insert_large_chunk(m, tp, psize);
+        }
+      }
+    }
+    pred = sp;
+    sp = next;
+  }
+  return released;
+}
+
+static int sys_trim(mstate m, size_t pad) {
+  size_t released = 0;
+  if (pad < MAX_REQUEST && is_initialized(m)) {
+    pad += TOP_FOOT_SIZE; /* ensure enough room for segment overhead */
+
+    if (m->topsize > pad) {
+      /* Shrink top space in granularity-size units, keeping at least one */
+      size_t unit = mparams.granularity;
+      size_t extra = ((m->topsize - pad + (unit - SIZE_T_ONE)) / unit -
+                      SIZE_T_ONE) * unit;
+      msegmentptr sp = segment_holding(m, (char*)m->top);
+
+      if (!is_extern_segment(sp)) {
+        if (is_mmapped_segment(sp)) {
+          if (HAVE_MMAP &&
+              sp->size >= extra &&
+              !has_segment_link(m, sp)) { /* can't shrink if pinned */
+            size_t newsize = sp->size - extra;
+            /* Prefer mremap, fall back to munmap */
+            if ((CALL_MREMAP(sp->base, sp->size, newsize, 0) != MFAIL) ||
+                (CALL_MUNMAP(sp->base + newsize, extra) == 0)) {
+              released = extra;
+            }
+          }
+        }
+        else if (HAVE_MORECORE) {
+          if (extra >= HALF_MAX_SIZE_T) /* Avoid wrapping negative */
+            extra = (HALF_MAX_SIZE_T) + SIZE_T_ONE - unit;
+          ACQUIRE_MORECORE_LOCK();
+          {
+            /* Make sure end of memory is where we last set it. */
+            char* old_br = (char*)(CALL_MORECORE(0));
+            if (old_br == sp->base + sp->size) {
+              char* rel_br = (char*)(CALL_MORECORE(-extra));
+              char* new_br = (char*)(CALL_MORECORE(0));
+              if (rel_br != CMFAIL && new_br < old_br)
+                released = old_br - new_br;
+            }
+          }
+          RELEASE_MORECORE_LOCK();
+        }
+      }
+
+      if (released != 0) {
+        sp->size -= released;
+        m->footprint -= released;
+        init_top(m, m->top, m->topsize - released);
+        check_top_chunk(m, m->top);
+      }
+    }
+
+    /* Unmap any unused mmapped segments */
+    if (HAVE_MMAP) 
+      released += release_unused_segments(m);
+
+    /* On failure, disable autotrim to avoid repeated failed future calls */
+    if (released == 0)
+      m->trim_check = MAX_SIZE_T;
+  }
+
+  return (released != 0)? 1 : 0;
+}
+
+/* ---------------------------- malloc support --------------------------- */
+
+/* allocate a large request from the best fitting chunk in a treebin */
+static void* tmalloc_large(mstate m, size_t nb) {
+  tchunkptr v = 0;
+  size_t rsize = -nb; /* Unsigned negation */
+  tchunkptr t;
+  bindex_t idx;
+  compute_tree_index(nb, idx);
+
+  if ((t = *treebin_at(m, idx)) != 0) {
+    /* Traverse tree for this bin looking for node with size == nb */
+    size_t sizebits = nb << leftshift_for_tree_index(idx);
+    tchunkptr rst = 0;  /* The deepest untaken right subtree */
+    for (;;) {
+      tchunkptr rt;
+      size_t trem = chunksize(t) - nb;
+      if (trem < rsize) {
+        v = t;
+        if ((rsize = trem) == 0)
+          break;
+      }
+      rt = t->child[1];
+      t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1];
+      if (rt != 0 && rt != t)
+        rst = rt;
+      if (t == 0) {
+        t = rst; /* set t to least subtree holding sizes > nb */
+        break;
+      }
+      sizebits <<= 1;
+    }
+  }
+
+  if (t == 0 && v == 0) { /* set t to root of next non-empty treebin */
+    binmap_t leftbits = left_bits(idx2bit(idx)) & m->treemap;
+    if (leftbits != 0) {
+      bindex_t i;
+      binmap_t leastbit = least_bit(leftbits);
+      compute_bit2idx(leastbit, i);
+      t = *treebin_at(m, i);
+    }
+  }
+
+  while (t != 0) { /* find smallest of tree or subtree */
+    size_t trem = chunksize(t) - nb;
+    if (trem < rsize) {
+      rsize = trem;
+      v = t;
+    }
+    t = leftmost_child(t);
+  }
+
+  /*  If dv is a better fit, return 0 so malloc will use it */
+  if (v != 0 && rsize < (size_t)(m->dvsize - nb)) {
+    if (RTCHECK(ok_address(m, v))) { /* split */
+      mchunkptr r = chunk_plus_offset(v, nb);
+      assert(chunksize(v) == rsize + nb);
+      if (RTCHECK(ok_next(v, r))) {
+        unlink_large_chunk(m, v);
+        if (rsize < MIN_CHUNK_SIZE)
+          set_inuse_and_pinuse(m, v, (rsize + nb));
+        else {
+          set_size_and_pinuse_of_inuse_chunk(m, v, nb);
+          set_size_and_pinuse_of_free_chunk(r, rsize);
+          insert_chunk(m, r, rsize);
+        }
+        return chunk2mem(v);
+      }
+    }
+    CORRUPTION_ERROR_ACTION(m);
+  }
+  return 0;
+}
+
+/* allocate a small request from the best fitting chunk in a treebin */
+static void* tmalloc_small(mstate m, size_t nb) {
+  tchunkptr t, v;
+  size_t rsize;
+  bindex_t i;
+  binmap_t leastbit = least_bit(m->treemap);
+  compute_bit2idx(leastbit, i);
+
+  v = t = *treebin_at(m, i);
+  rsize = chunksize(t) - nb;
+
+  while ((t = leftmost_child(t)) != 0) {
+    size_t trem = chunksize(t) - nb;
+    if (trem < rsize) {
+      rsize = trem;
+      v = t;
+    }
+  }
+
+  if (RTCHECK(ok_address(m, v))) {
+    mchunkptr r = chunk_plus_offset(v, nb);
+    assert(chunksize(v) == rsize + nb);
+    if (RTCHECK(ok_next(v, r))) {
+      unlink_large_chunk(m, v);
+      if (rsize < MIN_CHUNK_SIZE)
+        set_inuse_and_pinuse(m, v, (rsize + nb));
+      else {
+        set_size_and_pinuse_of_inuse_chunk(m, v, nb);
+        set_size_and_pinuse_of_free_chunk(r, rsize);
+        replace_dv(m, r, rsize);
+      }
+      return chunk2mem(v);
+    }
+  }
+
+  CORRUPTION_ERROR_ACTION(m);
+  return 0;
+}
+
+/* --------------------------- realloc support --------------------------- */
+
+static void* internal_realloc(mstate m, void* oldmem, size_t bytes) {
+  if (bytes >= MAX_REQUEST) {
+    MALLOC_FAILURE_ACTION;
+    return 0;
+  }
+  if (!PREACTION(m)) {
+    mchunkptr oldp = mem2chunk(oldmem);
+    size_t oldsize = chunksize(oldp);
+    mchunkptr next = chunk_plus_offset(oldp, oldsize);
+    mchunkptr newp = 0;
+    void* extra = 0;
+
+    /* Try to either shrink or extend into top. Else malloc-copy-free */
+
+    if (RTCHECK(ok_address(m, oldp) && ok_cinuse(oldp) &&
+                ok_next(oldp, next) && ok_pinuse(next))) {
+      size_t nb = request2size(bytes);
+      if (is_mmapped(oldp))
+        newp = mmap_resize(m, oldp, nb);
+      else if (oldsize >= nb) { /* already big enough */
+        size_t rsize = oldsize - nb;
+        newp = oldp;
+        if (rsize >= MIN_CHUNK_SIZE) {
+          mchunkptr remainder = chunk_plus_offset(newp, nb);
+          set_inuse(m, newp, nb);
+          set_inuse(m, remainder, rsize);
+          extra = chunk2mem(remainder);
+        }
+      }
+      else if (next == m->top && oldsize + m->topsize > nb) {
+        /* Expand into top */
+        size_t newsize = oldsize + m->topsize;
+        size_t newtopsize = newsize - nb;
+        mchunkptr newtop = chunk_plus_offset(oldp, nb);
+        set_inuse(m, oldp, nb);
+        newtop->head = newtopsize |PINUSE_BIT;
+        m->top = newtop;
+        m->topsize = newtopsize;
+        newp = oldp;
+      }
+    }
+    else {
+      USAGE_ERROR_ACTION(m, oldmem);
+      POSTACTION(m);
+      return 0;
+    }
+
+    POSTACTION(m);
+
+    if (newp != 0) {
+      if (extra != 0) {
+        internal_free(m, extra);
+      }
+      check_inuse_chunk(m, newp);
+      return chunk2mem(newp);
+    }
+    else {
+      void* newmem = internal_malloc(m, bytes);
+      if (newmem != 0) {
+        size_t oc = oldsize - overhead_for(oldp);
+        memcpy(newmem, oldmem, (oc < bytes)? oc : bytes);
+        internal_free(m, oldmem);
+      }
+      return newmem;
+    }
+  }
+  return 0;
+}
+
+/* --------------------------- memalign support -------------------------- */
+
+static void* internal_memalign(mstate m, size_t alignment, size_t bytes) {
+  if (alignment <= MALLOC_ALIGNMENT)    /* Can just use malloc */
+    return internal_malloc(m, bytes);
+  if (alignment <  MIN_CHUNK_SIZE) /* must be at least a minimum chunk size */
+    alignment = MIN_CHUNK_SIZE;
+  if ((alignment & (alignment-SIZE_T_ONE)) != 0) {/* Ensure a power of 2 */
+    size_t a = MALLOC_ALIGNMENT << 1;
+    while (a < alignment) a <<= 1;
+    alignment = a;
+  }
+  
+  if (bytes >= MAX_REQUEST - alignment) {
+    if (m != 0)  { /* Test isn't needed but avoids compiler warning */
+      MALLOC_FAILURE_ACTION;
+    }
+  }
+  else {
+    size_t nb = request2size(bytes);
+    size_t req = nb + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD;
+    char* mem = (char*)internal_malloc(m, req);
+    if (mem != 0) {
+      void* leader = 0;
+      void* trailer = 0;
+      mchunkptr p = mem2chunk(mem);
+
+      if (PREACTION(m)) return 0;
+      if ((((size_t)(mem)) % alignment) != 0) { /* misaligned */
+        /*
+          Find an aligned spot inside chunk.  Since we need to give
+          back leading space in a chunk of at least MIN_CHUNK_SIZE, if
+          the first calculation places us at a spot with less than
+          MIN_CHUNK_SIZE leader, we can move to the next aligned spot.
+          We've allocated enough total room so that this is always
+          possible.
+        */
+        char* br = (char*)mem2chunk((size_t)(((size_t)(mem +
+                                                       alignment -
+                                                       SIZE_T_ONE)) &
+                                             -alignment));
+        char* pos = ((size_t)(br - (char*)(p)) >= MIN_CHUNK_SIZE)?
+          br : br+alignment;
+        mchunkptr newp = (mchunkptr)pos;
+        size_t leadsize = pos - (char*)(p);
+        size_t newsize = chunksize(p) - leadsize;
+
+        if (is_mmapped(p)) { /* For mmapped chunks, just adjust offset */
+          newp->prev_foot = p->prev_foot + leadsize;
+          newp->head = (newsize|CINUSE_BIT);
+        }
+        else { /* Otherwise, give back leader, use the rest */
+          set_inuse(m, newp, newsize);
+          set_inuse(m, p, leadsize);
+          leader = chunk2mem(p);
+        }
+        p = newp;
+      }
+
+      /* Give back spare room at the end */
+      if (!is_mmapped(p)) {
+        size_t size = chunksize(p);
+        if (size > nb + MIN_CHUNK_SIZE) {
+          size_t remainder_size = size - nb;
+          mchunkptr remainder = chunk_plus_offset(p, nb);
+          set_inuse(m, p, nb);
+          set_inuse(m, remainder, remainder_size);
+          trailer = chunk2mem(remainder);
+        }
+      }
+
+      assert (chunksize(p) >= nb);
+      assert((((size_t)(chunk2mem(p))) % alignment) == 0);
+      check_inuse_chunk(m, p);
+      POSTACTION(m);
+      if (leader != 0) {
+        internal_free(m, leader);
+      }
+      if (trailer != 0) {
+        internal_free(m, trailer);
+      }
+      return chunk2mem(p);
+    }
+  }
+  return 0;
+}
+
+/* ------------------------ comalloc/coalloc support --------------------- */
+
+static void** ialloc(mstate m,
+                     size_t n_elements,
+                     size_t* sizes,
+                     int opts,
+                     void* chunks[]) {
+  /*
+    This provides common support for independent_X routines, handling
+    all of the combinations that can result.
+
+    The opts arg has:
+    bit 0 set if all elements are same size (using sizes[0])
+    bit 1 set if elements should be zeroed
+  */
+
+  size_t    element_size;   /* chunksize of each element, if all same */
+  size_t    contents_size;  /* total size of elements */
+  size_t    array_size;     /* request size of pointer array */
+  void*     mem;            /* malloced aggregate space */
+  mchunkptr p;              /* corresponding chunk */
+  size_t    remainder_size; /* remaining bytes while splitting */
+  void**    marray;         /* either "chunks" or malloced ptr array */
+  mchunkptr array_chunk;    /* chunk for malloced ptr array */
+  flag_t    was_enabled;    /* to disable mmap */
+  size_t    size;
+  size_t    i;
+
+  /* compute array length, if needed */
+  if (chunks != 0) {
+    if (n_elements == 0)
+      return chunks; /* nothing to do */
+    marray = chunks;
+    array_size = 0;
+  }
+  else {
+    /* if empty req, must still return chunk representing empty array */
+    if (n_elements == 0)
+      return (void**)internal_malloc(m, 0);
+    marray = 0;
+    array_size = request2size(n_elements * (sizeof(void*)));
+  }
+
+  /* compute total element size */
+  if (opts & 0x1) { /* all-same-size */
+    element_size = request2size(*sizes);
+    contents_size = n_elements * element_size;
+  }
+  else { /* add up all the sizes */
+    element_size = 0;
+    contents_size = 0;
+    for (i = 0; i != n_elements; ++i)
+      contents_size += request2size(sizes[i]);
+  }
+
+  size = contents_size + array_size;
+
+  /*
+     Allocate the aggregate chunk.  First disable direct-mmapping so
+     malloc won't use it, since we would not be able to later
+     free/realloc space internal to a segregated mmap region.
+  */
+  was_enabled = use_mmap(m);
+  disable_mmap(m);
+  mem = internal_malloc(m, size - CHUNK_OVERHEAD);
+  if (was_enabled)
+    enable_mmap(m);
+  if (mem == 0)
+    return 0;
+
+  if (PREACTION(m)) return 0;
+  p = mem2chunk(mem);
+  remainder_size = chunksize(p);
+
+  assert(!is_mmapped(p));
+
+  if (opts & 0x2) {       /* optionally clear the elements */
+    memset((size_t*)mem, 0, remainder_size - SIZE_T_SIZE - array_size);
+  }
+
+  /* If not provided, allocate the pointer array as final part of chunk */
+  if (marray == 0) {
+    size_t  array_chunk_size;
+    array_chunk = chunk_plus_offset(p, contents_size);
+    array_chunk_size = remainder_size - contents_size;
+    marray = (void**) (chunk2mem(array_chunk));
+    set_size_and_pinuse_of_inuse_chunk(m, array_chunk, array_chunk_size);
+    remainder_size = contents_size;
+  }
+
+  /* split out elements */
+  for (i = 0; ; ++i) {
+    marray[i] = chunk2mem(p);
+    if (i != n_elements-1) {
+      if (element_size != 0)
+        size = element_size;
+      else
+        size = request2size(sizes[i]);
+      remainder_size -= size;
+      set_size_and_pinuse_of_inuse_chunk(m, p, size);
+      p = chunk_plus_offset(p, size);
+    }
+    else { /* the final element absorbs any overallocation slop */
+      set_size_and_pinuse_of_inuse_chunk(m, p, remainder_size);
+      break;
+    }
+  }
+
+#if DEBUG
+  if (marray != chunks) {
+    /* final element must have exactly exhausted chunk */
+    if (element_size != 0) {
+      assert(remainder_size == element_size);
+    }
+    else {
+      assert(remainder_size == request2size(sizes[i]));
+    }
+    check_inuse_chunk(m, mem2chunk(marray));
+  }
+  for (i = 0; i != n_elements; ++i)
+    check_inuse_chunk(m, mem2chunk(marray[i]));
+
+#endif /* DEBUG */
+
+  POSTACTION(m);
+  return marray;
+}
+
+
+/* -------------------------- public routines ---------------------------- */
+
+#if !ONLY_MSPACES
+
+void* dlmalloc(size_t bytes) {
+  /*
+     Basic algorithm:
+     If a small request (< 256 bytes minus per-chunk overhead):
+       1. If one exists, use a remainderless chunk in associated smallbin.
+          (Remainderless means that there are too few excess bytes to
+          represent as a chunk.)
+       2. If it is big enough, use the dv chunk, which is normally the
+          chunk adjacent to the one used for the most recent small request.
+       3. If one exists, split the smallest available chunk in a bin,
+          saving remainder in dv.
+       4. If it is big enough, use the top chunk.
+       5. If available, get memory from system and use it
+     Otherwise, for a large request:
+       1. Find the smallest available binned chunk that fits, and use it
+          if it is better fitting than dv chunk, splitting if necessary.
+       2. If better fitting than any binned chunk, use the dv chunk.
+       3. If it is big enough, use the top chunk.
+       4. If request size >= mmap threshold, try to directly mmap this chunk.
+       5. If available, get memory from system and use it
+
+     The ugly goto's here ensure that postaction occurs along all paths.
+  */
+
+  if (!PREACTION(gm)) {
+    void* mem;
+    size_t nb;
+    if (bytes <= MAX_SMALL_REQUEST) {
+      bindex_t idx;
+      binmap_t smallbits;
+      nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes);
+      idx = small_index(nb);
+      smallbits = gm->smallmap >> idx;
+
+      if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */
+        mchunkptr b, p;
+        idx += ~smallbits & 1;       /* Uses next bin if idx empty */
+        b = smallbin_at(gm, idx);
+        p = b->fd;
+        assert(chunksize(p) == small_index2size(idx));
+        unlink_first_small_chunk(gm, b, p, idx);
+        set_inuse_and_pinuse(gm, p, small_index2size(idx));
+        mem = chunk2mem(p);
+        check_malloced_chunk(gm, mem, nb);
+        goto postaction;
+      }
+
+      else if (nb > gm->dvsize) {
+        if (smallbits != 0) { /* Use chunk in next nonempty smallbin */
+          mchunkptr b, p, r;
+          size_t rsize;
+          bindex_t i;
+          binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx));
+          binmap_t leastbit = least_bit(leftbits);
+          compute_bit2idx(leastbit, i);
+          b = smallbin_at(gm, i);
+          p = b->fd;
+          assert(chunksize(p) == small_index2size(i));
+          unlink_first_small_chunk(gm, b, p, i);
+          rsize = small_index2size(i) - nb;
+          /* Fit here cannot be remainderless if 4byte sizes */
+          if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)
+            set_inuse_and_pinuse(gm, p, small_index2size(i));
+          else {
+            set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
+            r = chunk_plus_offset(p, nb);
+            set_size_and_pinuse_of_free_chunk(r, rsize);
+            replace_dv(gm, r, rsize);
+          }
+          mem = chunk2mem(p);
+          check_malloced_chunk(gm, mem, nb);
+          goto postaction;
+        }
+
+        else if (gm->treemap != 0 && (mem = tmalloc_small(gm, nb)) != 0) {
+          check_malloced_chunk(gm, mem, nb);
+          goto postaction;
+        }
+      }
+    }
+    else if (bytes >= MAX_REQUEST)
+      nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */
+    else {
+      nb = pad_request(bytes);
+      if (gm->treemap != 0 && (mem = tmalloc_large(gm, nb)) != 0) {
+        check_malloced_chunk(gm, mem, nb);
+        goto postaction;
+      }
+    }
+
+    if (nb <= gm->dvsize) {
+      size_t rsize = gm->dvsize - nb;
+      mchunkptr p = gm->dv;
+      if (rsize >= MIN_CHUNK_SIZE) { /* split dv */
+        mchunkptr r = gm->dv = chunk_plus_offset(p, nb);
+        gm->dvsize = rsize;
+        set_size_and_pinuse_of_free_chunk(r, rsize);
+        set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
+      }
+      else { /* exhaust dv */
+        size_t dvs = gm->dvsize;
+        gm->dvsize = 0;
+        gm->dv = 0;
+        set_inuse_and_pinuse(gm, p, dvs);
+      }
+      mem = chunk2mem(p);
+      check_malloced_chunk(gm, mem, nb);
+      goto postaction;
+    }
+
+    else if (nb < gm->topsize) { /* Split top */
+      size_t rsize = gm->topsize -= nb;
+      mchunkptr p = gm->top;
+      mchunkptr r = gm->top = chunk_plus_offset(p, nb);
+      r->head = rsize | PINUSE_BIT;
+      set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
+      mem = chunk2mem(p);
+      check_top_chunk(gm, gm->top);
+      check_malloced_chunk(gm, mem, nb);
+      goto postaction;
+    }
+
+    mem = sys_alloc(gm, nb);
+
+  postaction:
+    POSTACTION(gm);
+    return mem;
+  }
+
+  return 0;
+}
+
+void dlfree(void* mem) {
+  /*
+     Consolidate freed chunks with preceeding or succeeding bordering
+     free chunks, if they exist, and then place in a bin.  Intermixed
+     with special cases for top, dv, mmapped chunks, and usage errors.
+  */
+
+  if (mem != 0) {
+    mchunkptr p  = mem2chunk(mem);
+#if FOOTERS
+    mstate fm = get_mstate_for(p);
+    if (!ok_magic(fm)) {
+      USAGE_ERROR_ACTION(fm, p);
+      return;
+    }
+#else /* FOOTERS */
+#define fm gm
+#endif /* FOOTERS */
+    if (!PREACTION(fm)) {
+      check_inuse_chunk(fm, p);
+      if (RTCHECK(ok_address(fm, p) && ok_cinuse(p))) {
+        size_t psize = chunksize(p);
+        mchunkptr next = chunk_plus_offset(p, psize);
+        if (!pinuse(p)) {
+          size_t prevsize = p->prev_foot;
+          if ((prevsize & IS_MMAPPED_BIT) != 0) {
+            prevsize &= ~IS_MMAPPED_BIT;
+            psize += prevsize + MMAP_FOOT_PAD;
+            if (CALL_MUNMAP((char*)p - prevsize, psize) == 0)
+              fm->footprint -= psize;
+            goto postaction;
+          }
+          else {
+            mchunkptr prev = chunk_minus_offset(p, prevsize);
+            psize += prevsize;
+            p = prev;
+            if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */
+              if (p != fm->dv) {
+                unlink_chunk(fm, p, prevsize);
+              }
+              else if ((next->head & INUSE_BITS) == INUSE_BITS) {
+                fm->dvsize = psize;
+                set_free_with_pinuse(p, psize, next);
+                goto postaction;
+              }
+            }
+            else
+              goto erroraction;
+          }
+        }
+
+        if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {
+          if (!cinuse(next)) {  /* consolidate forward */
+            if (next == fm->top) {
+              size_t tsize = fm->topsize += psize;
+              fm->top = p;
+              p->head = tsize | PINUSE_BIT;
+              if (p == fm->dv) {
+                fm->dv = 0;
+                fm->dvsize = 0;
+              }
+              if (should_trim(fm, tsize))
+                sys_trim(fm, 0);
+              goto postaction;
+            }
+            else if (next == fm->dv) {
+              size_t dsize = fm->dvsize += psize;
+              fm->dv = p;
+              set_size_and_pinuse_of_free_chunk(p, dsize);
+              goto postaction;
+            }
+            else {
+              size_t nsize = chunksize(next);
+              psize += nsize;
+              unlink_chunk(fm, next, nsize);
+              set_size_and_pinuse_of_free_chunk(p, psize);
+              if (p == fm->dv) {
+                fm->dvsize = psize;
+                goto postaction;
+              }
+            }
+          }
+          else
+            set_free_with_pinuse(p, psize, next);
+          insert_chunk(fm, p, psize);
+          check_free_chunk(fm, p);
+          goto postaction;
+        }
+      }
+    erroraction:
+      USAGE_ERROR_ACTION(fm, p);
+    postaction:
+      POSTACTION(fm);
+    }
+  }
+#if !FOOTERS
+#undef fm
+#endif /* FOOTERS */
+}
+
+void* dlcalloc(size_t n_elements, size_t elem_size) {
+  void* mem;
+  size_t req = 0;
+  if (n_elements != 0) {
+    req = n_elements * elem_size;
+    if (((n_elements | elem_size) & ~(size_t)0xffff) &&
+        (req / n_elements != elem_size))
+      req = MAX_SIZE_T; /* force downstream failure on overflow */
+  }
+  mem = dlmalloc(req);
+  if (mem != 0 && calloc_must_clear(mem2chunk(mem)))
+    memset(mem, 0, req);
+  return mem;
+}
+
+void* dlrealloc(void* oldmem, size_t bytes) {
+  if (oldmem == 0)
+    return dlmalloc(bytes);
+#ifdef REALLOC_ZERO_BYTES_FREES
+  if (bytes == 0) {
+    dlfree(oldmem);
+    return 0;
+  }
+#endif /* REALLOC_ZERO_BYTES_FREES */
+  else {
+#if ! FOOTERS
+    mstate m = gm;
+#else /* FOOTERS */
+    mstate m = get_mstate_for(mem2chunk(oldmem));
+    if (!ok_magic(m)) {
+      USAGE_ERROR_ACTION(m, oldmem);
+      return 0;
+    }
+#endif /* FOOTERS */
+    return internal_realloc(m, oldmem, bytes);
+  }
+}
+
+void* dlmemalign(size_t alignment, size_t bytes) {
+  return internal_memalign(gm, alignment, bytes);
+}
+
+void** dlindependent_calloc(size_t n_elements, size_t elem_size,
+                                 void* chunks[]) {
+  size_t sz = elem_size; /* serves as 1-element array */
+  return ialloc(gm, n_elements, &sz, 3, chunks);
+}
+
+void** dlindependent_comalloc(size_t n_elements, size_t sizes[],
+                                   void* chunks[]) {
+  return ialloc(gm, n_elements, sizes, 0, chunks);
+}
+
+void* dlvalloc(size_t bytes) {
+  size_t pagesz;
+  init_mparams();
+  pagesz = mparams.page_size;
+  return dlmemalign(pagesz, bytes);
+}
+
+void* dlpvalloc(size_t bytes) {
+  size_t pagesz;
+  init_mparams();
+  pagesz = mparams.page_size;
+  return dlmemalign(pagesz, (bytes + pagesz - SIZE_T_ONE) & ~(pagesz - SIZE_T_ONE));
+}
+
+int dlmalloc_trim(size_t pad) {
+  int result = 0;
+  if (!PREACTION(gm)) {
+    result = sys_trim(gm, pad);
+    POSTACTION(gm);
+  }
+  return result;
+}
+
+size_t dlmalloc_footprint(void) {
+  return gm->footprint;
+}
+
+size_t dlmalloc_max_footprint(void) {
+  return gm->max_footprint;
+}
+
+#if !NO_MALLINFO
+struct mallinfo dlmallinfo(void) {
+  return internal_mallinfo(gm);
+}
+#endif /* NO_MALLINFO */
+
+void dlmalloc_stats() {
+  internal_malloc_stats(gm);
+}
+
+size_t dlmalloc_usable_size(void* mem) {
+  if (mem != 0) {
+    mchunkptr p = mem2chunk(mem);
+    if (cinuse(p))
+      return chunksize(p) - overhead_for(p);
+  }
+  return 0;
+}
+
+int dlmallopt(int param_number, int value) {
+  return change_mparam(param_number, value);
+}
+
+#endif /* !ONLY_MSPACES */
+
+/* ----------------------------- user mspaces ---------------------------- */
+
+#if MSPACES
+
+static mstate init_user_mstate(char* tbase, size_t tsize) {
+  size_t msize = pad_request(sizeof(struct malloc_state));
+  mchunkptr mn;
+  mchunkptr msp = align_as_chunk(tbase);
+  mstate m = (mstate)(chunk2mem(msp));
+  memset(m, 0, msize);
+  INITIAL_LOCK(&m->mutex);
+  msp->head = (msize|PINUSE_BIT|CINUSE_BIT);
+  m->seg.base = m->least_addr = tbase;
+  m->seg.size = m->footprint = m->max_footprint = tsize;
+  m->magic = mparams.magic;
+  m->mflags = mparams.default_mflags;
+  disable_contiguous(m);
+  init_bins(m);
+  mn = next_chunk(mem2chunk(m));
+  init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) - TOP_FOOT_SIZE);
+  check_top_chunk(m, m->top);
+  return m;
+}
+
+mspace create_mspace(size_t capacity, int locked) {
+  mstate m = 0;
+  size_t msize = pad_request(sizeof(struct malloc_state));
+  init_mparams(); /* Ensure pagesize etc initialized */
+
+  if (capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) {
+    size_t rs = ((capacity == 0)? mparams.granularity :
+                 (capacity + TOP_FOOT_SIZE + msize));
+    size_t tsize = granularity_align(rs);
+    char* tbase = (char*)(CALL_MMAP(tsize));
+    if (tbase != CMFAIL) {
+      m = init_user_mstate(tbase, tsize);
+      m->seg.sflags = IS_MMAPPED_BIT;
+      set_lock(m, locked);
+    }
+  }
+  return (mspace)m;
+}
+
+mspace create_mspace_with_base(void* base, size_t capacity, int locked) {
+  mstate m = 0;
+  size_t msize = pad_request(sizeof(struct malloc_state));
+  init_mparams(); /* Ensure pagesize etc initialized */
+
+  if (capacity > msize + TOP_FOOT_SIZE &&
+      capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) {
+    m = init_user_mstate((char*)base, capacity);
+    m->seg.sflags = EXTERN_BIT;
+    set_lock(m, locked);
+  }
+  return (mspace)m;
+}
+
+size_t destroy_mspace(mspace msp) {
+  size_t freed = 0;
+  mstate ms = (mstate)msp;
+  if (ok_magic(ms)) {
+    msegmentptr sp = &ms->seg;
+    while (sp != 0) {
+      char* base = sp->base;
+      size_t size = sp->size;
+      flag_t flag = sp->sflags;
+      sp = sp->next;
+      if ((flag & IS_MMAPPED_BIT) && !(flag & EXTERN_BIT) &&
+          CALL_MUNMAP(base, size) == 0)
+        freed += size;
+    }
+  }
+  else {
+    USAGE_ERROR_ACTION(ms,ms);
+  }
+  return freed;
+}
+
+/*
+  mspace versions of routines are near-clones of the global
+  versions. This is not so nice but better than the alternatives.
+*/
+
+
+void* mspace_malloc(mspace msp, size_t bytes) {
+  mstate ms = (mstate)msp;
+  if (!ok_magic(ms)) {
+    USAGE_ERROR_ACTION(ms,ms);
+    return 0;
+  }
+  if (!PREACTION(ms)) {
+    void* mem;
+    size_t nb;
+    if (bytes <= MAX_SMALL_REQUEST) {
+      bindex_t idx;
+      binmap_t smallbits;
+      nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes);
+      idx = small_index(nb);
+      smallbits = ms->smallmap >> idx;
+
+      if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */
+        mchunkptr b, p;
+        idx += ~smallbits & 1;       /* Uses next bin if idx empty */
+        b = smallbin_at(ms, idx);
+        p = b->fd;
+        assert(chunksize(p) == small_index2size(idx));
+        unlink_first_small_chunk(ms, b, p, idx);
+        set_inuse_and_pinuse(ms, p, small_index2size(idx));
+        mem = chunk2mem(p);
+        check_malloced_chunk(ms, mem, nb);
+        goto postaction;
+      }
+
+      else if (nb > ms->dvsize) {
+        if (smallbits != 0) { /* Use chunk in next nonempty smallbin */
+          mchunkptr b, p, r;
+          size_t rsize;
+          bindex_t i;
+          binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx));
+          binmap_t leastbit = least_bit(leftbits);
+          compute_bit2idx(leastbit, i);
+          b = smallbin_at(ms, i);
+          p = b->fd;
+          assert(chunksize(p) == small_index2size(i));
+          unlink_first_small_chunk(ms, b, p, i);
+          rsize = small_index2size(i) - nb;
+          /* Fit here cannot be remainderless if 4byte sizes */
+          if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)
+            set_inuse_and_pinuse(ms, p, small_index2size(i));
+          else {
+            set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
+            r = chunk_plus_offset(p, nb);
+            set_size_and_pinuse_of_free_chunk(r, rsize);
+            replace_dv(ms, r, rsize);
+          }
+          mem = chunk2mem(p);
+          check_malloced_chunk(ms, mem, nb);
+          goto postaction;
+        }
+
+        else if (ms->treemap != 0 && (mem = tmalloc_small(ms, nb)) != 0) {
+          check_malloced_chunk(ms, mem, nb);
+          goto postaction;
+        }
+      }
+    }
+    else if (bytes >= MAX_REQUEST)
+      nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */
+    else {
+      nb = pad_request(bytes);
+      if (ms->treemap != 0 && (mem = tmalloc_large(ms, nb)) != 0) {
+        check_malloced_chunk(ms, mem, nb);
+        goto postaction;
+      }
+    }
+
+    if (nb <= ms->dvsize) {
+      size_t rsize = ms->dvsize - nb;
+      mchunkptr p = ms->dv;
+      if (rsize >= MIN_CHUNK_SIZE) { /* split dv */
+        mchunkptr r = ms->dv = chunk_plus_offset(p, nb);
+        ms->dvsize = rsize;
+        set_size_and_pinuse_of_free_chunk(r, rsize);
+        set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
+      }
+      else { /* exhaust dv */
+        size_t dvs = ms->dvsize;
+        ms->dvsize = 0;
+        ms->dv = 0;
+        set_inuse_and_pinuse(ms, p, dvs);
+      }
+      mem = chunk2mem(p);
+      check_malloced_chunk(ms, mem, nb);
+      goto postaction;
+    }
+
+    else if (nb < ms->topsize) { /* Split top */
+      size_t rsize = ms->topsize -= nb;
+      mchunkptr p = ms->top;
+      mchunkptr r = ms->top = chunk_plus_offset(p, nb);
+      r->head = rsize | PINUSE_BIT;
+      set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
+      mem = chunk2mem(p);
+      check_top_chunk(ms, ms->top);
+      check_malloced_chunk(ms, mem, nb);
+      goto postaction;
+    }
+
+    mem = sys_alloc(ms, nb);
+
+  postaction:
+    POSTACTION(ms);
+    return mem;
+  }
+
+  return 0;
+}
+
+void mspace_free(mspace msp, void* mem) {
+  if (mem != 0) {
+    mchunkptr p  = mem2chunk(mem);
+#if FOOTERS
+    mstate fm = get_mstate_for(p);
+#else /* FOOTERS */
+    mstate fm = (mstate)msp;
+#endif /* FOOTERS */
+    if (!ok_magic(fm)) {
+      USAGE_ERROR_ACTION(fm, p);
+      return;
+    }
+    if (!PREACTION(fm)) {
+      check_inuse_chunk(fm, p);
+      if (RTCHECK(ok_address(fm, p) && ok_cinuse(p))) {
+        size_t psize = chunksize(p);
+        mchunkptr next = chunk_plus_offset(p, psize);
+        if (!pinuse(p)) {
+          size_t prevsize = p->prev_foot;
+          if ((prevsize & IS_MMAPPED_BIT) != 0) {
+            prevsize &= ~IS_MMAPPED_BIT;
+            psize += prevsize + MMAP_FOOT_PAD;
+            if (CALL_MUNMAP((char*)p - prevsize, psize) == 0)
+              fm->footprint -= psize;
+            goto postaction;
+          }
+          else {
+            mchunkptr prev = chunk_minus_offset(p, prevsize);
+            psize += prevsize;
+            p = prev;
+            if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */
+              if (p != fm->dv) {
+                unlink_chunk(fm, p, prevsize);
+              }
+              else if ((next->head & INUSE_BITS) == INUSE_BITS) {
+                fm->dvsize = psize;
+                set_free_with_pinuse(p, psize, next);
+                goto postaction;
+              }
+            }
+            else
+              goto erroraction;
+          }
+        }
+
+        if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {
+          if (!cinuse(next)) {  /* consolidate forward */
+            if (next == fm->top) {
+              size_t tsize = fm->topsize += psize;
+              fm->top = p;
+              p->head = tsize | PINUSE_BIT;
+              if (p == fm->dv) {
+                fm->dv = 0;
+                fm->dvsize = 0;
+              }
+              if (should_trim(fm, tsize))
+                sys_trim(fm, 0);
+              goto postaction;
+            }
+            else if (next == fm->dv) {
+              size_t dsize = fm->dvsize += psize;
+              fm->dv = p;
+              set_size_and_pinuse_of_free_chunk(p, dsize);
+              goto postaction;
+            }
+            else {
+              size_t nsize = chunksize(next);
+              psize += nsize;
+              unlink_chunk(fm, next, nsize);
+              set_size_and_pinuse_of_free_chunk(p, psize);
+              if (p == fm->dv) {
+                fm->dvsize = psize;
+                goto postaction;
+              }
+            }
+          }
+          else
+            set_free_with_pinuse(p, psize, next);
+          insert_chunk(fm, p, psize);
+          check_free_chunk(fm, p);
+          goto postaction;
+        }
+      }
+    erroraction:
+      USAGE_ERROR_ACTION(fm, p);
+    postaction:
+      POSTACTION(fm);
+    }
+  }
+}
+
+void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size) {
+  void* mem;
+  size_t req = 0;
+  mstate ms = (mstate)msp;
+  if (!ok_magic(ms)) {
+    USAGE_ERROR_ACTION(ms,ms);
+    return 0;
+  }
+  if (n_elements != 0) {
+    req = n_elements * elem_size;
+    if (((n_elements | elem_size) & ~(size_t)0xffff) &&
+        (req / n_elements != elem_size))
+      req = MAX_SIZE_T; /* force downstream failure on overflow */
+  }
+  mem = internal_malloc(ms, req);
+  if (mem != 0 && calloc_must_clear(mem2chunk(mem)))
+    memset(mem, 0, req);
+  return mem;
+}
+
+void* mspace_realloc(mspace msp, void* oldmem, size_t bytes) {
+  if (oldmem == 0)
+    return mspace_malloc(msp, bytes);
+#ifdef REALLOC_ZERO_BYTES_FREES
+  if (bytes == 0) {
+    mspace_free(msp, oldmem);
+    return 0;
+  }
+#endif /* REALLOC_ZERO_BYTES_FREES */
+  else {
+#if FOOTERS
+    mchunkptr p  = mem2chunk(oldmem);
+    mstate ms = get_mstate_for(p);
+#else /* FOOTERS */
+    mstate ms = (mstate)msp;
+#endif /* FOOTERS */
+    if (!ok_magic(ms)) {
+      USAGE_ERROR_ACTION(ms,ms);
+      return 0;
+    }
+    return internal_realloc(ms, oldmem, bytes);
+  }
+}
+
+void* mspace_memalign(mspace msp, size_t alignment, size_t bytes) {
+  mstate ms = (mstate)msp;
+  if (!ok_magic(ms)) {
+    USAGE_ERROR_ACTION(ms,ms);
+    return 0;
+  }
+  return internal_memalign(ms, alignment, bytes);
+}
+
+void** mspace_independent_calloc(mspace msp, size_t n_elements,
+                                 size_t elem_size, void* chunks[]) {
+  size_t sz = elem_size; /* serves as 1-element array */
+  mstate ms = (mstate)msp;
+  if (!ok_magic(ms)) {
+    USAGE_ERROR_ACTION(ms,ms);
+    return 0;
+  }
+  return ialloc(ms, n_elements, &sz, 3, chunks);
+}
+
+void** mspace_independent_comalloc(mspace msp, size_t n_elements,
+                                   size_t sizes[], void* chunks[]) {
+  mstate ms = (mstate)msp;
+  if (!ok_magic(ms)) {
+    USAGE_ERROR_ACTION(ms,ms);
+    return 0;
+  }
+  return ialloc(ms, n_elements, sizes, 0, chunks);
+}
+
+int mspace_trim(mspace msp, size_t pad) {
+  int result = 0;
+  mstate ms = (mstate)msp;
+  if (ok_magic(ms)) {
+    if (!PREACTION(ms)) {
+      result = sys_trim(ms, pad);
+      POSTACTION(ms);
+    }
+  }
+  else {
+    USAGE_ERROR_ACTION(ms,ms);
+  }
+  return result;
+}
+
+void mspace_malloc_stats(mspace msp) {
+  mstate ms = (mstate)msp;
+  if (ok_magic(ms)) {
+    internal_malloc_stats(ms);
+  }
+  else {
+    USAGE_ERROR_ACTION(ms,ms);
+  }
+}
+
+size_t mspace_footprint(mspace msp) {
+  size_t result;
+  mstate ms = (mstate)msp;
+  if (ok_magic(ms)) {
+    result = ms->footprint;
+  }
+  USAGE_ERROR_ACTION(ms,ms);
+  return result;
+}
+
+
+size_t mspace_max_footprint(mspace msp) {
+  size_t result;
+  mstate ms = (mstate)msp;
+  if (ok_magic(ms)) {
+    result = ms->max_footprint;
+  }
+  USAGE_ERROR_ACTION(ms,ms);
+  return result;
+}
+
+
+#if !NO_MALLINFO
+struct mallinfo mspace_mallinfo(mspace msp) {
+  mstate ms = (mstate)msp;
+  if (!ok_magic(ms)) {
+    USAGE_ERROR_ACTION(ms,ms);
+  }
+  return internal_mallinfo(ms);
+}
+#endif /* NO_MALLINFO */
+
+int mspace_mallopt(int param_number, int value) {
+  return change_mparam(param_number, value);
+}
+
+#endif /* MSPACES */
+
+/* -------------------- Alternative MORECORE functions ------------------- */
+
+/*
+  Guidelines for creating a custom version of MORECORE:
+
+  * For best performance, MORECORE should allocate in multiples of pagesize.
+  * MORECORE may allocate more memory than requested. (Or even less,
+      but this will usually result in a malloc failure.)
+  * MORECORE must not allocate memory when given argument zero, but
+      instead return one past the end address of memory from previous
+      nonzero call.
+  * For best performance, consecutive calls to MORECORE with positive
+      arguments should return increasing addresses, indicating that
+      space has been contiguously extended.
+  * Even though consecutive calls to MORECORE need not return contiguous
+      addresses, it must be OK for malloc'ed chunks to span multiple
+      regions in those cases where they do happen to be contiguous.
+  * MORECORE need not handle negative arguments -- it may instead
+      just return MFAIL when given negative arguments.
+      Negative arguments are always multiples of pagesize. MORECORE
+      must not misinterpret negative args as large positive unsigned
+      args. You can suppress all such calls from even occurring by defining
+      MORECORE_CANNOT_TRIM,
+
+  As an example alternative MORECORE, here is a custom allocator
+  kindly contributed for pre-OSX macOS.  It uses virtually but not
+  necessarily physically contiguous non-paged memory (locked in,
+  present and won't get swapped out).  You can use it by uncommenting
+  this section, adding some #includes, and setting up the appropriate
+  defines above:
+
+      #define MORECORE osMoreCore
+
+  There is also a shutdown routine that should somehow be called for
+  cleanup upon program exit.
+
+  #define MAX_POOL_ENTRIES 100
+  #define MINIMUM_MORECORE_SIZE  (64 * 1024U)
+  static int next_os_pool;
+  void *our_os_pools[MAX_POOL_ENTRIES];
+
+  void *osMoreCore(int size)
+  {
+    void *ptr = 0;
+    static void *sbrk_top = 0;
+
+    if (size > 0)
+    {
+      if (size < MINIMUM_MORECORE_SIZE)
+         size = MINIMUM_MORECORE_SIZE;
+      if (CurrentExecutionLevel() == kTaskLevel)
+         ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);
+      if (ptr == 0)
+      {
+        return (void *) MFAIL;
+      }
+      // save ptrs so they can be freed during cleanup
+      our_os_pools[next_os_pool] = ptr;
+      next_os_pool++;
+      ptr = (void *) ((((size_t) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);
+      sbrk_top = (char *) ptr + size;
+      return ptr;
+    }
+    else if (size < 0)
+    {
+      // we don't currently support shrink behavior
+      return (void *) MFAIL;
+    }
+    else
+    {
+      return sbrk_top;
+    }
+  }
+
+  // cleanup any allocated memory pools
+  // called as last thing before shutting down driver
+
+  void osCleanupMem(void)
+  {
+    void **ptr;
+
+    for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)
+      if (*ptr)
+      {
+         PoolDeallocate(*ptr);
+         *ptr = 0;
+      }
+  }
+
+*/
+
+
+/* -----------------------------------------------------------------------
+History:
+    V2.8.3 Thu Sep 22 11:16:32 2005  Doug Lea  (dl at gee)
+      * Add max_footprint functions
+      * Ensure all appropriate literals are size_t
+      * Fix conditional compilation problem for some #define settings
+      * Avoid concatenating segments with the one provided
+        in create_mspace_with_base
+      * Rename some variables to avoid compiler shadowing warnings
+      * Use explicit lock initialization.
+      * Better handling of sbrk interference.
+      * Simplify and fix segment insertion, trimming and mspace_destroy
+      * Reinstate REALLOC_ZERO_BYTES_FREES option from 2.7.x
+      * Thanks especially to Dennis Flanagan for help on these.
+
+    V2.8.2 Sun Jun 12 16:01:10 2005  Doug Lea  (dl at gee)
+      * Fix memalign brace error.
+
+    V2.8.1 Wed Jun  8 16:11:46 2005  Doug Lea  (dl at gee)
+      * Fix improper #endif nesting in C++
+      * Add explicit casts needed for C++
+
+    V2.8.0 Mon May 30 14:09:02 2005  Doug Lea  (dl at gee)
+      * Use trees for large bins
+      * Support mspaces
+      * Use segments to unify sbrk-based and mmap-based system allocation,
+        removing need for emulation on most platforms without sbrk.
+      * Default safety checks
+      * Optional footer checks. Thanks to William Robertson for the idea.
+      * Internal code refactoring
+      * Incorporate suggestions and platform-specific changes.
+        Thanks to Dennis Flanagan, Colin Plumb, Niall Douglas,
+        Aaron Bachmann,  Emery Berger, and others.
+      * Speed up non-fastbin processing enough to remove fastbins.
+      * Remove useless cfree() to avoid conflicts with other apps.
+      * Remove internal memcpy, memset. Compilers handle builtins better.
+      * Remove some options that no one ever used and rename others.
+
+    V2.7.2 Sat Aug 17 09:07:30 2002  Doug Lea  (dl at gee)
+      * Fix malloc_state bitmap array misdeclaration
+
+    V2.7.1 Thu Jul 25 10:58:03 2002  Doug Lea  (dl at gee)
+      * Allow tuning of FIRST_SORTED_BIN_SIZE
+      * Use PTR_UINT as type for all ptr->int casts. Thanks to John Belmonte.
+      * Better detection and support for non-contiguousness of MORECORE.
+        Thanks to Andreas Mueller, Conal Walsh, and Wolfram Gloger
+      * Bypass most of malloc if no frees. Thanks To Emery Berger.
+      * Fix freeing of old top non-contiguous chunk im sysmalloc.
+      * Raised default trim and map thresholds to 256K.
+      * Fix mmap-related #defines. Thanks to Lubos Lunak.
+      * Fix copy macros; added LACKS_FCNTL_H. Thanks to Neal Walfield.
+      * Branch-free bin calculation
+      * Default trim and mmap thresholds now 256K.
+
+    V2.7.0 Sun Mar 11 14:14:06 2001  Doug Lea  (dl at gee)
+      * Introduce independent_comalloc and independent_calloc.
+        Thanks to Michael Pachos for motivation and help.
+      * Make optional .h file available
+      * Allow > 2GB requests on 32bit systems.
+      * new WIN32 sbrk, mmap, munmap, lock code from <Walter at GeNeSys-e.de>.
+        Thanks also to Andreas Mueller <a.mueller at paradatec.de>,
+        and Anonymous.
+      * Allow override of MALLOC_ALIGNMENT (Thanks to Ruud Waij for
+        helping test this.)
+      * memalign: check alignment arg
+      * realloc: don't try to shift chunks backwards, since this
+        leads to  more fragmentation in some programs and doesn't
+        seem to help in any others.
+      * Collect all cases in malloc requiring system memory into sysmalloc
+      * Use mmap as backup to sbrk
+      * Place all internal state in malloc_state
+      * Introduce fastbins (although similar to 2.5.1)
+      * Many minor tunings and cosmetic improvements
+      * Introduce USE_PUBLIC_MALLOC_WRAPPERS, USE_MALLOC_LOCK
+      * Introduce MALLOC_FAILURE_ACTION, MORECORE_CONTIGUOUS
+        Thanks to Tony E. Bennett <tbennett at nvidia.com> and others.
+      * Include errno.h to support default failure action.
+
+    V2.6.6 Sun Dec  5 07:42:19 1999  Doug Lea  (dl at gee)
+      * return null for negative arguments
+      * Added Several WIN32 cleanups from Martin C. Fong <mcfong at yahoo.com>
+         * Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h'
+          (e.g. WIN32 platforms)
+         * Cleanup header file inclusion for WIN32 platforms
+         * Cleanup code to avoid Microsoft Visual C++ compiler complaints
+         * Add 'USE_DL_PREFIX' to quickly allow co-existence with existing
+           memory allocation routines
+         * Set 'malloc_getpagesize' for WIN32 platforms (needs more work)
+         * Use 'assert' rather than 'ASSERT' in WIN32 code to conform to
+           usage of 'assert' in non-WIN32 code
+         * Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to
+           avoid infinite loop
+      * Always call 'fREe()' rather than 'free()'
+
+    V2.6.5 Wed Jun 17 15:57:31 1998  Doug Lea  (dl at gee)
+      * Fixed ordering problem with boundary-stamping
+
+    V2.6.3 Sun May 19 08:17:58 1996  Doug Lea  (dl at gee)
+      * Added pvalloc, as recommended by H.J. Liu
+      * Added 64bit pointer support mainly from Wolfram Gloger
+      * Added anonymously donated WIN32 sbrk emulation
+      * Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen
+      * malloc_extend_top: fix mask error that caused wastage after
+        foreign sbrks
+      * Add linux mremap support code from HJ Liu
+
+    V2.6.2 Tue Dec  5 06:52:55 1995  Doug Lea  (dl at gee)
+      * Integrated most documentation with the code.
+      * Add support for mmap, with help from
+        Wolfram Gloger (Gloger at lrz.uni-muenchen.de).
+      * Use last_remainder in more cases.
+      * Pack bins using idea from  colin at nyx10.cs.du.edu
+      * Use ordered bins instead of best-fit threshhold
+      * Eliminate block-local decls to simplify tracing and debugging.
+      * Support another case of realloc via move into top
+      * Fix error occuring when initial sbrk_base not word-aligned.
+      * Rely on page size for units instead of SBRK_UNIT to
+        avoid surprises about sbrk alignment conventions.
+      * Add mallinfo, mallopt. Thanks to Raymond Nijssen
+        (raymond at es.ele.tue.nl) for the suggestion.
+      * Add `pad' argument to malloc_trim and top_pad mallopt parameter.
+      * More precautions for cases where other routines call sbrk,
+        courtesy of Wolfram Gloger (Gloger at lrz.uni-muenchen.de).
+      * Added macros etc., allowing use in linux libc from
+        H.J. Lu (hjl at gnu.ai.mit.edu)
+      * Inverted this history list
+
+    V2.6.1 Sat Dec  2 14:10:57 1995  Doug Lea  (dl at gee)
+      * Re-tuned and fixed to behave more nicely with V2.6.0 changes.
+      * Removed all preallocation code since under current scheme
+        the work required to undo bad preallocations exceeds
+        the work saved in good cases for most test programs.
+      * No longer use return list or unconsolidated bins since
+        no scheme using them consistently outperforms those that don't
+        given above changes.
+      * Use best fit for very large chunks to prevent some worst-cases.
+      * Added some support for debugging
+
+    V2.6.0 Sat Nov  4 07:05:23 1995  Doug Lea  (dl at gee)
+      * Removed footers when chunks are in use. Thanks to
+        Paul Wilson (wilson at cs.texas.edu) for the suggestion.
+
+    V2.5.4 Wed Nov  1 07:54:51 1995  Doug Lea  (dl at gee)
+      * Added malloc_trim, with help from Wolfram Gloger
+        (wmglo at Dent.MED.Uni-Muenchen.DE).
+
+    V2.5.3 Tue Apr 26 10:16:01 1994  Doug Lea  (dl at g)
+
+    V2.5.2 Tue Apr  5 16:20:40 1994  Doug Lea  (dl at g)
+      * realloc: try to expand in both directions
+      * malloc: swap order of clean-bin strategy;
+      * realloc: only conditionally expand backwards
+      * Try not to scavenge used bins
+      * Use bin counts as a guide to preallocation
+      * Occasionally bin return list chunks in first scan
+      * Add a few optimizations from colin at nyx10.cs.du.edu
+
+    V2.5.1 Sat Aug 14 15:40:43 1993  Doug Lea  (dl at g)
+      * faster bin computation & slightly different binning
+      * merged all consolidations to one part of malloc proper
+         (eliminating old malloc_find_space & malloc_clean_bin)
+      * Scan 2 returns chunks (not just 1)
+      * Propagate failure in realloc if malloc returns 0
+      * Add stuff to allow compilation on non-ANSI compilers
+          from kpv at research.att.com
+
+    V2.5 Sat Aug  7 07:41:59 1993  Doug Lea  (dl at g.oswego.edu)
+      * removed potential for odd address access in prev_chunk
+      * removed dependency on getpagesize.h
+      * misc cosmetics and a bit more internal documentation
+      * anticosmetics: mangled names in macros to evade debugger strangeness
+      * tested on sparc, hp-700, dec-mips, rs6000
+          with gcc & native cc (hp, dec only) allowing
+          Detlefs & Zorn comparison study (in SIGPLAN Notices.)
+
+    Trial version Fri Aug 28 13:14:29 1992  Doug Lea  (dl at g.oswego.edu)
+      * Based loosely on libg++-1.2X malloc. (It retains some of the overall
+         structure of old version,  but most details differ.)
+ 
+*/
diff --git a/man/GenMatch.Rd b/man/GenMatch.Rd
new file mode 100644
index 0000000..4aaf425
--- /dev/null
+++ b/man/GenMatch.Rd
@@ -0,0 +1,438 @@
+\name{GenMatch}
+\alias{GenMatch}
+\title{Genetic Matching}
+\description{
+  This function finds optimal balance using multivariate matching where
+  a genetic search algorithm determines the weight each covariate is
+  given.  Balance is determined by examining cumulative probability
+  distribution functions of a variety of standardized statistics.  By
+  default, these statistics include t-tests and Kolmogorov-Smirnov
+  tests. A variety of descriptive statistics based on empirical-QQ
+  (eQQ) plots can also be used or any user provided measure of balance.
+  The statistics are not used to conduct formal hypothesis tests,
+  because no measure of balance is a monotonic function of bias and
+  because balance should be maximized without limit. The object
+  returned by \code{GenMatch} can be supplied to the \code{\link{Match}}
+  function (via the \code{Weight.matrix} option) to obtain causal
+  estimates.  \code{GenMatch} uses \code{\link[rgenoud]{genoud}} to
+  perform the genetic search.  Using the \code{cluster} option, one may
+  use multiple computers, CPUs or cores to perform parallel
+  computations.
+}
+\usage{
+GenMatch(Tr, X, BalanceMatrix=X, estimand="ATT", M=1, weights=NULL,
+         pop.size = 100, max.generations=100,
+         wait.generations=4, hard.generation.limit=FALSE,
+         starting.values=rep(1,ncol(X)),
+         fit.func="pvals",
+         MemoryMatrix=TRUE,
+         exact=NULL, caliper=NULL, replace=TRUE, ties=TRUE,
+         CommonSupport=FALSE, nboots=0, ks=TRUE, verbose=FALSE,
+         distance.tolerance=1e-05,
+         tolerance=sqrt(.Machine$double.eps),
+         min.weight=0, max.weight=1000,
+         Domains=NULL, print.level=2,
+         project.path=NULL,
+         paired=TRUE, loss=1,
+         data.type.integer=FALSE,
+         restrict=NULL,
+         cluster=FALSE, balance=TRUE, ...)
+}
+\arguments{
+  \item{Tr}{ A vector indicating the observations which are in the
+    treatment regime and those which are not.  This can either be a
+    logical vector or a real vector where 0 denotes control and 1 denotes
+    treatment.}
+  \item{X}{ A matrix containing the variables we wish to match on.
+    This matrix may contain the actual observed covariates or the
+    propensity score or a combination of both.}
+  \item{BalanceMatrix}{ A matrix containing the variables we wish
+    to achieve balance on.  This is by default equal to \code{X}, but it can
+    in principle be a matrix which contains more or less variables than
+    \code{X} or variables which are transformed in various ways.  See
+    the examples.}
+  \item{estimand}{ A character string for the estimand.  The default
+    estimand is "ATT", the sample average treatment effect for the
+    treated. "ATE" is the sample average treatment effect, and
+    "ATC" is the sample average treatment effect for the controls.}
+  \item{M}{A scalar for the number of matches which should be
+    found. The default is one-to-one matching. Also see the \code{ties}
+    option.}
+  \item{weights}{ A vector the same length as \code{Y} which
+    provides observation specific weights.}
+  \item{pop.size}{Population Size.  This is the number of individuals
+    \code{\link[rgenoud]{genoud}} uses to solve the optimization problem.
+    The theorems proving that genetic algorithms find good solutions are
+    asymptotic in population size.  Therefore, it is important that this value not
+    be small.  See \code{\link[rgenoud]{genoud}} for more details.}
+  \item{max.generations}{ Maximum Generations.  This is the maximum
+    number of generations that \code{\link[rgenoud]{genoud}} will run when
+    optimizing.  This is a \emph{soft} limit.  The maximum generation
+    limit will be binding only if \code{hard.generation.limit} has been
+    set equal to \emph{TRUE}.  Otherwise, \code{wait.generations} controls
+    when optimization stops. See \code{\link[rgenoud]{genoud}} for more
+    details.}
+  \item{wait.generations}{If there is no improvement in the objective
+    function in this number of generations, optimization will stop.  The
+    other options controlling termination are \code{max.generations} and
+    \code{hard.generation.limit}.}
+  \item{hard.generation.limit}{ This logical variable determines if the
+    \code{max.generations} variable is a binding constraint.  If
+    \code{hard.generation.limit} is \emph{FALSE}, then
+    the algorithm may exceed the \code{max.generations}
+    count if the objective function has improved within a given number of
+    generations (determined by \code{wait.generations}).}
+  \item{starting.values}{
+    This vector's length is equal to the number of variables in \code{X}.  This
+    vector contains the starting weights each of the variables is
+    given. The \code{starting.values} vector is a way for the user
+    to insert \emph{one} individual into the starting population.
+    \code{\link[rgenoud]{genoud}} will randomly create the other individuals.  These values
+    correspond to the diagonal of the \code{Weight.matrix} as described
+    in detail in the \code{\link{Match}} function.}
+  \item{fit.func}{The balance metric \code{GenMatch} should optimize.
+    The user may choose from the following or provide a function:\cr
+    \code{pvals}: maximize the p.values from (paired) t-tests and
+    Kolmogorov-Smirnov tests conducted for each column in
+    \code{BalanceMatrix}.  Lexical optimization is conducted---see the
+    \code{loss} option for details.\cr
+    \code{qqmean.mean}: calculate the mean standardized difference in the eQQ
+    plot for each variable.  Minimize the mean of these differences across
+    variables.\cr
+    \code{qqmean.max}:  calculate the mean standardized difference in the eQQ
+    plot for each variable.  Minimize the maximum of these differences across
+    variables.  Lexical optimization is conducted.\cr
+    \code{qqmedian.mean}: calculate the median standardized difference in the eQQ
+    plot for each variable.  Minimize the median of these differences across
+    variables.\cr
+    \code{qqmedian.max}:  calculate the median standardized difference in the eQQ
+    plot for each variable.  Minimize the maximum of these differences across
+    variables.  Lexical optimization is conducted.\cr
+    \code{qqmax.mean}: calculate the maximum standardized difference in the eQQ
+    plot for each variable.  Minimize the mean of these differences across
+    variables.\cr
+    \code{qqmax.max}:  calculate the maximum standardized difference in the eQQ
+    plot for each variable.  Minimize the maximum of these differences across
+    variables.  Lexical optimization is conducted.\cr
+    Users may provide their own \code{fit.func}. The name of the user
+    provided function should not be backquoted or quoted.  This function needs
+    to return a fit value that will be minimized, by lexical
+    optimization if more than one fit value is returned.  The function
+    should expect two arguments.  The first being the \code{matches} object
+    returned by \code{GenMatch}---see
+    below.  And the second being a matrix which contains the variables to
+    be balanced---i.e., the \code{BalanceMatrix} the user provided to
+    \code{GenMatch}. For an example see
+    \url{http://sekhon.berkeley.edu/matching/R/my_fitfunc.R}.}
+  \item{MemoryMatrix}{
+    This variable controls if \code{\link[rgenoud]{genoud}} sets up a memory matrix.  Such a
+    matrix ensures that \code{\link[rgenoud]{genoud}} will request the fitness evaluation
+    of a given set of parameters only once. The variable may be
+    \emph{TRUE} or \emph{FALSE}.  If it is \emph{FALSE}, \code{\link[rgenoud]{genoud}}
+    will be aggressive in
+    conserving memory.  The most significant negative implication of
+    this variable being set to \emph{FALSE} is that \code{\link[rgenoud]{genoud}} will no
+    longer maintain a memory
+    matrix of all evaluated individuals.  Therefore, \code{\link[rgenoud]{genoud}} may request
+    evaluations which it has  previously requested.  When
+    the number variables in \code{X} is large, the memory matrix
+    consumes a large amount of RAM.\cr
+    
+    \code{\link[rgenoud]{genoud}}'s memory matrix will require \emph{significantly} less
+    memory if the user sets \code{hard.generation.limit} equal
+    to \emph{TRUE}.  Doing this is a good way of conserving
+    memory while still making use of the memory matrix structure.}
+  \item{exact}{ A logical scalar or vector for whether exact matching
+    should be done.  If a logical scalar is
+    provided, that logical value is applied to all covariates in
+    \code{X}.  If a logical vector is provided, a logical value should
+    be provided for each covariate in \code{X}. Using a logical vector
+    allows the user to specify exact matching for some but not other
+    variables.  When exact matches are not found, observations are
+    dropped.  \code{distance.tolerance} determines what is considered to
+    be an exact match. The \code{exact} option takes precedence over the
+    \code{caliper} option.  Obviously, if \code{exact} matching is done
+    using \emph{all} of the covariates, one should not be using
+    \code{GenMatch} unless the \code{distance.tolerance} has been set
+    unusually high.}
+  \item{caliper}{ A scalar or vector denoting the caliper(s) which
+    should be used when matching.  A caliper is the distance which is
+    acceptable for any match.  Observations which are outside of the
+    caliper are dropped. If a scalar caliper is provided, this caliper is
+    used for all covariates in \code{X}.  If a vector of calipers is
+    provided, a caliper value should be provided for each covariate in
+    \code{X}. The caliper is interpreted to be in standardized units.  For
+    example, \code{caliper=.25} means that all matches not equal to or
+    within .25 standard deviations of each covariate in \code{X} are
+    dropped.  The \code{ecaliper} object which is returned by
+    \code{GenMatch} shows the enforced caliper on the scale of the
+    \code{X} variables. Note that dropping observations generally changes
+    the quantity being estimated.}
+  \item{replace}{A logical flag for whether matching should be done with
+    replacement.  Note that if \code{FALSE}, the order of matches
+    generally matters.  Matches will be found in the same order as the
+    data are sorted.  Thus, the match(es) for the first observation will
+    be found first, the match(es) for the second observation will be found second, etc.
+    Matching without replacement will generally increase bias.
+    Ties are randomly broken when \code{replace==FALSE}---see the
+    \code{ties} option for details.}
+  \item{ties}{A logical flag for whether ties should be handled deterministically.  By
+    default \code{ties==TRUE}. If, for example, one treated observation
+    matches more than one control observation, the matched dataset will
+    include the multiple matched control observations and the matched data
+    will be weighted to reflect the multiple matches.  The sum of the
+    weighted observations will still equal the original number of
+    observations. If \code{ties==FALSE}, ties will be randomly broken.
+    \emph{If the dataset is large and there are many ties, setting
+    \code{ties=FALSE} often results in a large speedup.} Whether two
+    potential matches are close enough to be considered tied, is
+    controlled by the \code{distance.tolerance}
+    option.}
+  \item{CommonSupport}{This logical flag implements the usual procedure
+    by which observations outside of the common support of a variable
+    (usually the propensity score) across treatment and control groups are
+    discarded.  The \code{caliper} option is to
+    be preferred to this option because \code{CommonSupport}, consistent
+    with the literature, only drops \emph{outliers} and leaves
+    \emph{inliers} while the caliper option drops both.
+    If \code{CommonSupport==TRUE}, common support will be enforced on
+    the first variable in the \code{X} matrix.  Note that dropping
+    observations generally changes the quantity being estimated.  Use of
+    this option renders it impossible to use the returned
+    object \code{matches} to reconstruct the matched dataset.
+    Seriously, don't use this option; use the \code{caliper} option instead.}
+  \item{nboots}{The number of bootstrap samples to be run for the
+    \code{ks} test.  By default this option is set to zero so no
+    bootstraps are done.  See \code{\link{ks.boot}} for additional
+    details.}
+  \item{ks}{ A logical flag for if the univariate bootstrap
+    Kolmogorov-Smirnov (KS) test should be calculated.  If the ks option
+    is set to true, the univariate KS test is calculated for all
+    non-dichotomous variables.  The bootstrap KS test is consistent even
+    for non-continuous variables.  By default, the bootstrap KS test is
+    not used. To change this see the \code{nboots} option. If a given
+    variable is dichotomous, a t-test is used even if the KS test is requested.  See
+    \code{\link{ks.boot}} for additional details.}
+  \item{verbose}{A logical flag for whether details of each
+    fitness evaluation should be printed.  Verbose is set to FALSE if
+    the \code{cluster} option is used.}
+  \item{distance.tolerance}{This is a scalar which is used to determine
+    if distances between two observations are different from zero.  Values
+    less than \code{distance.tolerance} are deemed to be equal to zero.
+    This option can be used to perform a type of optimal matching.}
+  \item{tolerance}{ This is a scalar which is used to determine
+    numerical tolerances.  This option is used by numerical routines
+    such as those used to determine if a matrix is singular.}
+  \item{min.weight}{This is the minimum weight any variable may be
+    given.}  
+  \item{max.weight}{This is the maximum weight any variable may be
+    given.}
+  \item{Domains}{This is a \code{ncol(X)} \eqn{\times 2}{*2} matrix.
+    The first column is the lower bound, and the second column is the
+    upper bound for each variable over which \code{\link[rgenoud]{genoud}} will
+    search for weights.  If the user does not provide this matrix, the
+    bounds for each variable will be determined by the \code{min.weight}
+    and \code{max.weight} options.}
+  \item{print.level}{
+    This option controls the level of printing.  There
+    are four possible levels: 0 (minimal printing), 1 (normal), 2
+    (detailed), and 3 (debug).  If level 2 is selected, \code{GenMatch} will
+    print details about the population at each generation, including the
+    best individual found so far. If debug
+    level printing is requested, details of the \code{\link[rgenoud]{genoud}}
+    population are printed in the "genoud.pro" file which is located in
+    the temporary \code{R} directory returned by the \code{\link{tempdir}}
+    function.  See the \code{project.path} option for more details.
+    Because \code{GenMatch} runs may take a long time, it is important for the
+    user to receive feedback.  Hence, print level 2 has been set as the
+    default.}
+  \item{project.path}{ This is the path of the
+    \code{\link[rgenoud]{genoud}} project file.  By default no file is
+    produced unless \code{print.level=3}.  In that case,
+    \code{\link[rgenoud]{genoud}} places its output in a file called
+    "genoud.pro" located in the temporary directory provided by
+    \code{\link{tempdir}}.  If a file path is provided to the
+    \code{project.path} option, a file will be created regardless of the
+    \code{print.level}. The behavior of the project file, however, will
+    depend on the \code{print.level} chosen.  If the \code{print.level}
+    variable is set to 1, then the project file is rewritten after each
+    generation.  Therefore, only the currently fully completed generation
+    is included in the file.  If the \code{print.level} variable is set to
+    2 or higher, then each new generation is simply appended to the
+    project file. No project file is generated for
+    \code{print.level=0}.}
+  \item{paired}{A flag for whether the paired \code{\link{t.test}} should be
+    used when determining balance.}
+  \item{loss}{The loss function to be optimized.  The default value, \code{1},
+    implies "lexical" optimization: all of the balance statistics will
+    be sorted from the most discrepant to the least and weights will be
+    picked which minimize the maximum discrepancy. If multiple sets of
+    weights result in the same maximum discrepancy, then the second
+    largest discrepancy is examined to choose the best weights.  The
+    processes continues iteratively until ties are broken.  \cr
+
+    If the value of \code{2} is used, then only the maximum discrepancy
+    is examined.  This was the default behavior prior to version 1.0.  The
+    user may also pass in any function she desires. Note that the
+    option 1 corresponds to the \code{\link{sort}} function and option 2
+    to the \code{\link{min}} function.  Any user specified function
+    should expect a vector of balance statistics ("p-values") and it
+    should return either a vector of values (in which case "lexical"
+    optimization will be done) or a scalar value (which will be
+    maximized). Some possible alternative functions are
+    \code{\link{mean}} or \code{\link{median}}.}
+  \item{data.type.integer}{
+    By default, floating-point weights are considered. If this option is
+    set to \code{TRUE}, search will be done over integer weights. Note
+    that before version 4.1, the default was to use integer weights.}
+  \item{restrict}{A matrix which restricts the possible matches. This
+    matrix has one row for each restriction and three
+    columns.  The first two columns contain the two observation numbers
+    which are to be restricted (for example 4 and 20), and the third
+    column is the restriction imposed on the observation-pair.
+    Negative numbers in the third column imply that the two observations
+    cannot be matched under any circumstances, and positive numbers are
+    passed on as the distance between the two observations for the
+    matching algorithm.  The most commonly used positive restriction is
+    \code{0} which implies that the two observations will always
+    be matched.  \cr
+
+    Exclusion restriction are even more common.  For example, if we want
+    to exclude the observation pair 4 and 20 and the pair 6 and 55 from
+    being matched, the restrict matrix would be:
+    \code{restrict=rbind(c(4,20,-1),c(6,55,-1))}} \item{cluster}{This
+    can either be an object of the 'cluster' class returned by one of
+    the \code{\link[parallel]{makeCluster}} commands in the
+    \code{parallel} package or a vector of machine names so that
+    \code{GenMatch} can setup the cluster automatically. If it is the
+    latter, the vector should look like: \cr
+    \code{c("localhost","musil","musil","deckard")}.\cr This vector
+    would create a cluster with four nodes: one on the localhost another
+    on "deckard" and two on the machine named "musil".  Two nodes on a
+    given machine make sense if the machine has two or more chips/cores.
+    \code{GenMatch} will setup a SOCK cluster by a call to
+    \code{\link[parallel]{makePSOCKcluster}}.  This will require the
+    user to type in her password for each node as the cluster is by
+    default created via \code{ssh}.  One can add on usernames to the
+    machine name if it differs from the current shell: "username at musil".
+    Other cluster types, such as PVM and MPI, which do not require
+    passwords, can be created by directly calling
+    \code{\link[parallel]{makeCluster}}, and then passing the returned
+    cluster object to \code{GenMatch}. For an example of how to manually
+    setup up a cluster with a direct call to
+    \code{\link[parallel]{makeCluster}} see
+    \url{http://sekhon.berkeley.edu/matching/R/cluster_manual.R}.  For
+    an example of how to get around a firewall by ssh tunneling see:
+    \url{http://sekhon.berkeley.edu/matching/R/cluster_manual_tunnel.R}.}
+    \item{balance}{This logical flag controls if load balancing is done
+    across the cluster.  Load balancing can result in better cluster
+    utilization; however, increased communication can reduce
+    performance.  This option is best used if each individual call to
+    \code{\link[Matching]{Match}} takes at least several minutes to
+    calculate or if the nodes in the cluster vary significantly in their
+    performance. If cluster==FALSE, this option has no effect.}
+    \item{...}{Other options which are passed on to
+    \code{\link[rgenoud]{genoud}}.}  } \value{ \item{value}{The fit
+    values at the solution.  By default, this is a vector of p-values
+    sorted from the smallest to the largest.  There will generally be
+    twice as many p-values as there are variables in
+    \code{BalanceMatrix}, unless there are dichotomous variables in this
+    matrix.  There is one p-value for each covariate in
+    \code{BalanceMatrix} which is the result of a paired t-test and
+    another p-value for each non-dichotomous variable in
+    \code{BalanceMatrix} which is the result of a Kolmogorov-Smirnov
+    test. Recall that these p-values cannot be interpreted as hypothesis
+    tests.  They are simply measures of balance.}  \item{par}{A vector
+    of the weights given to each variable in \code{X}.}
+    \item{Weight.matrix}{A matrix whose diagonal corresponds to the
+    weight given to each variable in \code{X}.  This object corresponds
+    to the \code{Weight.matrix} in the \code{\link{Match}} function.}
+    \item{matches}{A matrix where the first column contains the row
+    numbers of the treated observations in the matched dataset. The
+    second column contains the row numbers of the control
+    observations. And the third column contains the weight that each
+    matched pair is given.  These objects may not correspond
+    respectively to the \code{index.treated}, \code{index.control} and
+    \code{weights} objects which are returned by \code{\link{Match}}
+    because they may be ordered in a different way. Therefore, end users
+    should use the objects returned by \code{\link{Match}} because those
+    are ordered in the way that users expect.}
+  \item{ecaliper }{The
+    size of the enforced caliper on the scale of the \code{X} variables.
+    This object has the same length as the number of covariates in
+    \code{X}.}  } \references{ Sekhon, Jasjeet S. 2011.  "Multivariate
+    and Propensity Score Matching Software with Automated Balance
+    Optimization.''  \emph{Journal of Statistical Software} 42(7): 1-52.
+    \url{http://www.jstatsoft.org/v42/i07/}
+  
+  Diamond, Alexis and Jasjeet S. Sekhon. 2013. "Genetic
+  Matching for Estimating Causal Effects: A General Multivariate
+  Matching Method for Achieving Balance in Observational Studies.''
+  \emph{Review of Economics and Statistics}.  95 (3): 932--945.
+  \url{http://sekhon.berkeley.edu/papers/GenMatch.pdf}
+
+  Sekhon, Jasjeet Singh and Walter R. Mebane, Jr. 1998.  "Genetic
+  Optimization Using Derivatives: Theory and Application to Nonlinear
+  Models.'' \emph{Political Analysis}, 7: 187-210.
+  \url{http://sekhon.berkeley.edu/genoud/genoud.pdf} 
+}
+\author{
+  Jasjeet S. Sekhon, UC Berkeley, \email{sekhon at berkeley.edu},
+  \url{http://sekhon.berkeley.edu/}.  
+}
+\seealso{ Also see \code{\link{Match}}, \code{\link{summary.Match}},
+  \code{\link{MatchBalance}}, \code{\link[rgenoud]{genoud}},
+  \code{\link{balanceUV}}, \code{\link{qqstats}},
+  \code{\link{ks.boot}}, \code{\link{GerberGreenImai}}, \code{\link{lalonde}}
+} 
+\examples{
+data(lalonde)
+attach(lalonde)
+
+#The covariates we want to match on
+X = cbind(age, educ, black, hisp, married, nodegr, u74, u75, re75, re74)
+
+#The covariates we want to obtain balance on
+BalanceMat <- cbind(age, educ, black, hisp, married, nodegr, u74, u75, re75, re74,
+                    I(re74*re75))
+
+#
+#Let's call GenMatch() to find the optimal weight to give each
+#covariate in 'X' so as we have achieved balance on the covariates in
+#'BalanceMat'. This is only an example so we want GenMatch to be quick
+#so the population size has been set to be only 16 via the 'pop.size'
+#option. This is *WAY* too small for actual problems.
+#For details see http://sekhon.berkeley.edu/papers/MatchingJSS.pdf.
+#
+genout <- GenMatch(Tr=treat, X=X, BalanceMatrix=BalanceMat, estimand="ATE", M=1,
+                   pop.size=16, max.generations=10, wait.generations=1)
+
+#The outcome variable
+Y=re78/1000
+
+#
+# Now that GenMatch() has found the optimal weights, let's estimate
+# our causal effect of interest using those weights
+#
+mout <- Match(Y=Y, Tr=treat, X=X, estimand="ATE", Weight.matrix=genout)
+summary(mout)
+
+#                        
+#Let's determine if balance has actually been obtained on the variables of interest
+#                        
+mb <- MatchBalance(treat~age +educ+black+ hisp+ married+ nodegr+ u74+ u75+
+                   re75+ re74+ I(re74*re75),
+                   match.out=mout, nboots=500)
+
+# For more examples see: http://sekhon.berkeley.edu/matching/R.
+}
+\keyword{nonparametric}
+
+%  LocalWords:  GenMatch Kolmogorov multinomial CPUs BalanceMatrix estimand ATT
+%  LocalWords:  ncol MemoryMatrix nboots ATC rgenoud genoud emph cr ecaliper UC
+%  LocalWords:  eqn tempdir rbind makeCluster localhost musil deckard usernames
+%  LocalWords:  makePSOCKcluster PVM MPI url dataset seealso MatchBalance cbind
+%  LocalWords:  balanceUV GerberGreenImai lalonde hisp nodegr genout
+%  LocalWords:  BalanceMat mout mb mv pvals qqmean QQ qqmedian qqmax Smirnov Tr
+%  LocalWords:  func CommonSupport min Abadie Imbens boostrap ssh username educ
+%  LocalWords:  ealso qqstats nonparametric eQQ rep ks inliers es
diff --git a/man/GerberGreenImai.Rd b/man/GerberGreenImai.Rd
new file mode 100644
index 0000000..fb74d8f
--- /dev/null
+++ b/man/GerberGreenImai.Rd
@@ -0,0 +1,83 @@
+\name{GerberGreenImai}
+\alias{GerberGreenImai}
+\docType{data}
+\title{Gerber and Green Dataset used by Imai}
+\description{
+
+  This is the dataset used by Imai (2005) to replicate and evaluate the
+  field experiment done by Gerber and Green (2000). The accompanying
+  demo replicates Imai's propensity score model which is then used to
+  estimate the causal effect of get-out-the-vote telephone calls on
+  turnout. 
+  
+}
+\usage{data(GerberGreenImai)}
+\format{
+  A data frame with 10829 observations on the following 26 variables.
+  \describe{
+    \item{PERSONS }{Number persons in household}
+    \item{WARD    }{Ward of residence}
+    \item{QUESTION}{Asked to commit to voting}
+    \item{MAILGRP }{Sent mail}
+    \item{PHONEGRP}{Phone batch \#1}
+    \item{PERSNGRP}{Personal contact attempted}
+    \item{APPEAL  }{Content of message}
+    \item{CONTACT }{Personal contact occurred}
+    \item{MAILINGS}{Number of mailings sent}
+    \item{AGE     }{Age of respondent}
+    \item{MAJORPTY}{Democratic or Republican}
+    \item{VOTE96.0}{Abstained in 1996}
+    \item{VOTE96.1}{Voted in 1996}
+    \item{MAILCALL}{Phone batch \#2}
+    \item{VOTED98 }{Voted in 1998}
+    \item{PHNSCRPT}{Script read to phone respondents}
+    \item{DIS.MC  }{Contacted by phone in batch \#2}
+    \item{DIS.PHN }{Contacted by phone in batch \#1}
+    \item{PHN.C   }{Contacted by phone}
+    \item{PHNTRT1 }{Phone contact attempted (no blood or blood/civic)}
+    \item{PHNTRT2 }{Phone contact attempted (no blood)}
+    \item{PHN.C1  }{Contact occurred in phntrt1}
+    \item{PHN.C2  }{Contact occurred in phntrt2}
+    \item{NEW     }{New voter}
+    \item{phone   }{Contacted by phone}
+    \item{AGE2    }{Age squared}
+  }
+}
+\details{
+
+  The demo provided, entitled \code{GerberGreenImai}, uses Imai's
+  propensity score model to estimate the causal effect of
+  get-out-the-vote telephone calls on turnout. The propensity score
+  model fails to balance age.
+
+}
+\references{
+
+  Gerber, Alan S. and Donald P. Green. 2000. ``The Effects of
+  Canvassing, Telephone Calls, and Direct Mail on Voter Turnout: A Field
+  Experiment.'' \emph{American Political Science Review} 94: 653-663.
+
+  Gerber, Alan S. and Donald P. Green. 2005. ``Correction to Gerber
+  and Green (2000), replication of disputed findings, and reply to
+  Imai (2005).''  \emph{American Political Science Review} 99:
+  301-313.
+
+  Imai, Kosuke. 2005. ``Do Get-Out-The-Vote Calls Reduce Turnout?
+  The Importance of Statistical Methods for Field Experiments.'' 
+  \emph{American Political Science Review} 99: 283-300.
+
+  Hansen, Ben B. Hansen and Jake Bowers. forthcoming. ``Attributing
+  Effects to a Cluster Randomized Get-Out-The-Vote Campaign.''
+  \emph{Journal of the American Statistical Association}.
+} 
+\seealso{ Also see \code{\link{Match}} and \code{\link{MatchBalance}},
+  \code{\link{GenMatch}}, \code{\link{balanceUV}}, \code{\link{ks.boot}}
+  \code{\link{lalonde}}
+}
+\keyword{datasets}
+
+
+%  LocalWords:  GerberGreenImai docType Dataset dataset Imai's MAILGRP PHONEGRP
+%  LocalWords:  PERSNGRP MAJORPTY MAILCALL PHNSCRPT PHN PHNTRT phntrt emph
+%  LocalWords:  Kosuke seealso MatchBalance GenMatch balanceUV
+%  LocalWords:  lalonde datasets
diff --git a/man/Match.Rd b/man/Match.Rd
new file mode 100644
index 0000000..1df8db5
--- /dev/null
+++ b/man/Match.Rd
@@ -0,0 +1,379 @@
+\name{Match}
+\alias{Match}
+\title{Multivariate and Propensity Score Matching Estimator for Causal Inference}
+\description{
+  \code{Match} implements a variety of algorithms for multivariate
+  matching including propensity score, Mahalanobis and inverse variance
+  matching.  The function is intended to be used in conjunction with the
+  \code{MatchBalance} function which determines the extent to which
+  \code{Match} has been able to achieve covariate balance.  In order to
+  do propensity score matching, one should estimate the propensity model
+  before calling \code{Match}, and then send \code{Match} the propensity
+  score to use.  \code{Match} enables a wide variety of matching
+  options including matching with or without replacement, bias
+  adjustment, different methods for handling ties, exact and caliper
+  matching, and a method for the user to fine tune the matches via a
+  general restriction matrix.  Variance estimators include the usual
+  Neyman standard errors, Abadie-Imbens standard errors, and robust
+  variances which do not assume a homogeneous causal effect. The
+  \code{\link{GenMatch}} function can be used to \emph{automatically
+  find balance} via a genetic search algorithm which determines the
+  optimal weight to give each covariate.
+}
+\usage{
+Match(Y=NULL, Tr, X, Z = X, V = rep(1, length(Y)), estimand = "ATT", M = 1,
+      BiasAdjust = FALSE, exact = NULL, caliper = NULL, replace=TRUE, ties=TRUE,
+      CommonSupport=FALSE,Weight = 1, Weight.matrix = NULL, weights = NULL,
+      Var.calc = 0, sample = FALSE, restrict=NULL, match.out = NULL,
+      distance.tolerance = 1e-05, tolerance=sqrt(.Machine$double.eps),
+      version="standard")
+}
+\arguments{
+  \item{Y}{ A vector containing the outcome of interest.
+    Missing values are not allowed.  An outcome vector is not required
+    because the matches generated will be the same regardless of the
+    outcomes.  Of course, without any outcomes no causal effect
+    estimates will be produced, only a matched dataset. }
+  \item{Tr}{ A vector indicating the observations which are
+    in the treatment regime and those which are not.  This can either be a
+    logical vector or a real vector where 0 denotes control and 1 denotes
+    treatment.}
+  \item{X}{ A matrix containing the variables we wish to match on.
+    This matrix may contain the actual observed covariates or the
+    propensity score or a combination of both. All columns of this
+    matrix must have positive variance or \code{Match} will return an
+    error.}
+  \item{Z}{ A matrix containing the covariates for which we wish to make
+    bias adjustments.}
+  \item{V}{ A matrix containing the covariates for which the variance
+    of the causal effect may vary. Also see the \code{Var.calc} option,
+    which takes precedence.}
+  \item{estimand}{ A character string for the estimand.  The default
+    estimand is "ATT", the sample average treatment effect for the
+    treated. "ATE" is the sample average treatment effect, and
+    "ATC" is the sample average treatment effect for the controls.}
+  \item{M}{A scalar for the number of matches which should be
+    found. The default is one-to-one matching. Also see the \code{ties}
+    option.}
+  \item{BiasAdjust}{ A logical scalar for whether regression adjustment
+    should be used. See the \code{Z} matrix.}
+  \item{exact}{ A logical scalar or vector for whether exact matching
+    should be done. If a logical scalar is provided, that logical value is
+      applied to all covariates in
+    \code{X}.  If a logical vector is provided, a logical value should
+    be provided for each covariate in \code{X}. Using a logical vector
+    allows the user to specify exact matching for some but not other
+    variables.  When exact matches are not found, observations are
+    dropped.  \code{distance.tolerance} determines what is considered to be an
+    exact match. The \code{exact} option takes precedence over the
+    \code{caliper} option.}
+  \item{caliper}{ A scalar or vector denoting the caliper(s) which
+    should be used when matching.  A caliper is the distance which is
+    acceptable for any match.  Observations which are outside of the
+    caliper are dropped. If a scalar caliper is provided, this caliper is
+    used for all covariates in \code{X}.  If a vector of calipers is
+    provided, a caliper value should be provided for each covariate in
+    \code{X}. The caliper is interpreted to be in standardized units.  For
+    example, \code{caliper=.25} means that all matches not equal to or
+    within .25 standard deviations of each covariate in \code{X} are
+    dropped. Note that dropping observations generally changes the
+    quantity being estimated.}
+  \item{replace}{A logical flag for whether matching should be done with
+    replacement.  Note that if \code{FALSE}, the order of matches
+    generally matters.  Matches will be found in the same order as the
+    data are sorted.  Thus, the match(es) for the first observation will
+    be found first, the match(es) for the second observation will be found second, etc.
+    Matching without replacement will generally increase bias.
+    Ties are randomly broken when \code{replace==FALSE}
+    ---see the \code{ties} option for details.}
+  \item{ties}{A logical flag for whether ties should be handled deterministically.  By
+    default \code{ties==TRUE}. If, for example, one treated observation
+    matches more than one control observation, the matched dataset will
+    include the multiple matched control observations and the matched data
+    will be weighted to reflect the multiple matches.  The sum of the
+    weighted observations will still equal the original number of
+    observations. If \code{ties==FALSE}, ties will be randomly broken.
+    \emph{If the dataset is large and there are many ties, setting
+    \code{ties=FALSE} often results in a large speedup.} Whether two
+    potential matches are close enough to be considered tied, is
+    controlled by the \code{distance.tolerance}
+    option.}
+  \item{CommonSupport}{This logical flag implements the usual procedure
+    by which observations outside of the common support of a variable
+    (usually the propensity score) across treatment and control groups are
+    discarded.  The \code{caliper} option is to
+    be preferred to this option because \code{CommonSupport}, consistent
+    with the literature, only drops \emph{outliers} and leaves
+    \emph{inliers} while the caliper option drops both.
+    If \code{CommonSupport==TRUE}, common support will be enforced on
+    the first variable in the \code{X} matrix.  Note that dropping
+    observations generally changes the quantity being estimated. Use of
+    this option renders it impossible to use the returned
+    objects \code{index.treated} and \code{index.control} to
+    reconstruct the matched dataset.  The returned object \code{mdata}
+    will, however, still contain the matched dataset.  Seriously, don't
+    use this option; use the \code{caliper} option instead.}
+  \item{Weight}{ A scalar for the type of weighting scheme the matching
+    algorithm should use when weighting each of the covariates in
+    \code{X}.  The default value of 1 denotes that weights are equal to
+    the inverse of the variances. 2 denotes the Mahalanobis distance
+    metric, and 3 denotes that the user will supply a weight matrix
+    (\code{Weight.matrix}).  Note that if the user supplies a
+    \code{Weight.matrix}, \code{Weight} will be automatically set to be
+    equal to 3.}
+  \item{Weight.matrix}{ This matrix denotes the weights the matching
+    algorithm uses when weighting each of the covariates in \code{X}---see
+    the \code{Weight} option. This square matrix should have as many
+    columns as the number of columns of the \code{X} matrix. This matrix
+    is usually provided by a call to the \code{\link{GenMatch}} function
+    which finds the optimal weight each variable should be given so as to
+    achieve balance on the covariates. \cr
+
+    For most uses, this matrix has zeros in the off-diagonal
+    cells.  This matrix can be used to weight some variables more than
+    others.  For
+    example, if \code{X} contains three variables and we want to 
+    match as best as we can on the first, the following would work well:
+    \cr
+    \code{> Weight.matrix <- diag(3)}\cr
+    \code{> Weight.matrix[1,1] <- 1000/var(X[,1])} \cr
+    \code{> Weight.matrix[2,2] <- 1/var(X[,2])} \cr
+    \code{> Weight.matrix[3,3] <- 1/var(X[,3])} \cr
+    This code changes the weights implied by the
+    inverse of the variances by multiplying the first variable by a 1000
+    so that it is highly weighted.  In order to enforce exact matching
+    see the \code{exact} and \code{caliper} options.}
+  \item{weights}{ A vector the same length as \code{Y} which
+    provides observation specific weights.}
+  \item{Var.calc}{ A scalar for the variance estimate
+    that should be used.  By default \code{Var.calc=0} which means that
+    homoscedasticity is assumed.  For values of  \code{Var.calc > 0},
+    robust variances are calculated using \code{Var.calc} matches. }
+  \item{sample}{ A logical flag for whether the population or sample
+    variance is returned. }
+  \item{distance.tolerance}{This is a scalar which is used to determine
+    if distances between two observations are different from zero.  Values
+    less than \code{distance.tolerance} are deemed to be equal to zero.
+    This option can be used to perform a type of optimal matching}
+  \item{tolerance}{ This is a scalar which is used to determine
+    numerical tolerances.  This option is used by numerical routines
+    such as those used to determine if a matrix is singular.}
+  \item{restrict}{A matrix which restricts the possible matches.  This
+    matrix has one row for each restriction and three
+    columns.  The first two columns contain the two observation numbers
+    which are to be restricted (for example 4 and 20), and the third
+    column is the restriction imposed on the observation-pair.
+    Negative numbers in the third column imply that the two observations
+    cannot be matched under any circumstances, and positive numbers are
+    passed on as the distance between the two observations for the
+    matching algorithm.  The most commonly used positive restriction is
+    \code{0} which implies that the two observations will always
+    be matched.  \cr
+
+    Exclusion restrictions are even more common.  For example, if we want
+    to exclude the observation pair 4 and 20 and
+    the pair 6 and 55 from being matched, the restrict matrix would be:
+    \code{restrict=rbind(c(4,20,-1),c(6,55,-1))}}
+  \item{match.out}{ The return object from a previous call to
+    \code{Match}.  If this object is provided, then \code{Match} will
+    use the matches found by the previous invocation of the function.
+    Hence, \code{Match} will run faster.  This is
+    useful when the treatment does not vary across calls to
+    \code{Match} and one wants to use the same set of matches as found
+    before.  This often occurs when one is trying to estimate the causal
+    effect of the same treatment (\code{Tr}) on different outcomes
+    (\code{Y}). When using this option, be careful to use the same
+    arguments as used for the previous invocation of \code{Match} unless
+    you know exactly what you are doing.}
+  \item{version}{The version of the code to be used.  The "fast" C/C++
+    version of the code does not calculate Abadie-Imbens standard errors.
+    Additional speed can be obtained by setting \code{ties=FALSE} or
+    \code{replace=FALSE} if the dataset is large and/or has many ties.
+    The "legacy" version of the code does not make a call to an optimized
+    C/C++ library and is included only for historical compatibility.  The
+    "fast" version of the code is significantly faster than the "standard"
+    version for large datasets, and the "legacy" version is much slower
+    than either of the other two.}
+}
+\details{
+  
+  This function is intended to be used in conjunction with the
+  \code{MatchBalance} function which checks if the results of this
+  function have actually achieved balance.  The results of this function
+  can be summarized by a call to the \code{\link{summary.Match}}
+  function. If one wants to do propensity score matching, one should estimate the
+  propensity model before calling \code{Match}, and then place the
+  fitted values in the \code{X} matrix---see the provided example.  \cr
+
+  The \code{\link{GenMatch}} function can be used to \emph{automatically
+  find balance} by the use of a genetic search algorithm which determines
+  the optimal weight to give each covariate. The object returned by
+  \code{\link{GenMatch}} can be supplied to the \code{Weight.matrix}
+  option of \code{Match} to obtain estimates.\cr
+
+  \code{Match} is often much faster with large datasets if
+  \code{ties=FALSE} or \code{replace=FALSE}---i.e., if matching is done
+  by randomly breaking ties or without replacement.  Also see the
+  \code{\link{Matchby}} function.  It provides a wrapper for
+  \code{Match} which is much faster for large datasets when it can be
+  used.\cr
+  
+  Three demos are included: \code{GerberGreenImai}, \code{DehejiaWahba},
+  and \code{AbadieImbens}.  These can be run by calling the
+  \code{\link{demo}} function such as by \code{demo(DehejiaWahba)}. \cr
+}
+
+\value{
+  \item{est }{The estimated average causal effect.}
+  \item{se }{The Abadie-Imbens standard error.  This standard error has
+    correct coverage if \code{X} consists of either covariates or a known
+    propensity score because it takes into account the uncertainty of the
+    matching procedure.  If an estimated propensity score is used, the
+    uncertainty involved in its estimation is not accounted for although
+    the uncertainty of the matching procedure itself still is.}
+  \item{est.noadj }{The estimated average causal effect without any
+    \code{BiasAdjust}.  If \code{BiasAdjust} is not requested, this is the
+    same as \code{est}.}
+  \item{se.standard }{The usual standard error.  This is the standard error
+    calculated on the matched data using the usual method of calculating
+    the difference of means (between treated and control) weighted by the
+    observation weights provided by \code{weights}.  Note that the
+    standard error provided by \code{se} takes into account the uncertainty
+    of the matching procedure while \code{se.standard} does not.  Neither
+    \code{se} nor \code{se.standard} take into account the uncertainty of
+    estimating a propensity score.  \code{se.standard} does
+    not take into account any \code{BiasAdjust}.  Summary of both types
+    of standard error results can be requested by setting the
+    \code{full=TRUE} flag when using the \code{\link{summary.Match}}
+    function on the object returned by \code{Match}.}
+  \item{se.cond }{The conditional standard error.  The practitioner
+    should not generally use this.}
+  \item{mdata }{A list which contains the matched datasets produced by
+    \code{Match}.  Three datasets are included in this list: \code{Y},
+    \code{Tr} and \code{X}.}
+  \item{index.treated }{A vector containing the observation numbers from
+    the original dataset for the treated observations in the
+    matched dataset.  This index in conjunction with \code{index.control}
+    can be used to recover the matched dataset produced by
+    \code{Match}.  For example, the \code{X} matrix used by \code{Match}
+    can be recovered by
+    \code{rbind(X[index.treated,],X[index.control,])}. The user should
+    generally just examine the output of \code{mdata}.}
+  \item{index.control }{A vector containing the observation numbers from
+    the original data for the control observations in the
+    matched data.  This index in conjunction with \code{index.treated}
+    can be used to recover the matched dataset produced by
+    \code{Match}.  For example, the \code{X} matrix used by \code{Match}
+    can be recovered by
+    \code{rbind(X[index.treated,],X[index.control,])}. The user should
+    generally just examine the output of \code{mdata}.}
+  \item{index.dropped}{A vector containing the observation numbers from
+    the original data which were dropped (if any) in the matched dataset 
+    because of various options such as \code{caliper} and
+    \code{exact}.  If no observations were dropped, this
+    index will be \code{NULL}.}
+  \item{weights}{A vector of weights.  There is one weight for each
+    matched-pair in the matched dataset.  If all of the observations had a
+    weight of 1 on input, then each matched-pair will have a weight of 1
+    on output if there are no ties.}
+  \item{orig.nobs }{The original number of observations in the dataset.}
+  \item{orig.wnobs }{The original number of weighted observations in the
+    dataset.}
+  \item{orig.treated.nobs}{The original number of treated observations (unweighted).}
+  \item{nobs }{The number of observations in the matched dataset.}
+  \item{wnobs }{The number of weighted observations in the matched dataset.}
+  \item{caliper }{The \code{caliper} which was used.}
+  \item{ecaliper }{The size of the enforced caliper on the scale of the
+    \code{X} variables.  This object has the same length as the number of
+    covariates in \code{X}.}
+  \item{exact}{The value of the \code{exact} function argument.}
+  \item{ndrops}{The number of weighted observations which were dropped
+    either because of caliper or exact matching.  This number, unlike
+    \code{ndrops.matches}, takes into account observation specific
+    weights which the user may have provided via the \code{weights}
+    argument.}
+  \item{ndrops.matches}{The number of matches which were dropped either because of 
+    caliper or exact matching.}  
+}
+\references{
+  Sekhon, Jasjeet S. 2011.  "Multivariate and Propensity Score
+  Matching Software with Automated Balance Optimization.''
+  \emph{Journal of Statistical Software} 42(7): 1-52.
+  \url{http://www.jstatsoft.org/v42/i07/}
+
+  Diamond, Alexis and Jasjeet S. Sekhon. 2013. "Genetic
+  Matching for Estimating Causal Effects: A General Multivariate
+  Matching Method for Achieving Balance in Observational Studies.''
+  \emph{Review of Economics and Statistics}. 95 (3): 932--945.
+  \url{http://sekhon.berkeley.edu/papers/GenMatch.pdf}
+
+  Abadie, Alberto and Guido Imbens. 2006.
+  ``Large Sample Properties of Matching Estimators for Average
+  Treatment Effects.'' \emph{Econometrica} 74(1): 235-267.
+
+  Imbens, Guido. 2004. Matching Software for Matlab and
+  Stata. 
+
+}
+\author{Jasjeet S. Sekhon, UC Berkeley, \email{sekhon at berkeley.edu},
+  \url{http://sekhon.berkeley.edu/}.
+}
+\seealso{ Also see \code{\link{summary.Match}},
+  \code{\link{GenMatch}},
+  \code{\link{MatchBalance}},
+  \code{\link{Matchby}},  
+  \code{\link{balanceUV}},
+  \code{\link{qqstats}}, \code{\link{ks.boot}},
+  \code{\link{GerberGreenImai}}, \code{\link{lalonde}}
+} 
+\examples{
+
+# Replication of Dehejia and Wahba psid3 model
+#
+# Dehejia, Rajeev and Sadek Wahba. 1999.``Causal Effects in
+# Non-Experimental Studies: Re-Evaluating the Evaluation of Training
+# Programs.''Journal of the American Statistical Association 94 (448):
+# 1053-1062.
+
+data(lalonde)
+
+#
+# Estimate the propensity model
+#
+glm1  <- glm(treat~age + I(age^2) + educ + I(educ^2) + black +
+             hisp + married + nodegr + re74  + I(re74^2) + re75 + I(re75^2) +
+             u74 + u75, family=binomial, data=lalonde)
+
+
+#
+#save data objects
+#
+X  <- glm1$fitted
+Y  <- lalonde$re78
+Tr  <- lalonde$treat
+
+#
+# one-to-one matching with replacement (the "M=1" option).
+# Estimating the treatment effect on the treated (the "estimand" option defaults to ATT).
+#
+rr  <- Match(Y=Y, Tr=Tr, X=X, M=1);
+summary(rr)
+
+# Let's check the covariate balance
+# 'nboots' is set to small values in the interest of speed.
+# Please increase to at least 500 each for publication quality p-values.  
+mb  <- MatchBalance(treat~age + I(age^2) + educ + I(educ^2) + black +
+                    hisp + married + nodegr + re74  + I(re74^2) + re75 + I(re75^2) +
+                    u74 + u75, data=lalonde, match.out=rr, nboots=10)
+}
+\keyword{nonparametric}
+
+
+%  LocalWords:  MatchBalance GenMatch emph estimand ATT BiasAdjust calc dataset
+%  LocalWords:  ATC ecaliper cr diag homoscedasticity rbind GerberGreenImai se
+%  LocalWords:  DehejiaWahba AbadieImbens noadj cond mdata datasets wnobs url
+%  LocalWords:  ndrops Abadie Imbens Econometrica Matlab Stata UC seealso Wahba
+%  LocalWords:  balanceUV lalonde Dehejia psid Rajeev Sadek glm hisp
+%  LocalWords:  nodegr rr nboots nmc mb Neyman Tr CommonSupport Var var Matchby
+%  LocalWords:  est orig nobs Guido ealso qqstats educ nonparametric rep es ks
+%  LocalWords:  inliers Mahalanobis
diff --git a/man/MatchBalance.Rd b/man/MatchBalance.Rd
new file mode 100644
index 0000000..2ef9b88
--- /dev/null
+++ b/man/MatchBalance.Rd
@@ -0,0 +1,207 @@
+\name{MatchBalance}
+\alias{MatchBalance}
+\title{Tests for Univariate and Multivariate Balance}
+\description{
+  This function provides a variety of balance statistics useful for
+  determining if balance exists in any unmatched dataset and
+  in matched datasets produced by the \code{\link{Match}}
+  function.  Matching is performed by the \code{\link{Match}} function,
+  and \code{MatchBalance} is used to determine if \code{\link{Match}}
+  was successful in achieving balance on the observed covariates.
+}
+\usage{
+MatchBalance(formul, data = NULL, match.out = NULL, ks = TRUE,
+             nboots=500, weights=NULL, digits=5, paired=TRUE, print.level=1)
+}
+\arguments{
+  \item{formul}{
+    This formula does \emph{not} estimate any model.  The formula is
+    simply an efficient way to use the R modeling language to list the
+    variables we wish to obtain univariate balance statistics for.  The
+    dependent variable in the formula is usually the treatment
+    indicator.  One should include many functions of the observed
+    covariates.  Generally, one should request balance statistics on
+    more higher-order terms and interactions than were used to conduct
+    the matching itself.}
+  \item{data}{ A data frame which contains all of the variables in the
+    formula.  If a data frame is not provided, the variables are
+    obtained via lexical scoping.}
+  \item{match.out}{ The output object from the \code{\link{Match}}
+    function.  If this output is included, \code{\link{MatchBalance}} will provide
+    balance statistics for both before and after matching. Otherwise
+    balance statistics will only be reported for the raw unmatched
+    data.}
+  \item{ks}{ A logical flag for whether the univariate bootstrap
+    Kolmogorov-Smirnov (KS) test should be calculated.  If the ks option
+    is set to true, the univariate KS test is calculated for all
+    non-dichotomous variables.  The bootstrap KS test is consistent even
+    for non-continuous variables.  See \code{\link{ks.boot}} for more
+    details.}
+  \item{weights}{An optional vector of observation specific weights.}
+  \item{nboots}{The number of bootstrap samples to be run.  If zero, no
+    bootstraps are done.  Bootstrapping is highly recommended because
+    the bootstrapped Kolmogorov-Smirnov test provides correct coverage
+    even when the distributions being compared are not continuous.  At
+    least 500 \code{nboots} (preferably 1000) are recommended for
+    publication quality p-values.}
+  \item{digits}{The number of significant digits that should be
+    displayed.}
+  \item{paired}{A flag for whether the paired \code{\link{t.test}} should be
+    used after matching.  Regardless of the value of this option, an
+    unpaired \code{\link{t.test}} is done for the unmatched data because
+    it is assumed that the unmatched data were not generated by a paired
+    experiment.}
+  \item{print.level}{The amount of printing to be done.  If zero, there is
+    no printing.  If one, the results are summarized.  If
+    two, details of the computations are printed.}
+}
+\value{
+  \item{BeforeMatching}{A list containing the before matching univariate
+    balance statistics. That is, a list containing the results of
+    the  \code{\link{balanceUV}} function applied to all of the 
+    covariates described in \code{formul}.  Note that the univariate
+    test results for all of the variables in \code{formul} are printed
+    if \code{verbose > 0}.}
+  \item{AfterMatching}{A list containing the after matching univariate
+    balance statistics. That is, a list containing the results of
+    the  \code{\link{balanceUV}} function applied to all of the 
+    covariates described in \code{formul}.  Note that the univariate
+    test results for all of the variables in \code{formul} are printed
+    if \code{verbose > 0}.  This object is \code{NULL}, if no matched
+    dataset was provided.}
+  \item{BMsmallest.p.value}{The smallest p.value found across all of the
+    \emph{before} matching balance tests (including t-tests and KS-tests.}
+  \item{BMsmallestVarName}{The name of the variable with the
+    \code{BMsmallest.p.value} (a vector in case of ties).}
+  \item{BMsmallestVarNumber}{The number of the variable with the
+    \code{BMsmallest.p.value} (a vector in case of ties).}
+  \item{AMsmallest.p.value}{The smallest p.value found across all of the
+    \emph{after} matching balance tests (including t-tests and
+    KS-tests.}
+  \item{AMsmallestVarName}{The name of the variable with the
+    \code{AMsmallest.p.value} (a vector in case of ties).}
+  \item{AMsmallestVarNumber}{The number of the variable with the
+    \code{AMsmallest.p.value} (a vector in case of ties).}  
+}
+\details{
+  This function can be used to determine if there is balance in the pre-
+  and/or post-matching datasets.  Difference of means between treatment
+  and control groups are provided as well as a variety of summary
+  statistics for the empirical CDF (eCDF) and empirical-QQ (eQQ) plot
+  between the two groups.  The eCDF results are the standardized mean,
+  median and maximum differences in the empirical CDF. The eQQ results
+  are summaries of the raw differences in the empirical-QQ plot.\cr
+
+  Two univariate tests are also provided: the t-test and the bootstrap
+  Kolmogorov-Smirnov (KS) test. These tests should not be treated as
+  hypothesis tests in the usual fashion because we wish to maximize
+  balance without limit.  The bootstrap KS test is highly
+  recommended (see the \code{ks} and \code{nboots} options) because the
+  bootstrap KS is consistent even for non-continuous distributions.
+  Before matching, the two sample t-test is used; after matching, the
+  paired t-test is used.\cr
+
+  Two multivariate tests are provided.  The KS and Chi-Square null
+  deviance tests.  The KS test is to be preferred over the Chi-Square
+  test because the Chi-Square test is not testing the relevant
+  hypothesis.  The null hypothesis for the KS test is equal balance
+  in the estimated probabilities between treated and control.  The null
+  hypothesis for the Chi-Square test, however, is all of the
+  parameters being insignificant; a comparison of residual versus null
+  deviance.  If the covariates being considered are discrete, this KS
+  test is asymptotically nonparametric as long as the logit model does
+  not produce zero parameter estimates.
+
+  \code{NA}'s are handled by the \code{\link{na.action}} option.  But it
+  is highly recommended that \code{NA}'s not simply be deleted, but
+  one should check to make sure that missingness is balanced.
+  }
+  \references{
+  Sekhon, Jasjeet S. 2011.  "Multivariate and Propensity Score
+  Matching Software with Automated Balance Optimization.''
+  \emph{Journal of Statistical Software} 42(7): 1-52.
+  \url{http://www.jstatsoft.org/v42/i07/}
+
+  Diamond, Alexis and Jasjeet S. Sekhon. 2013. "Genetic
+  Matching for Estimating Causal Effects: A General Multivariate
+  Matching Method for Achieving Balance in Observational Studies.''
+  \emph{Review of Economics and Statistics}.  95 (3): 932--945.
+  \url{http://sekhon.berkeley.edu/papers/GenMatch.pdf}
+
+  Abadie, Alberto.  2002.  ``Bootstrap Tests for Distributional Treatment
+  Effects in Instrumental Variable Models.'' \emph{Journal of the
+  American Statistical Association}, 97:457 (March) 284-292.  
+
+  Hall, Peter. 1992. \emph{The Bootstrap and Edgeworth Expansion}.  New
+  York: Springer-Verlag.
+
+  Wilcox, Rand R. 1997. \emph{Introduction to Robust Estimation}.  San
+  Diego, CA: Academic Press.
+
+  William J. Conover (1971), \emph{Practical nonparametric statistics}.
+  New York: John Wiley & Sons. Pages 295-301 (one-sample
+  "Kolmogorov" test), 309-314 (two-sample "Smirnov" test).
+
+  Shao, Jun and Dongsheng Tu. 1995. \emph{The Jackknife and Bootstrap}.
+  New York: Springer-Verlag.
+}
+\author{
+  Jasjeet S. Sekhon, UC Berkeley, \email{sekhon at berkeley.edu},
+  \url{http://sekhon.berkeley.edu/}.  
+}
+\seealso{
+  Also see \code{\link{Match}}, \code{\link{GenMatch}}, 
+  \code{\link{balanceUV}}, \code{\link{qqstats}}, \code{\link{ks.boot}}, 
+  \code{\link{GerberGreenImai}}, \code{\link{lalonde}}
+}
+\examples{
+#
+# Replication of Dehejia and Wahba psid3 model
+#
+# Dehejia, Rajeev and Sadek Wahba. 1999.``Causal Effects in
+# Non-Experimental Studies: Re-Evaluating the Evaluation of Training
+# Programs.''Journal of the American Statistical Association 94 (448):
+# 1053-1062.
+
+data(lalonde)
+
+#
+# Estimate the propensity model
+#
+glm1  <- glm(treat~age + I(age^2) + educ + I(educ^2) + black +
+             hisp + married + nodegr + re74  + I(re74^2) + re75 + I(re75^2) +
+             u74 + u75, family=binomial, data=lalonde)
+
+
+#
+#save data objects
+#
+X  <- glm1$fitted
+Y  <- lalonde$re78
+Tr  <- lalonde$treat
+
+#
+# one-to-one matching with replacement (the "M=1" option).
+# Estimating the treatment effect on the treated (the "estimand" option which defaults to 0).
+#
+rr  <- Match(Y=Y,Tr=Tr,X=X,M=1);
+
+#Let's summarize the output
+summary(rr)
+
+# Let's check the covariate balance
+# 'nboots' is set to small values in the interest of speed.
+# Please increase to at least 500 each for publication quality p-values.  
+mb  <- MatchBalance(treat~age + I(age^2) + educ + I(educ^2) + black +
+                    hisp + married + nodegr + re74  + I(re74^2) + re75 + I(re75^2) +
+                    u74 + u75, data=lalonde, match.out=rr, nboots=10)
+}
+\keyword{nonparametric}
+\keyword{htest}
+
+%  LocalWords:  MatchBalance formul nboots nrow regressors glm uv
+%  LocalWords:  datasets Kolmogorov balanceUV logit url Abadie emph
+%  LocalWords:  Edgeworth Verlag Conover Shao Dongsheng UC seealso GenMatch rr
+%  LocalWords:  GerberGreenImai lalonde Dehejia Wahba psid Rajeev Sadek hisp mb
+%  LocalWords:  nodegr estimand htest QQ eQQ cr Monte Carlo Smirnov ks rep Chi
+%  LocalWords:  pre nonparametric San CA Jun Tu ealso qqstats educ Tr
diff --git a/man/Matchby.Rd b/man/Matchby.Rd
new file mode 100644
index 0000000..7a26b0b
--- /dev/null
+++ b/man/Matchby.Rd
@@ -0,0 +1,277 @@
+\name{Matchby}
+\alias{Matchby}
+\title{Grouped Multivariate and Propensity Score Matching}
+\description{
+  This function is a wrapper for the \code{\link{Match}} function which
+  separates the matching problem into subgroups defined by a factor.
+  This is equivalent to conducting exact matching on each level of a factor.
+  Matches within each level are found as determined by the
+  usual matching options.  This function is much faster for large
+  datasets than the \code{\link{Match}} function itself.  For additional
+  speed, consider doing matching without replacement---see the
+  \code{replace} option.  This function is more limited than the
+  \code{\link{Match}} function.  For example, \code{Matchby} cannot be
+  used if the user wishes to provide observation specific weights. 
+}
+
+\usage{
+Matchby(Y, Tr, X, by, estimand = "ATT", M = 1, ties=FALSE, replace=TRUE,
+        exact = NULL, caliper = NULL, AI=FALSE, Var.calc=0,
+        Weight = 1, Weight.matrix = NULL, distance.tolerance = 1e-05,
+        tolerance = sqrt(.Machine$double.eps), print.level=1, version="Matchby", ...)
+}
+\arguments{
+  \item{Y}{ A vector containing the outcome of interest. Missing values are not allowed.}
+  \item{Tr}{ A vector indicating the observations which are
+    in the treatment regime and those which are not.  This can either be a
+    logical vector or a real vector where 0 denotes control and 1 denotes
+    treatment.}
+  \item{X}{ A matrix containing the variables we wish to match on.
+    This matrix may contain the actual observed covariates or the
+    propensity score or a combination of both.}
+  \item{by}{A "factor" in the sense that \code{as.factor(by)} defines the
+    grouping, or a list of such factors in which case their
+    interaction is used for the grouping.}
+  \item{estimand}{ A character string for the estimand.  The default
+    estimand is "ATT", the sample average treatment effect for the
+    treated. "ATE" is the sample average treatment effect (for all), and
+    "ATC" is the sample average treatment effect for the controls.}
+  \item{M}{ A scalar for the number of matches which should be
+    found. The default is one-to-one matching. Also see the
+    \code{ties} option.}
+  \item{ties}{A logical flag for whether ties should be handled
+    deterministically.  By default \code{ties==TRUE}. If, for example, one
+    treated observation matches more than one control observation, the
+    matched dataset will include the multiple matched control observations
+    and the matched data will be weighted to reflect the multiple matches.
+    The sum of the weighted observations will still equal the original
+    number of observations. If \code{ties==FALSE}, ties will be randomly
+    broken.  \emph{If the dataset is large and there are many ties,
+      setting \code{ties=FALSE} often results in a large speedup.} Whether
+    two potential matches are close enough to be considered tied, is
+    controlled by the \code{distance.tolerance} option.}
+  \item{replace}{Whether matching should be done with replacement.  Note
+    that if \code{FALSE}, the order of matches generally matters.  Matches
+    will be found in the same order as the data is sorted.  Thus, the
+    match(es) for the first observation will be found first and then for
+    the second etc. Matching without replacement will generally increase
+    bias so it is not recommended.  \emph{But if the dataset is large and
+      there are many potential matches, setting \code{replace=false} often
+      results in a large speedup and negligible or no bias.} Ties are
+    randomly broken when \code{replace==FALSE}---see the \code{ties}
+    option for details.}    
+  \item{exact}{ A logical scalar or vector for whether exact matching
+    should be done.  If a logical scalar is provided, that logical value is
+    applied to all covariates of
+    \code{X}.  If a logical vector is provided, a logical value should
+    be provided for each covariate in \code{X}. Using a logical vector
+    allows the user to specify exact matching for some but not other
+    variables.  When exact matches are not found, observations are
+    dropped.  \code{distance.tolerance} determines what is considered to be an
+    exact match. The \code{exact} option takes precedence over the
+    \code{caliper} option.}
+  \item{caliper}{ A scalar or vector denoting the caliper(s) which
+    should be used when matching.  A caliper is the distance which is
+    acceptable for any match.  Observations which are outside of the
+    caliper are dropped. If a scalar caliper is provided, this caliper is
+    used for all covariates in \code{X}.  If a vector of calipers is
+    provided, a caliper value should be provide for each covariate in
+    \code{X}. The caliper is interpreted to be in standardized units.  For
+    example, \code{caliper=.25} means that all matches not equal to or
+    within .25 standard deviations of each covariate in \code{X} are
+    dropped.}
+  \item{AI}{A logical flag for if the Abadie-Imbens standard error
+    should be calculated. It is computationally expensive to calculate
+    with large datasets. \code{Matchby} can only calculate AI SEs for ATT.
+    To calculate AI errors with other estimands, please use the
+    \code{\link{Match}} function.  See the \code{Var.calc} option if one
+    does not want to assume homoscedasticity.}
+  \item{Var.calc}{A scalar for the variance estimate
+    that should be used.  By default \code{Var.calc=0} which means that
+    homoscedasticity is assumed.  For values of  \code{Var.calc > 0},
+    robust variances are calculated using \code{Var.calc} matches.}  
+  \item{Weight}{ A scalar for the type of
+    weighting scheme the matching algorithm should use when weighting
+    each of the covariates in \code{X}.  The default value of
+    1 denotes that weights are equal to the inverse of the variances. 2
+    denotes the Mahalanobis distance metric, and 3 denotes
+    that the user will supply a weight matrix (\code{Weight.matrix}).  Note that
+    if the user supplies a \code{Weight.matrix}, \code{Weight} will be automatically
+    set to be equal to 3.}
+  \item{Weight.matrix}{ This matrix denotes the weights the matching
+    algorithm uses when weighting each of the covariates in \code{X}---see
+    the \code{Weight} option. This square matrix should have as many
+    columns as the number of columns of the \code{X} matrix. This matrix
+    is usually provided by a call to the \code{\link{GenMatch}} function
+    which finds the optimal weight each variable should be given so as to
+    achieve balance on the covariates. \cr
+
+    For most uses, this matrix has zeros in the off-diagonal
+    cells.  This matrix can be used to weight some variables more than
+    others.  For
+    example, if \code{X} contains three variables and we want to 
+    match as best as we can on the first, the following would work well:
+    \cr
+    \code{> Weight.matrix <- diag(3)}\cr
+    \code{> Weight.matrix[1,1] <- 1000/var(X[,1])} \cr
+    \code{> Weight.matrix[2,2] <- 1/var(X[,2])} \cr
+    \code{> Weight.matrix[3,3] <- 1/var(X[,3])} \cr
+    This code changes the weights implied by the
+    inverse of the variances by multiplying the first variable by a 1000
+    so that it is highly weighted.  In order to enforce exact matching
+    see the \code{exact} and \code{caliper} options.}
+  \item{distance.tolerance}{This is a scalar which is used to determine if distances
+    between two observations are different from zero.  Values less than
+    \code{distance.tolerance} are deemed to be equal to zero.  This
+    option can be used to perform a type of optimal matching}
+  \item{tolerance}{ This is a scalar which is used to determine
+    numerical tolerances.  This option is used by numerical routines
+    such as those used to determine if a matrix is singular.}
+  \item{print.level}{The level of printing. Set to '0' to turn off printing.}
+  \item{version}{The version of the code to be used.  The "Matchby" C/C++
+    version of the code is the fastest, and the end-user should not
+    change this option.}
+  \item{...}{Additional arguments passed on to \code{\link{Match}}.}
+}
+\details{
+  \code{Matchby} is much faster for large datasets than
+  \code{\link{Match}}.  But \code{Matchby} only implements a subset of
+  the functionality of \code{\link{Match}}.  For example, the
+  \code{restrict} option cannot be used, Abadie-Imbens standard errors
+  are not provided and bias adjustment cannot be requested.
+  \code{Matchby} is a wrapper for the \code{\link{Match}} function which
+  separates the matching problem into subgroups defined by a factor.  This
+  is the equivalent to doing exact matching on each factor, and the
+  way in which matches are found within each factor is determined by the
+  usual matching options. \cr
+
+  \emph{Note that by default \code{ties=FALSE} although the default for
+    the \code{Match} in \code{GenMatch} functions is \code{TRUE}.  This is
+    done because randomly breaking ties in large datasets often results in
+    a great speedup.}  For additional speed, consider doing matching
+  without replacement which is often much faster when the dataset is
+  large---see the \code{replace} option. \cr
+
+  There will be slight differences in the matches produced by
+  \code{Matchby} and \code{\link{Match}} because of how the covariates
+  are weighted.  When the data is broken up into separate groups (via
+  the \code{by} option), Mahalanobis distance and inverse variance
+  will imply different weights than when the data is taken as whole.
+}
+
+\value{
+  \item{est}{The estimated average causal effect.}
+  \item{se.standard }{The usual standard error.  This is the standard error
+    calculated on the matched data using the usual method of calculating
+    the difference of means (between treated and control) weighted so
+    that ties are taken into account.}
+  \item{se }{The Abadie-Imbens standard error. This is only calculated
+    if the \code{AI} option is \code{TRUE}. This standard error has
+    correct coverage if \code{X} consists of either covariates or a
+    known propensity score because it takes into account the uncertainty
+    of the matching
+    procedure.  If an estimated propensity score is used, the
+    uncertainty involved in its estimation is not accounted for although the
+    uncertainty of the matching procedure itself still is.}  
+  \item{index.treated }{A vector containing the observation numbers from
+    the original dataset for the treated observations in the
+    matched dataset.  This index in conjunction with \code{index.control}
+    can be used to recover the matched dataset produced by
+    \code{Matchby}.  For example, the \code{X} matrix used by \code{Matchby}
+    can be recovered by
+    \code{rbind(X[index.treated,],X[index.control,])}.}
+  \item{index.control }{A vector containing the observation numbers from
+    the original data for the control observations in the
+    matched data.  This index in conjunction with \code{index.treated}
+    can be used to recover the matched dataset produced by
+    \code{Matchby}.  For example, the \code{Y} matrix for the matched dataset
+    can be recovered by
+    \code{c(Y[index.treated],Y[index.control])}.}
+  \item{weights}{The weights for each observation in the matched
+    dataset.}
+  \item{orig.nobs }{The original number of observations in the dataset.}
+  \item{nobs }{The number of observations in the matched dataset.}
+  \item{wnobs }{The number of weighted observations in the matched dataset.}    
+  \item{orig.treated.nobs}{The original number of treated observations.}    
+  \item{ndrops}{The number of matches which were dropped because there
+    were not enough observations in a given group and because of
+    caliper and exact matching.}
+  \item{estimand}{The estimand which was estimated.}
+  \item{version}{The version of \code{\link{Match}} which was used.}
+}
+\references{
+  Sekhon, Jasjeet S. 2011.  "Multivariate and Propensity Score
+  Matching Software with Automated Balance Optimization.''
+  \emph{Journal of Statistical Software} 42(7): 1-52.
+  \url{http://www.jstatsoft.org/v42/i07/}
+
+  Diamond, Alexis and Jasjeet S. Sekhon. 2013. "Genetic
+  Matching for Estimating Causal Effects: A General Multivariate
+  Matching Method for Achieving Balance in Observational Studies.''
+  \emph{Review of Economics and Statistics}.  95 (3): 932--945.
+  \url{http://sekhon.berkeley.edu/papers/GenMatch.pdf}
+
+  Abadie, Alberto and Guido Imbens. 2006.
+  ``Large Sample Properties of Matching Estimators for Average
+  Treatment Effects.'' \emph{Econometrica} 74(1): 235-267.
+
+  Imbens, Guido. 2004. Matching Software for Matlab and
+  Stata. 
+
+}
+\author{Jasjeet S. Sekhon, UC Berkeley, \email{sekhon at berkeley.edu},
+  \url{http://sekhon.berkeley.edu/}.
+}
+\seealso{ Also see \code{\link{Match}},
+    \code{\link{summary.Matchby}},
+    \code{\link{GenMatch}},
+    \code{\link{MatchBalance}},
+    \code{\link{balanceUV}},
+    \code{\link{qqstats}}, \code{\link{ks.boot}},
+    \code{\link{GerberGreenImai}}, \code{\link{lalonde}}
+}
+\examples{
+#
+# Match exactly by racial groups and then match using the propensity score within racial groups
+#
+
+data(lalonde)
+
+#
+# Estimate the Propensity Score
+#
+glm1  <- glm(treat~age + I(age^2) + educ + I(educ^2) + 
+             hisp + married + nodegr + re74  + I(re74^2) + re75 + I(re75^2) +
+             u74 + u75, family=binomial, data=lalonde)
+
+
+#save data objects
+#
+X  <- glm1$fitted
+Y  <- lalonde$re78
+Tr <- lalonde$treat
+
+# one-to-one matching with replacement (the "M=1" option) after exactly
+# matching on race using the 'by' option.  Estimating the treatment
+# effect on the treated (the "estimand" option defaults to ATT).
+rr  <- Matchby(Y=Y, Tr=Tr, X=X, by=lalonde$black, M=1);
+summary(rr)
+
+# Let's check the covariate balance
+# 'nboots' is set to small values in the interest of speed.
+# Please increase to at least 500 each for publication quality p-values.  
+mb  <- MatchBalance(treat~age + I(age^2) + educ + I(educ^2) + black +
+                    hisp + married + nodegr + re74  + I(re74^2) + re75 + I(re75^2) +
+                    u74 + u75, data=lalonde, match.out=rr, nboots=10)
+
+}
+\keyword{nonparametric}
+
+
+%  LocalWords:  MatchBalance GenMatch emph estimand ATT BiasAdjust calc dataset
+%  LocalWords:  ATC ecaliper cr diag homoscedasticity rbind GerberGreenImai se
+%  LocalWords:  DehejiaWahba AbadieImbens noadj cond mdata datasets wnobs url
+%  LocalWords:  ndrops Abadie Imbens Econometrica Matlab Stata UC seealso Wahba
+%  LocalWords:  balanceUV lalonde Dehejia psid Rajeev Sadek glm hisp
+%  LocalWords:  nodegr rr nboots nmc mb Matchby ret qqstats Mahalanobis SEs
+%  LocalWords:  estimands
diff --git a/man/balanceUV.Rd b/man/balanceUV.Rd
new file mode 100644
index 0000000..dd6ab30
--- /dev/null
+++ b/man/balanceUV.Rd
@@ -0,0 +1,116 @@
+\name{balanceUV}
+\alias{balanceUV}
+\title{Univariate Balance Tests}
+\description{
+  This function provides a number of univariate balance metrics.
+  Generally, users should call \code{\link{MatchBalance}} and not this function
+  directly.
+}
+\usage{
+balanceUV(Tr, Co, weights = rep(1, length(Co)), exact = FALSE, ks=FALSE,
+          nboots = 1000, paired=TRUE, match=FALSE,
+          weights.Tr=rep(1,length(Tr)), weights.Co=rep(1,length(Co)),
+          estimand="ATT")
+}
+\arguments{
+  \item{Tr}{A vector containing the treatment observations.}
+  \item{Co}{A vector containing the control observations.}
+  \item{weights}{A vector containing the observation specific
+    weights. Only use this option when the treatment and control
+    observations are paired (as they are after matching).}
+  \item{exact}{A logical flag indicating if the exact Wilcoxon test
+    should be used instead of the test with a correction.  See
+    \code{\link{wilcox.test}} for details.}
+  \item{ks}{ A logical flag for if the univariate bootstrap
+    Kolmogorov-Smirnov (KS) test should be calculated.  If the ks option
+    is set to true, the univariate KS test is calculated for all
+    non-dichotomous variables.  The bootstrap KS test is consistent even
+    for non-continuous variables.  See \code{\link{ks.boot}} for more
+    details.}
+  \item{nboots}{The number of bootstrap samples to be run for the
+    \code{ks} test.  If zero, no bootstraps are done.  Bootstrapping is
+    highly recommended because the bootstrapped Kolmogorov-Smirnov test
+    only provides correct coverage even for non-continuous covariates. At
+    least 500 \code{nboots} (preferably 1000) are
+    recommended for publication quality p-values.}
+  \item{paired}{A flag for if the paired \code{\link{t.test}} should be used.}
+  \item{match}{A flag for if the \code{Tr} and \code{Co} objects are the result
+    of a call to \code{\link{Match}}.}
+  \item{weights.Tr}{A vector of weights for the treated observations.}
+  \item{weights.Co}{A vector of weights for the control observations.}
+  \item{estimand}{This determines if the standardized mean difference
+    returned by the \code{sdiff} object is standardized by the variance of
+    the treatment observations (which is done if the estimand is either
+    "ATE" or "ATT") or by the variance of the control observations (which
+    is done if the estimand is "ATC").}
+}
+\value{
+  \item{sdiff}{This is the standardized difference between the treated
+    and control units multiplied by 100.  That is, 100 times the mean
+    difference  between treatment and control units divided by the standard
+    deviation of the treatment
+    observations alone if the estimand is either \code{ATT} or
+    \code{ATE}.  The variance of the control observations are used if
+    the estimand is \code{ATC}.}
+  \item{sdiff.pooled}{This is the standardized difference between the
+    treated and control units multiplied by 100 using the pooled
+    variance.  That is, 100 times the mean
+    difference between treatment and control units divided by the pooled standard deviation as in
+    Rosenbaum and Rubin (1985).}
+  \item{mean.Tr}{The mean of the treatment group.}
+  \item{mean.Co}{The mean of the control group.}
+  \item{var.Tr}{The variance of the treatment group.}
+  \item{var.Co}{The variance of the control group.}
+  \item{p.value}{The p-value from the two-sided weighted \code{\link{t.test}}.}
+  \item{var.ratio}{var.Tr/var.Co.}
+  \item{ks}{The object returned by \code{\link{ks.boot}}.}
+  \item{tt}{The object returned by two-sided weighted
+    \code{\link{t.test}}.}
+  \item{qqsummary}{The return object from a call to
+    \code{\link{qqstats}} with standardization---i.e., balance test
+    based on the empirical CDF.}
+  \item{qqsummary.raw}{The return object from a call to
+    \code{\link{qqstats}} without standardization--i.e., balance tests
+    based on the empirical QQ-plot which retain the scale of the
+    variable.}
+}
+\author{
+  Jasjeet S. Sekhon, UC Berkeley, \email{sekhon at berkeley.edu},
+  \url{http://sekhon.berkeley.edu/}.  
+}
+\references{
+  Sekhon, Jasjeet S. 2011.  "Multivariate and Propensity Score
+  Matching Software with Automated Balance Optimization.''
+  \emph{Journal of Statistical Software} 42(7): 1-52.
+  \url{http://www.jstatsoft.org/v42/i07/}
+
+  Diamond, Alexis and Jasjeet S. Sekhon. 2013. "Genetic
+  Matching for Estimating Causal Effects: A General Multivariate
+  Matching Method for Achieving Balance in Observational Studies.''
+  \emph{Review of Economics and Statistics}.  95 (3): 932--945.
+  \url{http://sekhon.berkeley.edu/papers/GenMatch.pdf}
+
+  Rosenbaum, Paul R. and Donald B. Rubin. 1985. ``Constructing a Control
+  Group Using Multivariate Matched Sampling Methods That Incorporate the
+  Propensity Score.'' \emph{The American Statistician} 39:1 33-38.
+
+  Hollander, Myles and Douglas A. Wolfe. 1973. \emph{Nonparametric
+    statistical inference}. New York: John Wiley & Sons.
+  }
+  \seealso{ Also see \code{\link{summary.balanceUV}}, \code{\link{qqstats}}
+    \code{\link{ks.boot}}, \code{\link{Match}}, \code{\link{GenMatch}},
+    \code{\link{MatchBalance}},
+    \code{\link{GerberGreenImai}}, \code{\link{lalonde}} }
+\examples{
+data(lalonde)
+attach(lalonde)
+
+foo  <- balanceUV(re75[treat==1],re75[treat!=1])
+summary(foo)
+
+}
+\keyword{univar}
+
+%  LocalWords:  balanceUV Univariate MatchBalance nboots Wilcoxon wilcox sdiff
+%  LocalWords:  Kolmogorov tt UC url emph seealso GenMatch lalonde
+%  LocalWords:  GerberGreenImai univar qqstats
diff --git a/man/ks.boot.Rd b/man/ks.boot.Rd
new file mode 100644
index 0000000..4e73c1a
--- /dev/null
+++ b/man/ks.boot.Rd
@@ -0,0 +1,101 @@
+\name{ks.boot}
+\alias{ks.boot}
+\title{Bootstrap Kolmogorov-Smirnov}
+\description{
+  This function executes a bootstrap version of the univariate
+  Kolmogorov-Smirnov test which provides correct coverage even when
+  the distributions being compared are not entirely continuous.  Ties
+  are allowed with this test unlike the traditional Kolmogorov-Smirnov
+  test.
+}
+\usage{
+ks.boot(Tr, Co, nboots=1000, alternative = c("two.sided","less","greater"),
+        print.level=0)
+}
+\arguments{
+  \item{Tr}{A vector containing the treatment observations.}
+  \item{Co}{A vector containing the control observations.}
+  \item{nboots}{The number of bootstraps to be performed.  These are, in
+    fact, really Monte Carlo simulations which are preformed in order to
+    determine the proper p-value from the empiric.}
+  \item{alternative}{indicates the alternative hypothesis and must be one of
+    '"two.sided"' (default), '"less"', or '"greater"'.  You can
+    specify just the initial letter.  See \code{\link{ks.test}} for details.}
+  \item{print.level}{If this is greater than 1, then the simulation count is
+    printed out while the simulations are being done.}
+}
+\value{
+  \item{ks.boot.pvalue}{The bootstrap p-value of the Kolmogorov-Smirnov test
+    for the hypothesis that the probability densities for both the
+    treated and control groups are the same.}
+  \item{ks}{Return object from \code{\link{ks.test}}.}
+  \item{nboots}{The number of bootstraps which were completed.}
+}
+\author{
+  Jasjeet S. Sekhon, UC Berkeley, \email{sekhon at berkeley.edu},
+  \url{http://sekhon.berkeley.edu/}.  
+}
+\references{
+  Sekhon, Jasjeet S. 2011.  "Multivariate and Propensity Score
+  Matching Software with Automated Balance Optimization.''
+  \emph{Journal of Statistical Software} 42(7): 1-52.
+  \url{http://www.jstatsoft.org/v42/i07/}
+
+  Diamond, Alexis and Jasjeet S. Sekhon. 2013. "Genetic Matching for
+  Estimating Causal Effects: A General Multivariate Matching Method for
+  Achieving Balance in Observational Studies.'' \emph{Review of
+  Economics and Statistics}.  95 (3): 932--945.
+  \url{http://sekhon.berkeley.edu/papers/GenMatch.pdf}
+  
+  Abadie, Alberto.  2002.  ``Bootstrap Tests for Distributional Treatment
+  Effects in Instrumental Variable Models.'' \emph{Journal of the
+  American Statistical Association}, 97:457 (March) 284-292.
+  }
+  \seealso{ Also see \code{\link{summary.ks.boot}},
+    \code{\link{qqstats}}, \code{\link{balanceUV}}, \code{\link{Match}},
+    \code{\link{GenMatch}}, \code{\link{MatchBalance}}, 
+    \code{\link{GerberGreenImai}}, \code{\link{lalonde}} }
+\examples{
+#
+# Replication of Dehejia and Wahba psid3 model
+#
+# Dehejia, Rajeev and Sadek Wahba. 1999.``Causal Effects in
+# Non-Experimental Studies: Re-Evaluating the Evaluation of Training
+# Programs.''Journal of the American Statistical Association 94 (448):
+# 1053-1062.
+#
+data(lalonde)
+
+#
+# Estimate the propensity model
+#
+glm1  <- glm(treat~age + I(age^2) + educ + I(educ^2) + black +
+             hisp + married + nodegr + re74  + I(re74^2) + re75 + I(re75^2) +
+             u74 + u75, family=binomial, data=lalonde)
+
+
+#
+#save data objects
+#
+X  <- glm1$fitted
+Y  <- lalonde$re78
+Tr  <- lalonde$treat
+
+#
+# one-to-one matching with replacement (the "M=1" option).
+# Estimating the treatment effect on the treated (the "estimand" option which defaults to 0).
+#
+rr  <- Match(Y=Y,Tr=Tr,X=X,M=1);
+summary(rr)
+
+#
+# Do we have balance on 1975 income after matching?
+#
+ks  <- ks.boot(lalonde$re75[rr$index.treated], lalonde$re75[rr$index.control], nboots=500)
+summary(ks)
+}
+\keyword{htest}
+
+%  LocalWords:  Kolmogorov nboots ksboot pvalue UC url Abadie emph seealso psid
+%  LocalWords:  balanceUV GenMatch MatchBalance GerberGreenImai Wahba
+%  LocalWords:  lalonde Dehejia Rajeev Sadek glm hisp nodegr estimand rr htest
diff --git a/man/lalonde.Rd b/man/lalonde.Rd
new file mode 100644
index 0000000..c3a0b69
--- /dev/null
+++ b/man/lalonde.Rd
@@ -0,0 +1,52 @@
+\name{lalonde}
+\alias{lalonde}
+\docType{data}
+\title{Lalonde Dataset}
+\description{
+  Dataset used by Dehejia and Wahba (1999) to evaluate propensity score matching.
+}
+\usage{data(lalonde)}
+\format{
+  A data frame with 445 observations on the following 12 variables.
+  \describe{
+    \item{age}{age in years.}
+    \item{educ}{years of schooling.}
+    \item{black}{indicator variable for blacks.}
+    \item{hisp}{indicator variable for Hispanics.}
+    \item{married}{indicator variable for martial status.}
+    \item{nodegr}{indicator variable for high school diploma.}
+    \item{re74}{real earnings in 1974.}
+    \item{re75}{real earnings in 1975.}
+    \item{re78}{real earnings in 1978.}
+    \item{u74}{indicator variable for earnings in 1974 being zero.}
+    \item{u75}{indicator variable for earnings in 1975 being zero.}
+    \item{treat}{an indicator variable for treatment status.}
+  }
+}
+\details{
+  Two demos are provided which use this dataset.  The first,
+  \code{DehejiaWahba}, replicates one of the models from Dehejia and
+  Wahba (1999).  The second demo, \code{AbadieImbens}, replicates the
+  models produced by Abadie and Imbens in their Matlab code. 
+  Many of these models are found to produce good balance for the Lalonde
+  data.
+  }
+\references{
+  Dehejia, Rajeev and Sadek Wahba. 1999.``Causal Effects in
+  Non-Experimental Studies: Re-Evaluating the
+  Evaluation of Training Programs.'' \emph{Journal of the American Statistical
+  Association} 94 (448): 1053-1062.
+
+  LaLonde, Robert. 1986.  ``Evaluating the Econometric Evaluations of
+  Training Programs.''  \emph{American Economic Review} 76:604-620.
+} 
+  \seealso{ Also see \code{\link{Match}}, \code{\link{GenMatch}},
+  \code{\link{MatchBalance}},
+   \code{\link{balanceUV}},
+   \code{\link{ks.boot}}, \code{\link{GerberGreenImai}} }
+\keyword{datasets}
+
+%  LocalWords:  lalonde docType Dataset Dehejia Wahba hisp nodegr dataset url
+%  LocalWords:  DehejiaWahba AbadieImbens Abadie Imbens Rajeev Sadek emph
+%  LocalWords:  seealso GenMatch MatchBalance balanceUV datasets
+%  LocalWords:  GerberGreenImai
diff --git a/man/qqstats.Rd b/man/qqstats.Rd
new file mode 100644
index 0000000..ace1e4d
--- /dev/null
+++ b/man/qqstats.Rd
@@ -0,0 +1,104 @@
+\name{qqstats}
+\alias{qqstats}
+\title{QQ Summary Statistics}
+\description{
+  This function calculates a set of summary statistics for the QQ
+  plot of two samples of data.  The summaries are useful for determining
+  if the two samples are from the same distribution.  If
+  \code{standardize==TRUE}, the empirical CDF is used instead of the
+  empirical-QQ plot.  The later retains the scale of the variable.
+}
+\usage{
+qqstats(x, y, standardize=TRUE, summary.func)
+}
+\arguments{
+  \item{x}{The first sample.}
+  \item{y}{The second sample.}
+  \item{standardize}{A logical flag for whether the statistics should be
+  standardized by the empirical cumulative distribution functions of the
+  two samples.}
+  \item{summary.func}{A user provided function to summarize the
+    difference between the two distributions.  The function should
+    expect a vector of the differences as an argument and return summary
+    statistic.  For example, the \code{\link{quantile}} function is a
+    legal function to pass in.}
+}
+\value{
+  \item{meandiff}{The mean difference between the QQ plots of the two
+    samples.}
+  \item{mediandiff}{The median difference between the QQ plots of the
+    two samples.}
+  \item{maxdiff}{The maximum difference between the QQ plots of the two
+    samples.}
+  \item{summarydiff}{If the user provides a \code{summary.func}, the
+    user requested summary difference is returned.}
+  \item{summary.func}{If the user provides a \code{summary.func}, the
+    function is returned.}
+}
+\author{
+  Jasjeet S. Sekhon, UC Berkeley, \email{sekhon at berkeley.edu},
+  \url{http://sekhon.berkeley.edu/}.  
+}
+\references{
+  Sekhon, Jasjeet S. 2011.  "Multivariate and Propensity Score
+  Matching Software with Automated Balance Optimization.''
+  \emph{Journal of Statistical Software} 42(7): 1-52.
+  \url{http://www.jstatsoft.org/v42/i07/}
+
+  Diamond, Alexis and Jasjeet S. Sekhon. Forthcoming. "Genetic Matching for
+  Estimating Causal Effects: A General Multivariate Matching Method for
+  Achieving Balance in Observational Studies.'' \emph{Review of Economics and Statistics}.
+  \url{http://sekhon.berkeley.edu/papers/GenMatch.pdf}
+  }
+  \seealso{ Also see \code{\link{ks.boot}},
+    \code{\link{balanceUV}}, \code{\link{Match}},
+    \code{\link{GenMatch}},
+    \code{\link{MatchBalance}},
+    \code{\link{GerberGreenImai}}, \code{\link{lalonde}} }
+\examples{
+#
+# Replication of Dehejia and Wahba psid3 model
+#
+# Dehejia, Rajeev and Sadek Wahba. 1999.``Causal Effects in
+# Non-Experimental Studies: Re-Evaluating the Evaluation of Training
+# Programs.''Journal of the American Statistical Association 94 (448):
+# 1053-1062.
+#
+
+data(lalonde)
+
+#
+# Estimate the propensity model
+#
+glm1  <- glm(treat~age + I(age^2) + educ + I(educ^2) + black +
+             hisp + married + nodegr + re74  + I(re74^2) + re75 + I(re75^2) +
+             u74 + u75, family=binomial, data=lalonde)
+
+
+#
+#save data objects
+#
+X  <- glm1$fitted
+Y  <- lalonde$re78
+Tr  <- lalonde$treat
+
+#
+# one-to-one matching with replacement (the "M=1" option).
+# Estimating the treatment effect on the treated (the "estimand" option which defaults to 0).
+#
+rr  <- Match(Y=Y,Tr=Tr,X=X,M=1);
+summary(rr)
+
+#
+# Do we have balance on 1975 income after matching?
+#
+qqout  <- qqstats(lalonde$re75[rr$index.treated], lalonde$re75[rr$index.control])
+print(qqout)
+}
+\keyword{htest}
+\keyword{distribution}
+
+%  LocalWords:  Kolmogorov nboots ksboot pvalue UC url Abadie emph seealso psid
+%  LocalWords:  balanceUV GenMatch MatchBalance GerberGreenImai Wahba
+%  LocalWords:  lalonde Dehejia Rajeev Sadek glm hisp nodegr estimand rr htest
+%  LocalWords:  maxdiff QQ summarydiff func qqout qqstats meandiff mediandiff
diff --git a/man/summary.Match.Rd b/man/summary.Match.Rd
new file mode 100644
index 0000000..a9e3145
--- /dev/null
+++ b/man/summary.Match.Rd
@@ -0,0 +1,32 @@
+\name{summary.Match}
+\alias{summary.Match}
+\alias{print.summary.Match}
+\title{Summarizing output from Match}
+\description{
+  \code{\link{summary}} method for class \code{\link{Match}}
+}
+\usage{
+  \method{summary}{Match}(object, ... , full=FALSE, digits=5)
+}
+\arguments{
+  \item{object}{An object of class "\code{Match}", usually, a
+    result of a call to \code{\link{Match}}.}
+  \item{full}{A flag for whether the unadjusted estimates and naive
+    standard errors should also be summarized.}
+  \item{digits}{The number of significant digits that should be
+    displayed.}
+  \item{...}{Other options for the generic summary function.}
+}
+\author{
+  Jasjeet S. Sekhon, UC Berkeley, \email{sekhon at berkeley.edu},
+  \url{http://sekhon.berkeley.edu/}.  
+}
+\seealso{ Also see \code{\link{Match}}, \code{\link{GenMatch}},
+  \code{\link{MatchBalance}}, 
+  \code{\link{balanceUV}}, \code{\link{qqstats}}, \code{\link{ks.boot}},
+  \code{\link{GerberGreenImai}}, \code{\link{lalonde}}
+}
+\keyword{htest}
+
+%  LocalWords:  UC url seealso GenMatch MatchBalance balanceUV htest
+%  LocalWords:  GerberGreenImai lalonde
diff --git a/man/summary.Matchby.Rd b/man/summary.Matchby.Rd
new file mode 100644
index 0000000..3aac546
--- /dev/null
+++ b/man/summary.Matchby.Rd
@@ -0,0 +1,30 @@
+\name{summary.Matchby}
+\alias{summary.Matchby}
+\alias{print.summary.Matchby}
+\title{Summarizing output from Matchby}
+\description{
+  \code{\link{summary}} method for class \code{\link{Matchby}}
+}
+\usage{
+  \method{summary}{Matchby}(object, ... , digits=5)
+}
+\arguments{
+  \item{object}{An object of class "\code{Matchby}", usually, a
+    result of a call to \code{\link{Matchby}}.}
+  \item{digits}{The number of significant digits that should be
+    displayed.}
+  \item{...}{Other options for the generic summary function.}
+}
+\author{
+  Jasjeet S. Sekhon, UC Berkeley, \email{sekhon at berkeley.edu},
+  \url{http://sekhon.berkeley.edu/}.  
+}
+\seealso{ Also see \code{\link{Matchby}},  \code{\link{Match}}, \code{\link{GenMatch}},
+  \code{\link{MatchBalance}}, 
+  \code{\link{balanceUV}}, \code{\link{qqstats}}, \code{\link{ks.boot}},
+  \code{\link{GerberGreenImai}}, \code{\link{lalonde}}
+}
+\keyword{htest}
+
+%  LocalWords:  UC url seealso GenMatch MatchBalance balanceUV htest
+%  LocalWords:  GerberGreenImai lalonde Matchby qqstats
diff --git a/man/summary.balanceUV.Rd b/man/summary.balanceUV.Rd
new file mode 100644
index 0000000..1b3730f
--- /dev/null
+++ b/man/summary.balanceUV.Rd
@@ -0,0 +1,31 @@
+\name{summary.balanceUV}
+\alias{summary.balanceUV}
+\title{Summarizing output from balanceUV}
+\description{
+  \code{\link{summary}} method for class \code{\link{balanceUV}}
+}
+\usage{
+  \method{summary}{balanceUV}(object, ..., digits=5)
+}
+\arguments{
+  \item{object}{An object of class "\code{balanceUV}", usually, a
+    result of a call to \code{\link{balanceUV}}.}
+  \item{digits}{The number of significant digits that should be
+    displayed.}
+  \item{...}{Other options for the generic summary function.}  
+}
+\author{
+  Jasjeet S. Sekhon, UC Berkeley, \email{sekhon at berkeley.edu},
+  \url{http://sekhon.berkeley.edu/}.  
+}
+\seealso{
+  Also see \code{\link{balanceUV}}, 
+  \code{\link{Match}}, \code{\link{GenMatch}},
+  \code{\link{MatchBalance}}, \code{\link{qqstats}}, \code{\link{ks.boot}},
+  \code{\link{GerberGreenImai}},
+  \code{\link{lalonde}}
+}
+\keyword{htest}
+
+%  LocalWords:  balanceUV UC url seealso GenMatch MatchBalance htest
+%  LocalWords:  GerberGreenImai lalonde
diff --git a/man/summary.ks.boot.Rd b/man/summary.ks.boot.Rd
new file mode 100644
index 0000000..da23c7d
--- /dev/null
+++ b/man/summary.ks.boot.Rd
@@ -0,0 +1,31 @@
+\name{summary.ks.boot}
+\alias{summary.ks.boot}
+\alias{print.summary.ks.boot}
+\title{Summarizing output from ks.boot}
+\description{
+  \code{\link{summary}} method for class \code{\link{ks.boot}}
+}
+\usage{
+  \method{summary}{ks.boot}(object, ..., digits=5)
+}
+\arguments{
+  \item{object}{An object of class "\code{ks.boot}", usually, a
+    result of a call to \code{\link{ks.boot}}.}
+  \item{digits}{The number of significant digits that should be
+    displayed.}
+  \item{...}{Other options for the generic summary function.}  
+}
+\author{
+  Jasjeet S. Sekhon, UC Berkeley, \email{sekhon at berkeley.edu},
+  \url{http://sekhon.berkeley.edu/}.  
+}
+\seealso{
+  Also see \code{\link{ks.boot}}, \code{\link{balanceUV}}, \code{\link{qqstats}},
+  \code{\link{Match}}, \code{\link{GenMatch}},
+  \code{\link{MatchBalance}}, \code{\link{GerberGreenImai}},
+  \code{\link{lalonde}}
+}
+\keyword{htest}
+
+%  LocalWords:  UC url seealso balanceUV GenMatch MatchBalance htest
+%  LocalWords:  GerberGreenImai lalonde
diff --git a/src/Makevars.in b/src/Makevars.in
new file mode 100644
index 0000000..bc21262
--- /dev/null
+++ b/src/Makevars.in
@@ -0,0 +1,3 @@
+PKG_CFLAGS   = @PKG_CFLAGS@
+PKG_CXXFLAGS = @PKG_CXXFLAGS@
+
diff --git a/src/Makevars.win b/src/Makevars.win
new file mode 100644
index 0000000..9548d03
--- /dev/null
+++ b/src/Makevars.win
@@ -0,0 +1,3 @@
+PKG_CFLAGS = -O3 -finline-functions -funswitch-loops -fgcse-after-reload -funroll-loops 
+PKG_CXXFLAGS = -O3 -finline-functions -funswitch-loops -fgcse-after-reload -funroll-loops 
+PKG_LIBS = $(BLAS_LIBS)
diff --git a/src/cblas.h b/src/cblas.h
new file mode 100644
index 0000000..e9f4d53
--- /dev/null
+++ b/src/cblas.h
@@ -0,0 +1,38 @@
+/* 
+   CBLAS provides a C interface to the BLAS routines, which were
+   originally written in FORTRAN.  CBLAS wrappers are already provided
+   on Windows and OS X, but not on other UNIX-like operating systems
+   (such as Linux). For most platforms (particularly AMD chips), I
+   recommend Kazushige Goto's High-Performance BLAS Library:
+
+   http://www.cs.utexas.edu/users/flame/goto/
+   
+   For more information on BLAS (including function definitions) see:
+   http://www.netlib.org/blas/
+   
+   Note that I have only included wrappers for the BLAS functions which
+   the Matching package actually uses.
+   
+   Jas Sekhon
+   <sekhon at berkeley.edu>
+   http://sekhon.berkeley.edu
+   August 1, 2007
+*/
+
+
+#ifndef CBLAS_H
+#define CBLAS_H
+#endif
+#include <stddef.h>
+
+/*
+ * Enumerated and derived types
+ */
+#define CBLAS_INDEX size_t  /* this may vary between platforms */
+
+enum CBLAS_ORDER {CblasRowMajor=101, CblasColMajor=102};
+enum CBLAS_TRANSPOSE {CblasNoTrans=111, CblasTrans=112, CblasConjTrans=113};
+enum CBLAS_UPLO {CblasUpper=121, CblasLower=122};
+enum CBLAS_DIAG {CblasNonUnit=131, CblasUnit=132};
+enum CBLAS_SIDE {CblasLeft=141, CblasRight=142};
+
diff --git a/src/cblas_dasum.c b/src/cblas_dasum.c
new file mode 100644
index 0000000..848981a
--- /dev/null
+++ b/src/cblas_dasum.c
@@ -0,0 +1,48 @@
+/* 
+   DASUM - BLAS level one, sums the absolute values of the elements of
+   a double precision vector
+   
+   * cblas_dasum.c
+   *
+   * The program is a C interface to dasum
+   * It calls the fortran wrapper before calling dasum.
+   *
+   * Written by Keita Teranishi.  2/11/1998
+   
+   CBLAS provides a C interface to the BLAS routines, which were
+   originally written in FORTRAN.  CBLAS wrappers are already provided
+   on Windows and OS X, but not on other UNIX-like operating systems
+   (such as Linux). For most platforms (particularly AMD chips), I
+   recommend Kazushige Goto's High-Performance BLAS Library:
+
+   http://www.cs.utexas.edu/users/flame/goto/
+   
+   For more information on BLAS (including function definitions) see:
+   http://www.netlib.org/blas/
+   
+   Note that I have only included wrappers for the BLAS functions which
+   the Matching package actually uses.
+
+   Jas Sekhon
+   <sekhon at berkeley.edu>
+   http://sekhon.berkeley.edu
+   August 1, 2007
+*/
+
+
+#include <R.h>
+#include <R_ext/Applic.h> /* R blas declarations */
+
+#include "cblas.h"
+double cblas_dasum( const int N, const double *X, const int incX) 
+{
+   double asum;
+#ifdef F77_INT
+   F77_INT F77_N=N, F77_incX=incX;
+#else 
+   #define F77_N N
+   #define F77_incX incX
+#endif
+   asum = F77_CALL(dasum)( &F77_N, X, &F77_incX);
+   return asum;
+}
diff --git a/src/cblas_dgemm.c b/src/cblas_dgemm.c
new file mode 100644
index 0000000..a27c7fe
--- /dev/null
+++ b/src/cblas_dgemm.c
@@ -0,0 +1,144 @@
+/* 
+   DGEMM - perform one of the matrix-matrix operations 
+   C := alpha*op( A )*op( B ) + beta*C
+   
+   * cblas_dgemm.c
+   * This program is a C interface to dgemm.
+   * Written by Keita Teranishi
+   * 4/8/1998
+   
+   CBLAS provides a C interface to the BLAS routines, which were
+   originally written in FORTRAN.  CBLAS wrappers are already provided
+   on Windows and OS X, but not on other UNIX-like operating systems
+   (such as Linux). For most platforms (particularly AMD chips), I
+   recommend Kazushige Goto's High-Performance BLAS Library:
+
+   http://www.cs.utexas.edu/users/flame/goto/
+   
+   For more information on BLAS (including function definitions) see:
+   http://www.netlib.org/blas/
+   
+   Note that I have only included wrappers for the BLAS functions which
+   the Matching package actually uses.
+
+   Jas Sekhon
+   <sekhon at berkeley.edu>
+   http://sekhon.berkeley.edu
+   August 1, 2007
+*/
+
+
+#include <R.h>
+#include <R_ext/Applic.h> /* R blas declarations */
+
+#include "cblas.h"
+void cblas_dgemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA,
+                 const enum CBLAS_TRANSPOSE TransB, const int M, const int N,
+                 const int K, const double alpha, const double  *A,
+                 const int lda, const double  *B, const int ldb,
+                 const double beta, double  *C, const int ldc)
+{
+   char TA, TB;   
+#ifdef F77_CHAR
+   F77_CHAR F77_TA, F77_TB;
+#else
+   #define F77_TA &TA  
+   #define F77_TB &TB  
+#endif
+
+#ifdef F77_INT
+   F77_INT F77_M=M, F77_N=N, F77_K=K, F77_lda=lda, F77_ldb=ldb;
+   F77_INT F77_ldc=ldc;
+#else
+   #define F77_M M
+   #define F77_N N
+   #define F77_K K
+   #define F77_lda lda
+   #define F77_ldb ldb
+   #define F77_ldc ldc
+#endif
+
+   /* the follow two vars were originally in Carla's.h as ex-terns, but that runs into conflicts on system with a
+      preexisting cblas */
+   int CBLAS_CallFromC;
+   int RowMajorStrg;
+
+   RowMajorStrg = 0;
+   CBLAS_CallFromC = 1;
+
+   if( Order == CblasColMajor )
+   {
+      if(TransA == CblasTrans) TA='T';
+      else if ( TransA == CblasConjTrans ) TA='C';
+      else if ( TransA == CblasNoTrans )   TA='N';
+      else 
+      {
+	error("cblas_dgemm","Illegal TransA setting, %d\n", TransA);
+	/* cblas_xerbla(2, "cblas_dgemm","Illegal TransA setting, %d\n", TransA); */
+         CBLAS_CallFromC = 0;
+         RowMajorStrg = 0;
+         return;
+      }
+
+      if(TransB == CblasTrans) TB='T';
+      else if ( TransB == CblasConjTrans ) TB='C';
+      else if ( TransB == CblasNoTrans )   TB='N';
+      else 
+      {
+	error("cblas_dgemm","Illegal TransB setting, %d\n", TransB);
+	/* cblas_xerbla(3, "cblas_dgemm","Illegal TransB setting, %d\n", TransB); */
+         CBLAS_CallFromC = 0;
+         RowMajorStrg = 0;
+         return;
+      }
+
+      #ifdef F77_CHAR
+         F77_TA = C2F_CHAR(&TA);
+         F77_TB = C2F_CHAR(&TB);
+      #endif
+
+	 F77_CALL(dgemm)(F77_TA, F77_TB, &F77_M, &F77_N, &F77_K, &alpha, A,
+       &F77_lda, B, &F77_ldb, &beta, C, &F77_ldc);
+   } else if (Order == CblasRowMajor)
+   {
+      RowMajorStrg = 1;
+      if(TransA == CblasTrans) TB='T';
+      else if ( TransA == CblasConjTrans ) TB='C';
+      else if ( TransA == CblasNoTrans )   TB='N';
+      else 
+      {
+	error("cblas_dgemm","Illegal TransA setting, %d\n", TransA);
+	/* cblas_xerbla(2, "cblas_dgemm","Illegal TransA setting, %d\n", TransA); */
+         CBLAS_CallFromC = 0;
+         RowMajorStrg = 0;
+         return;
+      }
+      if(TransB == CblasTrans) TA='T';
+      else if ( TransB == CblasConjTrans ) TA='C';
+      else if ( TransB == CblasNoTrans )   TA='N';
+      else 
+      {
+	error("cblas_dgemm","Illegal TransB setting, %d\n", TransB);
+	/* cblas_xerbla(2, "cblas_dgemm","Illegal TransB setting, %d\n", TransB); */
+         CBLAS_CallFromC = 0;
+         RowMajorStrg = 0;
+         return;
+      }
+      #ifdef F77_CHAR
+         F77_TA = C2F_CHAR(&TA);
+         F77_TB = C2F_CHAR(&TB);
+      #endif
+
+	 F77_CALL(dgemm)(F77_TA, F77_TB, &F77_N, &F77_M, &F77_K, &alpha, B,
+			 &F77_ldb, A, &F77_lda, &beta, C, &F77_ldc);
+   } 
+   else  {
+     error("cblas_dgemm", "Illegal Order setting, %d\n", Order);
+     /* cblas_xerbla(1, "cblas_dgemm", "Illegal Order setting, %d\n", Order); */
+   }
+   CBLAS_CallFromC = 0;
+   RowMajorStrg = 0;
+   return;
+}
+
+
diff --git a/src/cblas_dscal.c b/src/cblas_dscal.c
new file mode 100644
index 0000000..a020f20
--- /dev/null
+++ b/src/cblas_dscal.c
@@ -0,0 +1,45 @@
+/* 
+   DSCAL - BLAS level one, scales a double precision vector
+   
+   * cblas_dscal.c
+   *
+   * The program is a C interface to dscal.
+   *
+   * Written by Keita Teranishi.  2/11/1998
+   
+   CBLAS provides a C interface to the BLAS routines, which were
+   originally written in FORTRAN.  CBLAS wrappers are already provided
+   on Windows and OS X, but not on other UNIX-like operating systems
+   (such as Linux). For most platforms (particularly AMD chips), I
+   recommend Kazushige Goto's High-Performance BLAS Library:
+   
+   http://www.cs.utexas.edu/users/flame/goto/
+   
+   For more information on BLAS (including function definitions) see:
+   http://www.netlib.org/blas/
+   
+   Note that I have only included wrappers for the BLAS functions which
+   the Matching package actually uses.
+   
+   Jas Sekhon
+   <sekhon at berkeley.edu>
+   http://sekhon.berkeley.edu
+   August 1, 2007
+*/
+
+
+#include <R.h>
+#include <R_ext/Applic.h> /* R blas declarations */
+
+#include "cblas.h"
+void cblas_dscal( const int N, const double alpha, double *X, 
+                       const int incX)
+{
+#ifdef F77_INT
+   F77_INT F77_N=N, F77_incX=incX;
+#else 
+   #define F77_N N
+   #define F77_incX incX
+#endif
+   F77_CALL(dscal)( &F77_N, &alpha, X, &F77_incX);
+}
diff --git a/src/matching.cc b/src/matching.cc
new file mode 100644
index 0000000..b5942f1
--- /dev/null
+++ b/src/matching.cc
@@ -0,0 +1,2898 @@
+/*  
+    Jasjeet S. Sekhon <sekhon at berkeley.edu>
+    HTTP://sekhon.berkeley.edu/
+    UC Berkeley
+    
+    2013/10/28
+    Under the GNU Public License Version 3
+
+    A *lot* of work and trail-and-error has gone into these functions
+    to ensure that they are reliable and fast when run either serially
+    or in parallel.  Parallel execution is especially tricky because
+    an algorithm which may be fast in serial mode can cause odd
+    bottlenecks when run in parallel (such as a cache-bottleneck when
+    executing SSE3 instructions via BLAS).  Also, the loops and other
+    structures in these functions have been written so that g++ does a
+    good job of optimizing them.  Indeed, for these functions icc is
+    no faster than g++.
+
+    Details of individuals function are provided right before they are
+    defined, but a general description of them is offered here.
+
+    'EstFuncC': This function is directly called from R (by the
+    est.func() function in Match().  And it estimates the causal
+    effect and properly weights the observations by the number of ties
+    (and the weights on input).
+
+    There are *four* different function to perform the actual
+    matching.  There are four versions because of speed
+    considerations.  That is, they make use of special cases (such as
+    the absence of observational specific weights), to make speed
+    gains.  And for clarity of code it was determined to make them
+    four separate functions instead of adding a lot of if-then
+    statements in one big function.  These functions are long, but it
+    was generally found to be faster to do it this way.  Odd things
+    occur with the optimizations algorithms in various compilers when
+    cross-function optimizations are requested---some optimizations
+    are performed and some are not.  It appears to significantly help
+    gcc to not breakup the functions (at least not to break them up
+    the way I was doing do).
+
+    The core matching functions (note that the slow R equivalent is
+    RmatchLoop() which is located in the Matching.R file.
+
+    'FasterMatchC': for GenMatch(), when there are *no* observation
+    specific weights, we are matching with replacement, keeping ties
+    and are using no caliper, no exact matching and no restriction
+    matrix.  Also note that GenMatch() assumes that the Weight.matrix
+    is a diagonal matrix.  Note that this is the most commonly used
+    matching function for GenMatch, and the fastest.  This function
+    cannot be used with Match(), because it does not reorder the
+    indexes at the end so to be usable to actually estimate causal
+    effects.  This makes the function faster than its equivalent which
+    is called from Match(), 'MatchLoopCfast'.
+
+    'FastMatchC': for GenMatch(), when there are observation specific
+    weights, but we are matching with replacement, keeping ties and
+    are using no caliper, no exact matching and no restriction matrix.
+    Also note that GenMatch() assumes that the Weight.matrix is a
+    diagonal matrix.  This function cannot be used with Match(),
+    because it does not reorder the indexes at the end so to be usable
+    to actually estimate causal effects.  This makes the function
+    faster than its equivalent which is called from Match(),
+    'MatchLoopC'.
+
+    'MatchLoopC': This is the most featured matching function.  It is
+    called by Match() when we have observational specific weights, and
+    by GenMatch() when there are observational specific weights and
+    one or more of no replacement, no ties, exact matching, caliper
+    matching or use of the restriction matrix.
+
+    'MatchLoopCfast': This function is called by Match() when there
+    are no observation specific weights, and by GenMatch() when there
+    are no observational specific weights but one or more of no
+    replacement, no ties, exact matching, caliper matching or use of
+    the restriction matrix.
+*/
+
+/* Note: We are using the include cblas header which will direct to the
+   central R BLAS */
+
+#include "scythematrix.h"
+
+using namespace SCYTHE;
+using namespace std;
+
+/* #include <stdio.h> */
+#include <stdlib.h>
+#include <cmath>
+#include <vector>
+/* Now included from  "scythematrix.h"
+#include <R.h>
+*/
+#include <Rdefines.h>
+
+#include "matching.h"
+
+#ifdef __NBLAS__
+/* #if defined(__darwin__) || defined(__APPLE__)
+#include <vecLib/cblas.h> 
+#else */
+#define INTERNAL_CBLAS 
+#include <R_ext/Applic.h>
+/* #endif  */
+#endif
+
+/* 
+   __GenMatchBLAS_ needlessly calculates Distance for observations who were assigned to the same treatment
+#ifdef __NBLAS__
+#if !defined(__darwin__) & !defined(__APPLE__)
+#define __GenMatchBLAS__
+#endif
+#endif
+*/
+
+extern "C"
+{
+#ifdef INTERNAL_CBLAS
+#include "cblas.h"
+
+  void cblas_dgemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA,
+		   const enum CBLAS_TRANSPOSE TransB, const int M, const int N,
+		   const int K, const double alpha, const double  *A,
+		   const int lda, const double  *B, const int ldb,
+		   const double beta, double  *C, const int ldc);
+
+  void cblas_dscal( const int N, const double alpha, double *X, 
+		    const int incX);
+
+  double cblas_dasum( const int N, const double *X, const int incX);
+#endif
+
+/*---------------------------------------------------------------------------
+   Function :   kth_smallest()
+   In       :   array of elements, # of elements in the array, rank k
+   Out      :   one element
+   Job      :   find the kth smallest element in the array
+   Notice   :   use the median() macro defined below to get the median. 
+
+                Reference:
+
+                http://www.eso.org/~ndevilla/median/
+
+                  Author: Wirth, Niklaus 
+                   Title: Algorithms + data structures = programs 
+               Publisher: Englewood Cliffs: Prentice-Hall, 1976 
+    Physical description: 366 p. 
+                  Series: Prentice-Hall Series in Automatic Computation 
+
+ ---------------------------------------------------------------------------*/
+
+
+  double kth_smallest(double *a, long n, long k)
+  {
+    long i,j,l,m ;
+    double x, tmp;
+    
+    l=0 ; m=n-1 ;
+    while (l<m) {
+      x=a[k] ;
+      i=l ;
+      j=m ;
+      do {
+	while (a[i]<x) i++ ;
+	while (x<a[j]) j-- ;
+	if (i<=j) {
+	  tmp=a[i];
+	  a[i]=a[j];
+	  a[j]=tmp;
+	      i++ ; j-- ;
+	}
+      } while (i<=j) ;
+      if (j<k) l=i ;
+      if (k<i) m=j ;
+    }
+    return a[k] ;
+  } // end of kth_smallest
+
+
+/*---------------------------------------------------------------------------
+   Function : EstFuncC
+
+   IN       : I_N: the number of observations
+
+              I_All: what we are estimating---i.e.,the 'estmand' argument to Match()
+
+              I_length: the number of matched pairs which were found by Match()
+
+              I_Y: the outcome---i.e,. the 'Y' argument to Match()
+
+              I_Tr: the treatment indicator--i.e., the 'Tr' argument to Match()
+
+              I_weight: the observation specific weights---i.e, the 'weight' argument 
+                        to Match()
+
+              I_indx: the return object from one of the core Match()
+                      functions such as 'RmatchLoop', 'FasterMatchC', 'FastMatchC', 
+                      'MatchLoopC', and 'MatchLoopCfast'.
+
+
+   OUT      : A matrix of Yobs by 3 or 4 (if bias correction is being done).  
+              The first column is the causal effect ('YCAUS').
+	       If BiasAdjustment==TRUE, the second column will be the
+	       BiasAdjustment adjusted yby the weights.  And the next
+	       two columns are the weights ('Kcount' and 'KKcount').
+
+   JOB      : To estimate the causal effect and to properly weight the
+              observations by the number of ties (and the weights on input).  
+	       This function is directly called from R (by the est.func() function 
+	       in Match().
+ ---------------------------------------------------------------------------*/
+  
+  SEXP EstFuncC (SEXP I_N, SEXP I_All, SEXP I_length, SEXP I_Y, SEXP I_Tr, SEXP I_weight, SEXP I_indx)
+	      
+  {
+    SEXP ret;
+    
+    long N, All, i, l, j, k, SumFoo, length;
+    double SumFooWeight, SumIndx3;
+    long ic=3;
+
+    N = asInteger(I_N);
+    All = asInteger(I_All);
+    length = asInteger(I_length);
+
+    // In vars
+    Matrix Tr = Matrix(N, 1);
+    Matrix weight = Matrix(N, 1);
+    Matrix indx = Matrix(length, ic);
+    Matrix Y = Matrix(N, 1);
+    
+    // Extra vars
+    Matrix Kcount = Matrix(N, 1);
+    Matrix KKcount = Matrix(N, 1);
+    Matrix YCAUS = Matrix(N, 1);
+    Matrix foo = Matrix(N,1);
+    Matrix WFW = Matrix(N,1);
+    Matrix WWFW = Matrix(N, 1);
+
+    k=0;
+    //rows and colums are fliped!! j,i != i,j
+    for(j=0;j<ic; j++)
+      {
+	for(i=0;i<length; i++)
+	  {
+	    indx[M(i,j,ic)] = REAL(I_indx)[k];
+	    
+	    // count from offest 0 instead of R's offset 1
+	    if(j<2)
+	      {
+		indx[M(i,j,ic)] = indx[M(i,j,ic)] - 1;	
+	      }
+	    k++;
+	  }
+      }
+    
+    for(i=0;i<N; i++)
+      {
+	Y[i] = REAL(I_Y)[i];
+	Tr[i] = REAL(I_Tr)[i];
+	weight[i] = REAL(I_weight)[i];
+      }
+    
+    
+    //Master Loop
+    for (i=0; i<N; i++)
+      {
+	if ( ((int) Tr[i]==1 & All!=1) | (All==1))
+	  {
+	    
+	    SumFooWeight = 0;
+	    SumFoo = 0;
+	    SumIndx3 = 0;
+	    for (l=0; l<length; l++)
+	      {
+		if((int) indx[M(l,0,ic)]==i)
+		  {
+		    SumFoo++;
+		    
+		    k = (int) indx[M(l,1,ic)];
+		    
+		    foo[k] = 1.0;
+		    
+		    SumIndx3 = SumIndx3 + indx[M(l,2,ic)];
+		    SumFooWeight = SumFooWeight + weight[k];
+		  } // end of if
+	      }//end l for
+	  } //Tr[i]
+	
+	if (SumFoo > 0)
+	  {
+	    for (l=0; l<length; l++)
+	      {
+		
+		if((int) indx[M(l,0,ic)]==i)
+		  {
+         	    k = (int) indx[M(l,1,ic)];
+		    
+		    WFW[k]  = weight[k]*foo[k]/SumFooWeight;
+		    WWFW[k] = weight[k]*WFW[k]/SumFooWeight;
+		    
+		    Kcount[k] = Kcount[k] + weight[i] * WFW[k];
+		    
+		    KKcount[k] = KKcount[k] + weight[i]*WWFW[k];
+		    
+		    //if ( ((int) Tr[i]==1 & All!=1) | (All==1))
+		      YCAUS[i] = Y[k]*indx[M(l,2,ic)]/SumIndx3 + YCAUS[i];
+		  } // endof if
+	      } // l for loop
+		
+		if ((int) Tr[i]==1)
+		  {
+		    YCAUS[i] = Y[i] - YCAUS[i];
+		  } 
+		else 
+		  {
+		    YCAUS[i] = YCAUS[i] - Y[i];
+		  }
+	      } //if SumFoo
+      }// end of master N loop
+
+	    
+    PROTECT(ret=allocMatrix(REALSXP, N, 3));
+    
+    // stack up cbind(YCAUS, Kcount, KKcount)
+    k = 0;
+    for( i = 0; i < N; i++ )
+      {
+	REAL(ret)[k] = YCAUS[i];
+	k++;
+      }
+    for( i = 0; i < N; i++ )
+      {
+	REAL(ret)[k] = Kcount[i];
+	k++;
+      }
+    for( i = 0; i < N; i++ )
+      {
+	REAL(ret)[k] = KKcount[i];
+	k++;
+      }
+    UNPROTECT(1);
+    return(ret); 
+  } //end of EstFuncC
+
+
+/*---------------------------------------------------------------------------
+   Function : FasterMatchC
+
+   In       : I_N: the number of observations
+
+              I_xvars: the number of columns in the 'X' matrix---i.e.,
+                       the number of variables to match on.
+
+              I_All: what we are estimating---i.e.,the 'estmand' argument to GenMatch()
+
+              I_M: 1-to-M matching---i.e., this is the 'M' option to GenMatch()
+
+	       I_cdd: Distance tolerance
+
+              I_ww: Weight.matrix, GenMatch assumes that it is diagonal
+
+              I_Tr: the treatment indicator--i.e., the 'Tr' argument to GenMatch()
+
+              I_X: The matrix containing the variable we are going to
+              match on, the 'X' option to GenMatch().
+
+
+   OUT: A matrix of number of matches rows and 3 columns. The first
+   column contains the treatment observations being matched, the
+   second the control observations and the third the weights (adjusted
+   for ties).
+
+   JOB: For GenMatch(), when there are *no* observation specific
+   weights, we are matching with replacement, keeping ties and are
+   using no caliper, no exact matching and no restriction matrix.
+   Also note that GenMatch() assumes that the Weight.matrix is a
+   diagonal matrix.  Note that this is the most commonly used matching
+   function for GenMatch, and the fastest.  This function cannot be
+   used with Match(), because it does not reorder the indexes at the
+   end so to be usable to actually estimate causal effects.  This
+   makes the function faster than its equivalent which is called from
+   Match(), 'MatchLoopCfast'.
+
+ ---------------------------------------------------------------------------*/
+
+  SEXP FasterMatchC(SEXP I_N, SEXP I_xvars, SEXP I_All, SEXP I_M, SEXP I_cdd,
+		    SEXP I_ww, SEXP I_Tr, SEXP I_X)
+  {
+    SEXP ret;
+
+    long N, xvars, All, M; 
+    double cdd, Distmax, Wi_ratio, dfoo;
+    
+    long i, j, k;
+    
+    N = asInteger(I_N);
+    xvars = asInteger(I_xvars);
+    All = asInteger(I_All);
+    M = asInteger(I_M);
+    cdd = asReal(I_cdd);
+    
+    Matrix ww = Matrix(xvars, xvars);
+    Matrix Tr = Matrix(N, 1);
+    Matrix X = Matrix(N, xvars);
+    
+    k=0;
+    //rows and colums are fliped!! j,i != i,j
+    for(j=0;j<xvars; j++)
+    {
+      for(i=0;i<xvars; i++)
+      {
+        //ww(i,j) = REAL(I_ww)[k];
+        ww[M(i,j,xvars)] = REAL(I_ww)[k];
+        k++;
+      }
+    }
+    
+    for(i=0;i<N; i++)
+    {
+      Tr[i] = REAL(I_Tr)[i];
+    }
+    
+    //rows and colums are fliped!! j,i != i,j
+    k=0;
+    for(j=0;j<xvars; j++)
+    {
+      for(i=0;i<N; i++)
+      {
+        //X(i,j) = REAL(I_X)[k];
+        X[M(i,j,xvars)] = REAL(I_X)[k];
+        k++;
+      }
+    }
+    
+    Matrix INN = Matrix::seqa(1, 1, N);
+    // TT is just equal to INN
+
+    Matrix ZX(N, xvars), Dist(N, 1);
+
+    /* set misc */
+    int TREATi = 0;
+    
+    Matrix DistPot;
+    Matrix ACTMAT, POTMAT;
+
+    // Matrices to avoid rbind
+    int NM = N*M*100;
+    Matrix I  = Matrix(NM,1);
+    Matrix IM = Matrix(NM,1);
+    Matrix W  = Matrix(NM,1);
+    
+    //These are larger than needed; it is just easier this way
+    int *order_DistPot = (int *) malloc(N*sizeof(int));  
+    //double *S = (double *) malloc(N*sizeof(double));  
+    
+    int MatchCount=0;
+    int MCindx=0;
+    int overFirstNM=1;
+    for(i=0; i < N; i++)
+    {
+      // treatment indicator for observation to be matched        
+      TREATi = (int) Tr[i];
+      
+      // proceed with all observations if All==1
+      // but only with treated observations if All=0        
+      if ( (TREATi==1 & All!=1) | (All==1) )
+      {
+
+#ifdef __GenMatchBLAS__
+        // this loop is equivalent to the matrix X less the matrix A, which is
+        // the product of N rows by 1 column of 1.0 and row R of X.
+	// I.E.,         xx = X(i,_); DX = (X - (index_onesN * xx)) 
+        double *dest = ZX.data;
+        double *src  = X.data;
+        double *row  = X.data + (i * xvars);
+        for (int jj = 0; jj < N; ++jj) {
+          for (int kk = 0; kk < xvars; ++kk, ++dest, ++src) {
+            *dest = *src - row[kk];
+          }
+        }
+
+	//JSS, dgemm is slower and I assume that dtrmm and dsymm are also
+	//http://docs.sun.com/source/819-3691/dscal.html
+	for (int kk=0; kk < xvars; kk++)
+	  {
+	    cblas_dscal(N, ww.data[M(kk,kk,xvars)], ZX.data+kk, xvars);
+	  }
+
+	ZX.multi_scalar(ZX);
+
+	//http://docs.sun.com/source/819-3691/dasum.html 
+	for (int jj=0; jj < N; jj++)
+	  {
+	    Dist.data[jj] = cblas_dasum(xvars, ZX.data+M(jj, 0, xvars), 1);
+	  }
+
+#else
+	// Don't calculate Distance for observations with of the same treatment assignment
+	// Original No BLAS version from Matching 197, this version from 4.4-52
+        for (int jj = 0; jj < N; jj++) {
+	  if( abs(TREATi-Tr[jj]) > TOL )
+	    {
+	      Dist.data[jj] = 0.0;
+	      for (int kk=0; kk < xvars; kk++)
+		{
+		  ZX.data[M(jj,kk,xvars)] = X.data[M(jj,kk,xvars)] - X.data[M(i,kk,xvars)];
+		  dfoo  = ZX.data[M(jj,kk,xvars)] * ww.data[M(kk,kk,xvars)];
+		  Dist.data[jj] += dfoo*dfoo;
+		}
+	    } // if TR
+	} //end of jj loop
+#endif /* end __GenMatchBLAS__ */
+        
+        // Dist distance to observation to be matched
+        // is N by 1 vector	    
+        
+        // set of potential matches (all observations with other treatment)
+        // JSS, note:logical vector
+        POTMAT = EqualityTestScalar(Tr, 1-TREATi);
+        
+	// X's for potential matches
+	DistPot = selif(Dist, POTMAT);
+	//DistPot_size is a constant!! Fix it
+	long DistPot_size = size(DistPot);
+	
+	//rsort_with_index(DistPot.data, order_DistPot, DistPot_size);
+	//R_rsort(DistPot.data, DistPot_size);
+	//rPsort(DistPot.data, DistPot_size, M);
+	
+	Distmax = kth_smallest(DistPot.data, DistPot_size, (M-1));        
+        
+        // selection of actual matches 
+        // logical index
+        ACTMAT = LessEqualTestScalar(Dist,  (Distmax+cdd));
+        ACTMAT = VectorAnd(POTMAT, ACTMAT);
+        
+        // distance to actual matches.  This is NEVER used.
+        // ACTDIST = selif(Dist, ACTMAT);
+
+	// counts how many times each observation is matched.
+	double Mi = sum(ACTMAT);
+	Wi_ratio = 1/Mi;
+
+	// collect results
+	MatchCount = MatchCount + (int) Mi;
+	
+	if(MatchCount > NM)
+	  {
+	    
+	    NM = NM+N*M*100;
+	    
+	    if(overFirstNM > 0)
+	      {
+		Rprintf("Increasing memory because of ties: allocating a matrix of size 3 times %d doubles.\n", NM);
+		Rprintf("I would be faster with the ties=FALSE option.\n");
+		warning("Increasing memory because of ties.  I would be faster with the ties=FALSE option.");
+	      }
+	    
+	    int OldMatchCount = MatchCount - (int) Mi;
+	    
+	    Matrix tI_tmp  = Matrix(NM,1);
+	    Matrix tIM_tmp = Matrix(NM,1);
+	    Matrix tW_tmp  = Matrix(NM,1);
+
+	    memcpy(tI_tmp.data, I.data, OldMatchCount*sizeof(double));
+	    memcpy(tIM_tmp.data, IM.data, OldMatchCount*sizeof(double));
+	    memcpy(tW_tmp.data, W.data, OldMatchCount*sizeof(double));
+	    /*
+	    cblas_dcopy(OldMatchCount, I.data, 0, tI_tmp.data, 0);
+	    cblas_dcopy(OldMatchCount, IM.data, 0, tIM_tmp.data, 0);
+	    cblas_dcopy(OldMatchCount, W.data, 0, tW_tmp.data, 0);
+	    */
+
+	    I = tI_tmp;
+	    IM = tIM_tmp;
+	    W = tW_tmp;
+	  }
+	
+	//foo1 = ones(ACTMATsum, 1)*(i+1);
+	//memcpy(tI.data+MCindx, foo1.data, foo1.size*sizeof(double));
+	//memcpy(tW.data+MCindx, Wi.data, Wi.size*sizeof(double));
+	
+	for (j=0; j < (int) Mi; j++)
+	  {
+	    I.data[MCindx+j] = i+1;
+	    W.data[MCindx+j] = Wi_ratio;
+	  }
+	
+	k=0;
+	for (j=0; j<N; j++)
+	  {
+	    if(ACTMAT.data[j] > (1-TOL))
+	      {
+		IM.data[MCindx+k] = j+1;
+		k++;
+	      }
+	  }
+	MCindx = MCindx+k;
+      } // end of (TREATi==1 & All!=1) | (All==1) )
+    } //END OF i MASTER LOOP!
+
+    // subset matrices to get back to the right dims
+    long orig_rowsize = I.rowsize;
+    if (MatchCount > 0)
+      {
+	if (orig_rowsize != MatchCount)
+	  {
+	    I.rowsize = MatchCount;
+	    IM.rowsize = MatchCount;
+	    W.rowsize = MatchCount;
+	  }
+      }
+    else
+      {
+	I=Matrix(1, 1);
+	IM=Matrix(1, 1);
+	W=Matrix(1, 1);
+      }
+
+    /*ATT is okay already */
+    /* ATE*/
+    if(All==1)
+    {
+      long tl  = MatchCount;
+      Matrix I2  = Matrix::zeros(tl, 1);
+      Matrix IM2 = Matrix::zeros(tl, 1);
+      Matrix trt = Matrix::zeros(tl, 1);
+      
+      for(i=0; i<tl; i++)
+      {
+        k =(int) I[i] -1 ;
+        trt[i] = Tr[k];
+      }
+      
+      for (i=0; i<tl; i++)
+      {
+        if (trt[i]==1)
+	  {
+	    I2[i] = I[i];
+	    IM2[i] = IM[i];
+	  } 
+        else
+	  {
+	    I2[i] = IM[i];
+	    IM2[i] = I[i];		
+	  }
+      }
+      
+      I = I2;
+      IM = IM2;
+    } 
+    else if(All==2)     /* ATC */
+      {
+	Matrix Itmp = I;
+	Matrix IMtmp = IM;
+	
+	I = IMtmp;
+	IM = Itmp;
+      }
+    
+    /* Free Memory */
+    //free(S);
+    free(order_DistPot);
+
+    //Do we need to readjust to free memory?.  Don't think so.  Check for memory leaks.
+    /*
+    if (orig_rowsize != MatchCount)
+      {
+	I.rowsize = orig_rowsize*1000;
+	IM.rowsize = orig_rowsize*1000;
+	W.rowsize = orig_rowsize*1000;
+      }
+    */
+    
+    PROTECT(ret=allocMatrix(REALSXP, MatchCount, 3));
+    /* Loop through the data and display the same in matrix format */
+    k = 0;
+    for( j = 0; j < MatchCount; j++, k++)
+      {
+        REAL(ret)[k] = I[j];
+      }
+    for( j = 0; j < MatchCount; j++, k++)
+      {
+        REAL(ret)[k] = IM[j];
+      }
+    for( j = 0; j < MatchCount; j++, k++)
+      {
+        REAL(ret)[k] = W[j];
+      }
+    UNPROTECT(1);
+
+    return(ret);    
+  } //end of FasterMatchC
+
+
+/*---------------------------------------------------------------------------
+   Function : FastMatchC
+
+   In       : I_N: the number of observations
+
+              I_xvars: the number of columns in the 'X' matrix---i.e.,
+                       the number of variables to match on.
+
+              I_All: what we are estimating---i.e.,the 'estmand' argument to GenMatch()
+
+              I_M: 1-to-M matching---i.e., this is the 'M' option to GenMatch()
+
+	       I_cdd: Distance tolerance
+
+              I_ww: Weight.matrix, GenMatch assumes that it is diagonal
+
+              I_Tr: the treatment indicator--i.e., the 'Tr' argument to GenMatch()
+
+              I_X: The matrix containing the variable we are going to
+              match on, the 'X' option to GenMatch().
+
+              I_weight: the observation specific weights---i.e, the 'weight' argument 
+                        to GenMatch()
+
+
+   OUT: A matrix of number of matches rows and 3 columns. The first
+   column contains the treatment observations being matched, the
+   second the control observations and the third the weights (adjusted
+   for ties).
+
+   JOB: For GenMatch(), when there are observation specific weights,
+   but we are matching with replacement, keeping ties and are using no
+   caliper, no exact matching and no restriction matrix.  Also note
+   that GenMatch() assumes that the Weight.matrix is a diagonal
+   matrix.  This function cannot be used with Match(), because it does
+   not reorder the indexes at the end so to be usable to actually
+   estimate causal effects.  This makes the function faster than its
+   equivalent which is called from Match(), 'MatchLoopC'.
+
+ ---------------------------------------------------------------------------*/
+
+
+  SEXP FastMatchC(SEXP I_N, SEXP I_xvars, SEXP I_All, SEXP I_M, SEXP I_cdd,
+                  SEXP I_ww, SEXP I_Tr, SEXP I_X, SEXP I_weight)
+  {
+    SEXP ret;
+    
+    long N, xvars, All, M; 
+    double cdd, dfoo;
+    
+    long i, j, k;
+    
+    N = asInteger(I_N);
+    xvars = asInteger(I_xvars);
+    All = asInteger(I_All);
+    M = asInteger(I_M);
+    cdd = asReal(I_cdd);
+    
+    Matrix ww = Matrix(xvars, xvars);
+
+    Matrix Tr = Matrix(N, 1);
+    Matrix X = Matrix(N, xvars);
+    Matrix weight = Matrix(N, 1);
+    
+    k=0;
+    //rows and colums are fliped!! j,i != i,j
+    for(j=0;j<xvars; j++)
+    {
+      for(i=0;i<xvars; i++)
+      {
+        //ww(i,j) = REAL(I_ww)[k];
+        ww[M(i,j,xvars)] = REAL(I_ww)[k];
+        k++;
+      }
+    }
+    
+    for(i=0;i<N; i++)
+    {
+      Tr[i] = REAL(I_Tr)[i];
+    }
+    
+    //rows and colums are fliped!! j,i != i,j
+    k=0;
+    for(j=0;j<xvars; j++)
+    {
+      for(i=0;i<N; i++)
+      {
+        //X(i,j) = REAL(I_X)[k];
+        X[M(i,j,xvars)] = REAL(I_X)[k];
+        k++;
+      }
+    }
+    
+    for(i=0;i<N; i++)
+    {
+      weight[i] = REAL(I_weight)[i];
+    }
+    
+    Matrix INN = Matrix::seqa(1, 1, N);
+    // TT is just equal to INN
+
+    Matrix ZX(N, xvars), Dist(N, 1);
+
+    Matrix foo1;
+    Matrix foo2;
+
+    /* set misc */
+    int TREATi = 0, ACTMATsum = 0;
+    
+    Matrix DistPot, weightPot, tt,
+      weightPot_sort, weightPot_sum, Wi, I, IM, W;
+    Matrix ACTMAT, POTMAT;
+    
+    //These are larger than needed; it is just easier this way
+    int *order_DistPot = (int *) malloc(N*sizeof(int));  
+    double *S = (double *) malloc(N*sizeof(double));  
+    
+    int first=1;
+    for(i=0; i < N; i++)
+    {
+      // treatment indicator for observation to be matched        
+      TREATi = (int) Tr[i];
+      
+      // proceed with all observations if All==1
+      // but only with treated observations if All=0        
+      if ( (TREATi==1 & All!=1) | (All==1) )
+      {
+#ifdef __GenMatchBLAS__
+        // this loop is equivalent to the matrix X less the matrix A, which is
+        // the product of N rows by 1 column of 1.0 and row R of X.
+	// I.E.,         xx = X(i,_); DX = (X - (index_onesN * xx)) 
+        double *dest = ZX.data;
+        double *src  = X.data;
+        double *row  = X.data + (i * xvars);
+        for (int jj = 0; jj < N; ++jj) {
+          for (int kk = 0; kk < xvars; ++kk, ++dest, ++src) {
+            *dest = *src - row[kk];
+          }
+        }
+
+	//JSS, dgemm is slower and I assume that dtrmm and dsymm are also
+	//http://docs.sun.com/source/819-3691/dscal.html
+	for (int kk=0; kk < xvars; kk++)
+	  {
+	    cblas_dscal(N, ww.data[M(kk,kk,xvars)], ZX.data+kk, xvars);
+	  }
+
+	ZX.multi_scalar(ZX);
+
+	//http://docs.sun.com/source/819-3691/dasum.html 
+	for (int jj=0; jj < N; jj++)
+	  {
+	    Dist.data[jj] = cblas_dasum(xvars, ZX.data+M(jj, 0, xvars), 1);
+	  }
+#else
+	// Don't calculate Distance for observations with of the same treatment assignment
+	// Original No BLAS version from Matching 197, this version from 4.4-52
+        for (int jj = 0; jj < N; jj++) {
+	  if( abs(TREATi-Tr[jj]) > TOL )
+	    {
+	      Dist.data[jj] = 0.0;
+	      for (int kk=0; kk < xvars; kk++)
+		{
+		  ZX.data[M(jj,kk,xvars)] = X.data[M(jj,kk,xvars)] - X.data[M(i,kk,xvars)];
+		  dfoo  = ZX.data[M(jj,kk,xvars)] * ww.data[M(kk,kk,xvars)];
+		  Dist.data[jj] += dfoo*dfoo;
+		}
+	    } // if TR
+	} //end of jj loop
+#endif /* end __GenMatchBLAS__ */
+        
+        // Dist distance to observation to be matched
+        // is N by 1 vector	    
+        
+        // set of potential matches (all observations with other treatment)
+        // JSS, note:logical vector
+        POTMAT = EqualityTestScalar(Tr, 1-TREATi);
+        
+        // X's for potential matches
+        DistPot = selif(Dist, POTMAT);
+        weightPot = selif(weight, POTMAT);
+        
+        long weightPot_size = size(weightPot);
+        
+        for(j=0; j< weightPot_size; j++)
+	  {
+	    // assume that weightPot_size = size(DistPot)
+	    order_DistPot[j] = j;
+	    S[j] = (double) DistPot[j];
+	  }
+        
+        rsort_with_index (S, order_DistPot, weightPot_size);
+        
+        weightPot_sort = Matrix(weightPot_size, 1);
+        for(j=0; j < weightPot_size; j++)
+	  {
+	    weightPot_sort[j] = weightPot[order_DistPot[j]];
+	  }
+        weightPot_sum = cumsum(weightPot_sort);
+        
+        tt = Matrix::seqa(1, 1, rows(weightPot_sum));
+        
+        foo1 = GreaterEqualTestScalar(weightPot_sum, M);
+        foo2 = selif(tt, foo1);
+        
+        long MMM = (long) min(foo2) - 1;
+        
+        // distance at last match
+        double Distmax = S[MMM];
+        
+        // selection of actual matches 
+        // logical index
+        ACTMAT = LessEqualTestScalar(Dist,  (Distmax+cdd));
+        ACTMAT = VectorAnd(POTMAT, ACTMAT);
+        
+        // distance to actual matches.  This is NEVER used.
+        // ACTDIST = selif(Dist, ACTMAT);
+        
+        // counts how many times each observation is matched.
+        double Mi = sum(multi_scalar(weight, ACTMAT));
+        
+	//previously in a __NBLAS__ wrapper, but it should always be used
+        foo1 = weight;
+        foo1.multi_scalar(weight);
+        foo1.multi_scalar(ACTMAT);
+	
+        Wi = selif(weight, ACTMAT);
+        Wi = weight[i]*Wi/Mi;
+        
+        ACTMATsum = (int) sumc(ACTMAT)[0];
+        
+        // collect results
+        if (first==1)
+	  {
+	    I = Matrix::ones(ACTMATsum, 1)*(i+1);
+	    IM = selif(INN, ACTMAT);
+	    W = Wi;
+	    first = 0;
+	  }// end of first==1 
+        else 
+	  {
+	    I = rbind(I, Matrix::ones(ACTMATsum, 1)*(i+1));
+	    IM = rbind(IM, selif(INN, ACTMAT));
+	    W = rbind(W, Wi);
+	  } // end of i else
+        
+      } // end of (TREATi==1 & All!=1) | (All==1) )
+    } //END OF i MASTER LOOP!
+    
+    /*ATT is okay already */
+    /* ATE*/
+    if(All==1)
+    {
+      long tl  = rows(I);
+      Matrix I2  = Matrix::zeros(tl, 1);
+      Matrix IM2 = Matrix::zeros(tl, 1);
+      Matrix trt = Matrix::zeros(tl, 1);
+      
+      for(i=0; i<tl; i++)
+      {
+        k =(int) I[i] -1 ;
+        trt[i] = Tr[k];
+      }
+      
+      for (i=0; i<tl; i++)
+      {
+        if (trt[i]==1)
+	      {
+          I2[i] = I[i];
+          IM2[i] = IM[i];
+	      } 
+        else
+	      {
+          I2[i] = IM[i];
+          IM2[i] = I[i];		
+	      }
+      }
+      
+      I = I2;
+      IM = IM2;
+    } 
+    else if(All==2)     /* ATC */
+    {
+      Matrix Itmp = I;
+      Matrix IMtmp = IM;
+      
+      I = IMtmp;
+      IM = Itmp;
+    }
+    
+    /* Free Memory */
+    free(S);
+    free(order_DistPot);
+
+    i = I.rowsize;
+    PROTECT(ret=allocMatrix(REALSXP, i, 3));
+    /* Loop through the data and display the same in matrix format */
+    k = 0;
+    for( j = 0; j < i; j++, k++)
+      {
+        REAL(ret)[k] = I[j];
+      }
+    for( j = 0; j < i; j++, k++)
+      {
+        REAL(ret)[k] = IM[j];
+      }
+    for( j = 0; j < i; j++, k++)
+      {
+        REAL(ret)[k] = W[j];
+      }
+    UNPROTECT(1);
+
+    return(ret);    
+  } //end of FastMatchC
+
+
+/*---------------------------------------------------------------------------
+   Function : MatchLoopC
+
+   In       : I_N: the number of observations
+
+              I_xvars: the number of columns in the 'X' matrix---i.e.,
+                       the number of variables to match on.
+
+              I_All: what we are estimating---i.e.,the 'estmand' argument to GenMatch()
+
+              I_M: 1-to-M matching---i.e., this is the 'M' option to GenMatch()
+
+	       I_cdd: Distance tolerance
+
+	       I_caliper: indicator for if we are using a caliper
+
+	       I_replace: indicator for if we doing matching with replacement?
+
+	       I_ties: indicator for if are we ignoring ties?
+
+              I_ww: Weight.matrix, GenMatch assumes that it is diagonal
+
+              I_Tr: the treatment indicator--i.e., the 'Tr' argument to GenMatch()
+
+              I_X: The matrix containing the variable we are going to
+              match on, the 'X' option to GenMatch().
+
+              I_weight: the observation specific weights---i.e, the 'weight' argument 
+                        to GenMatch()
+
+	       I_CaliperVec: A vector which contains the caliper which we must fit in
+            
+              I_Xorig: The X matrix unscaled (we need this to make caliper comparisons)
+
+              I_restrict_trigger: an indicator for if we are using the restriction matrix
+
+              I_restrict_nrow: the number of restriction we have
+
+              I_restrict: the actual restriction matrix
+
+              I_DaigWeightMatrixFlag: is our I_ww matrix diagonal?
+
+
+   OUT: A matrix of number of matches rows and 5 columns. The first
+   column contains the treatment observations being matched, the
+   second the control observations and the third the weights (adjusted
+   for ties).
+
+   JOB: This is the most featured matching function.  It is called by
+   Match() when we have observational specific weights, and by
+   GenMatch() when there are observational specific weights and one or
+   more of no replacement, no ties, exact matching, caliper matching
+   or use of the restriction matrix.
+
+ ---------------------------------------------------------------------------*/
+  
+  SEXP MatchLoopC(SEXP I_N, SEXP I_xvars, SEXP I_All, SEXP I_M, SEXP I_cdd,
+                  SEXP I_caliper, SEXP I_replace, SEXP I_ties,
+                  SEXP I_ww, SEXP I_Tr, SEXP I_X, SEXP I_weight,
+                  SEXP I_CaliperVec, SEXP I_Xorig,
+                  SEXP I_restrict_trigger, SEXP I_restrict_nrow, SEXP I_restrict,
+		  SEXP I_DiagWeightMatrixFlag)
+  {
+    SEXP ret;
+    
+    long N, xvars, All, M, caliper, replace, ties, restrict_trigger, restrict_nrow, DiagWeightMatrixFlag,
+      sum_caliper_drops=0, replace_count=0;
+    double cdd, diff, dfoo;
+    
+    long i, j, k, r, c;
+    
+    N = asInteger(I_N);
+    xvars = asInteger(I_xvars);
+    All = asInteger(I_All);
+    M = asInteger(I_M);
+    cdd = asReal(I_cdd);
+    caliper = (long) asReal(I_caliper);
+    replace = asInteger(I_replace);
+    ties = asInteger(I_ties);
+    restrict_nrow = asInteger(I_restrict_nrow);
+    restrict_trigger = asInteger(I_restrict_trigger);
+    DiagWeightMatrixFlag = asInteger(I_DiagWeightMatrixFlag);
+    
+    Matrix ww = Matrix(xvars, xvars);
+    Matrix Tr = Matrix(N, 1);
+    Matrix X = Matrix(N, xvars);
+    Matrix weight = Matrix(N, 1);
+    
+    k=0;
+    //rows and colums are fliped!! j,i != i,j
+    for(j=0;j<xvars; j++)
+      {
+	for(i=0;i<xvars; i++)
+	  {
+	    //ww(i,j) = REAL(I_ww)[k];
+	    ww[M(i,j,xvars)] = REAL(I_ww)[k];
+	    k++;
+	  }
+      }
+    
+    for(i=0;i<N; i++)
+      {
+	Tr[i] = REAL(I_Tr)[i];
+      }
+    
+    //rows and colums are fliped!! j,i != i,j
+    k=0;
+    for(j=0;j<xvars; j++)
+      {
+	for(i=0;i<N; i++)
+	  {
+	    //X(i,j) = REAL(I_X)[k];
+	    X[M(i,j,xvars)] = REAL(I_X)[k];
+	    k++;
+	  }
+      }
+    
+    for(i=0;i<N; i++)
+      {
+	weight[i] = REAL(I_weight)[i];
+      }
+    
+    Matrix IMi;
+    Matrix Xorig;
+    Matrix CaliperVec;
+    if(caliper==1)
+    {
+      Xorig = Matrix(N, xvars);
+      CaliperVec = Matrix(xvars, 1);
+      
+      for (i=0; i<xvars; i++)
+      {
+        CaliperVec[i] = REAL(I_CaliperVec)[i];
+      }
+      
+      //rows and colums are fliped!! j,i != i,j
+      k=0;
+      for(j=0;j<xvars; j++)
+      {
+        for(i=0;i<N; i++)
+	      {
+          //X(i,j) = REAL(I_X)[k];
+          Xorig[M(i,j,xvars)] = REAL(I_Xorig)[k];
+          k++;
+	      }
+      }	
+    } // end of caliper==1
+    
+    Matrix restrict; 
+    if (restrict_trigger==1)
+    {
+      restrict = Matrix(restrict_nrow, 3);
+      
+      k=0;
+      for(j=0;j<3; j++)
+      {
+        for(i=0;i<restrict_nrow; i++)
+	      {
+		restrict[M(i,j,3)] = REAL(I_restrict)[k];
+		k++;
+	      }
+      }	
+    } /* if (restrict_trigger==1) */
+
+    // required for replace=0, to keep track of obs already used
+    long *ReplaceVector;
+    if(replace==0)
+      {
+	ReplaceVector = (long *) malloc(N*sizeof(long));
+      }
+
+    //Start random number generator if we are breaking ties
+    if (ties==0)
+      GetRNGstate();
+
+    Matrix INN = Matrix::seqa(1, 1, N);
+    // TT is just equal to INN
+
+#ifdef __NBLAS__
+    Matrix DX, ZX(N, xvars), Dist(N, 1);
+    if (DiagWeightMatrixFlag!=1) {
+      /* ctor zeros data so this does not add any computational time and maintains the dims outside 
+	 the scope of this if statement */
+      DX = Matrix::zeros(N, xvars);
+    }
+#else
+    Matrix index_onesN = Matrix::ones(N, 1);
+    Matrix xx;
+    Matrix DX;
+#endif
+
+    Matrix Kcount  = Matrix::zeros(N,1);
+    Matrix KKcount = Matrix::zeros(N,1);
+    Matrix foo1;
+    Matrix foo2;
+
+    /* set misc */
+    int TREATi = 0, ACTMATsum = 0;
+
+    Matrix DistPot, weightPot, tt, 
+      weightPot_sort, weightPot_sum, Wi, I, IM, IMt, W;
+    Matrix ACTMAT, POTMAT(N, 1);
+
+    //These are larger than needed; it is just easier this way
+    int *order_DistPot = (int *) malloc(N*sizeof(int));  
+    double *S = (double *) malloc(N*sizeof(double));  
+
+    int first=1;
+    for(i=0; i < N; i++)
+      {
+	// treatment indicator for observation to be matched        
+	TREATi = (int) Tr[i];
+	
+	// proceed with all observations if All==1
+	// but only with treated observations if All=0        
+	if ( (TREATi==1 & All!=1) | (All==1) )
+	  {
+#ifdef __NBLAS__
+	    if (DiagWeightMatrixFlag!=1)
+	      {
+		// this loop is equivalent to the matrix X less the matrix A, which is
+		// the product of N rows by 1 column of 1.0 and row R of X.
+		double *dest = ZX.data;
+		double *src  = X.data;
+		double *row  = X.data + (i * xvars);
+		for (int jj = 0; jj < N; ++jj) {
+		  for (int kk = 0; kk < xvars; ++kk, ++dest, ++src) {
+		    *dest = *src - row[kk];
+		  }
+		}
+
+		/* note that xvars must be > 1 */
+		//JSS
+		// do the second multiplication with dgemm, multiplying the matrix
+		// above, D, by the transpose of matrix W.
+		cblas_dgemm(CblasRowMajor,// column major
+			    CblasNoTrans, // A not transposed
+			    CblasTrans,   // B transposed
+			    xvars,        // M
+			    N,            // N
+			    xvars,        // K
+			    1.0,          // alpha, (alpha * A * B)
+			    ww.data,      // A
+			    xvars,        // leading dimension for A
+			    ZX.data,      // B
+			    xvars,        // leading dimension for B
+			    0.0,          // beta, (beta * C)
+			    DX.data,      // C
+			    N);           // leading dimension for C
+		
+		DX.multi_scalar(DX);
+		
+		std::swap(DX.colsize, DX.rowsize);
+		    
+		Dist = sumc(DX);
+		
+		std::swap(Dist.colsize, Dist.rowsize); // transpose 1 x N -> N x 1
+		std::swap(DX.colsize, DX.rowsize);
+	      } else 
+	      {
+#ifdef __GenMatchBLAS__
+		// this loop is equivalent to the matrix X less the matrix A, which is
+		// the product of N rows by 1 column of 1.0 and row R of X.
+		double *dest = ZX.data;
+		double *src  = X.data;
+		double *row  = X.data + (i * xvars);
+		for (int jj = 0; jj < N; ++jj) {
+		  for (int kk = 0; kk < xvars; ++kk, ++dest, ++src) {
+		    *dest = *src - row[kk];
+		  }
+		}
+
+		//http://docs.sun.com/source/819-3691/dscal.html
+		for (int kk=0; kk < xvars; kk++)
+		  {
+		    cblas_dscal(N, ww.data[M(kk,kk,xvars)], ZX.data+kk, xvars);
+		  }
+		
+		ZX.multi_scalar(ZX);
+		
+		//http://docs.sun.com/source/819-3691/dasum.html 
+		for (int jj=0; jj < N; jj++)
+		  {
+		    Dist.data[jj] = cblas_dasum(xvars, ZX.data+M(jj, 0, xvars), 1);
+		  }
+#else
+		// Don't calculate Distance for observations with of the same treatment assignment
+		// Original No BLAS version from Matching 197, this version from 4.4-52
+		for (int jj = 0; jj < N; jj++) {
+		  if( abs(TREATi-Tr[jj]) > TOL )
+		    {
+		      Dist.data[jj] = 0.0;
+		      for (int kk=0; kk < xvars; kk++)
+			{
+			  ZX.data[M(jj,kk,xvars)] = X.data[M(jj,kk,xvars)] - X.data[M(i,kk,xvars)];
+			  dfoo  = ZX.data[M(jj,kk,xvars)] * ww.data[M(kk,kk,xvars)];
+			  Dist.data[jj] += dfoo*dfoo;
+			}
+		    } // if TR
+		} //end of jj loop
+#endif /* end of __GenMatchBLAS__ ifdef */
+	      } /* end of if (DiagWeightMatrixFlag!=1) */
+#else
+	    // covariate value for observation to be matched                        
+	    xx = X(i,_);
+	    
+	    
+	    DX = (X - (index_onesN * xx)) * t(ww);
+	    
+	    if (xvars>1)
+	      {
+		//JSS
+		foo1 = t(multi_scalar(DX, DX));
+		Dist = t(sumc(foo1));
+		
+	      } 
+	    else 
+	      {
+		Dist = multi_scalar(DX, DX);
+	      } // end of xvars
+#endif /* end __NBLAS__ */
+	    
+	    // Dist distance to observation to be matched
+	    // is N by 1 vector	    
+	    
+	    if (restrict_trigger==1)
+	      {
+		for(j=0; j<restrict_nrow; j++)
+		  {
+		    if ( ((long) restrict[M(j,0,3)])-1 ==i )
+		      {
+			
+			if (restrict[M(j,2,3)] < 0) {
+			  Dist[ ((long) restrict[M(j,1,3)])-1 ] = DOUBLE_XMAX;
+			}
+			else {
+			  Dist[ ((long) restrict[M(j,1,3)])-1 ] = restrict[M(j,2,3)];
+			}
+		      }
+		    else if ( ((long) restrict[M(j,1,3)])-1 ==i ) 
+		      {
+			
+			if (restrict[M(j,2,3)] < 0) {
+			  Dist[ ((long) restrict[M(j,0,3)])-1 ] = DOUBLE_XMAX;
+			}
+			else {
+			  Dist[ ((long) restrict[M(j,0,3)])-1 ] = restrict[M(j,2,3)];
+			}
+		      }
+		  }
+	      } /* if (restrict_trigger==1) */
+
+	    // Don't match observations we have already matched
+	    if(replace_count > 0)
+	      {
+		for(j=0; j<replace_count; j++)
+		  {
+		    Dist[ ( ReplaceVector[j] - 1) ] = DOUBLE_XMAX;
+		  }
+	      } // end of replace_count
+
+            // set of potential matches (all observations with other treatment)
+            // JSS, note:logical vector
+	    POTMAT = EqualityTestScalar(Tr, 1-TREATi);
+	    
+	    if (caliper==1)
+	      {
+		for (j=0; j<N; j++)
+		  {
+		    if((int) POTMAT[j]==1)
+		      {
+			for (k=0; k<xvars; k++)
+			  {
+			    diff = abs(Xorig[M(i, k, xvars)] - Xorig[M(j,k,xvars)]); 
+			    if (diff > CaliperVec[k])
+			      {
+				Dist[j] = DOUBLE_XMAX;
+				break;
+			      }
+			  }
+		      }
+		  } 
+	      }//end of if caliper
+	    
+            // X's for potential matches
+            DistPot = selif(Dist, POTMAT);
+            weightPot = selif(weight, POTMAT);
+
+	    long weightPot_size = size(weightPot);
+
+	    for(j=0; j< weightPot_size; j++)
+	      {
+		// assume that weightPot_size = size(DistPot)
+		order_DistPot[j] = j;
+		S[j] = (double) DistPot[j];
+	      }
+	    
+	    rsort_with_index (S, order_DistPot, weightPot_size);
+	    
+	    weightPot_sort = Matrix(weightPot_size, 1);
+	    for(j=0; j < weightPot_size; j++)
+	      {
+		weightPot_sort[j] = weightPot[order_DistPot[j]];
+	      }
+            weightPot_sum = cumsum(weightPot_sort);
+	    
+	    tt = Matrix::seqa(1, 1, rows(weightPot_sum));
+	    
+	    foo1 = GreaterEqualTestScalar(weightPot_sum, M);
+	    foo2 = selif(tt, foo1);
+	    
+	    long MMM = (long) min(foo2) - 1;
+
+	    // distance at last match
+            double Distmax = S[MMM];
+
+	    if (restrict_trigger==1 | caliper==1)
+	      {
+		if ( (Distmax+cdd) > DOUBLE_XMAX_CHECK)
+		  {
+		    sum_caliper_drops++;
+		    continue;
+		  }
+	      } 
+
+            // selection of actual matches 
+            // logical index
+	    ACTMAT = LessEqualTestScalar(Dist,  (Distmax+cdd));
+	    ACTMAT = VectorAnd(POTMAT, ACTMAT);
+
+	    if (ties==0)
+	      {
+		int Mii = (int) sum(ACTMAT);
+		//Do we have ties?
+		if (Mii > M)
+		  {
+		    IMt = selif(INN, ACTMAT);
+		    int nties_broken = 0;
+		    int ntiesToBreak = Mii - M;
+		    while (nties_broken < ntiesToBreak) {
+		      int idrop = (int) ( unif_rand()*(double) Mii);
+		      k = (int) IMt[idrop];
+		      if (k > (-1+TOL) )
+			{
+			  ACTMAT[k - 1] = 0;
+			  IMt[idrop] = -1;
+			  nties_broken++;
+			} // end if
+		    }// end of while loop
+		  }
+	      }// end of ties loop	    
+	    
+	    // distance to actual matches.  This is NEVER used.
+	    // ACTDIST = selif(Dist, ACTMAT);
+	    
+            // counts how many times each observation is matched.
+	    double Mi = sum(multi_scalar(weight, ACTMAT));
+	    
+            Kcount = Kcount + 
+	      weight[i] * multi_scalar(weight, ACTMAT)/Mi;
+	    
+	    //previously in a __NBLAS__ wrapper, but it should always be used
+	    foo1 = weight;
+	    foo1.multi_scalar(weight);
+	    foo1.multi_scalar(ACTMAT);
+	    
+	    KKcount = KKcount + (weight[i]* foo1)/(Mi*Mi);
+	    
+            Wi = selif(weight, ACTMAT);
+	    Wi = weight[i]*Wi/Mi;
+	    
+	    ACTMATsum = (int) sumc(ACTMAT)[0];
+
+	    //if no replacement
+	    if(replace==0)
+	      {
+		IMt = selif(INN, ACTMAT);
+		for (j=0; j<IMt.rowsize; j++)
+		  {
+		    ReplaceVector[replace_count] = (long) IMt.data[j];
+		    replace_count++;
+		  }
+	      }//end of replace==0
+
+	    // collect results
+	    if (first==1)
+	      {
+		I = Matrix::ones(ACTMATsum, 1)*(i+1);
+		if(replace==0)
+		  {
+		    IM = IMt;
+		  } 
+		else 
+		  {
+		    IM = selif(INN, ACTMAT);
+		  }
+		W = Wi;
+		first = 0;
+	      }// end of first==1 
+	    else 
+	      {
+		I = rbind(I, Matrix::ones(ACTMATsum, 1)*(i+1));
+		if(replace==0)
+		  {
+		    IM = rbind(IM, IMt);
+		  } 
+		else
+		  {
+		    IM = rbind(IM, selif(INN, ACTMAT));
+		  }
+		W = rbind(W, Wi);
+	      } // end of i else
+	    
+	  } // end of (TREATi==1 & All!=1) | (All==1) )
+      } //END OF i MASTER LOOP!
+
+    //Stop random number generator if we are breaking ties
+    if (ties==0)
+      PutRNGstate();
+    
+    Matrix rr = cbind(I, IM);
+    rr = cbind(rr, W);
+    
+    long tl  = rows(I);
+    /*ATT is okay already */
+    /* ATE*/
+    if((All==1) & (I[0]!=0))
+      {
+	Matrix I2  = Matrix::zeros(tl, 1);
+	Matrix IM2 = Matrix::zeros(tl, 1);
+	Matrix trt = Matrix::zeros(tl, 1);
+	
+	for(i=0; i<tl; i++)
+	  {
+	    k =(int) I[i] -1 ;
+	    trt[i] = Tr[k];
+	  }
+	
+	for (i=0; i<tl; i++)
+	  {
+	    if (trt[i]==1)
+	      {
+		I2[i] = I[i];
+		IM2[i] = IM[i];
+	      } 
+	    else
+	      {
+		I2[i] = IM[i];
+		IM2[i] = I[i];		
+	      }
+	  }
+	
+	I = I2;
+	IM = IM2;
+      } 
+    else if(All==2)     /* ATC */
+      {
+	Matrix Itmp = I;
+	Matrix IMtmp = IM;
+	
+	I = IMtmp;
+	IM = Itmp;
+      }
+    
+    rr = cbind(rr, I);
+    rr = cbind(rr, IM);
+    
+    if (caliper==1)
+      {
+	Matrix scalar_returns = Matrix::zeros(tl, 1);
+	scalar_returns[0] = sum_caliper_drops;
+	rr = cbind(rr, scalar_returns);
+      }
+    
+    // rr key
+    // 1] I (unadjusted); 2] IM (unadjusted); 3] weight; 4] I (adjusted); 5] IM (adjusted);
+    // scalar returns [0]: caliper drops
+    
+    /* Free Memory */
+    free(S);
+    free(order_DistPot);
+    if(replace==0)
+      {
+	free(ReplaceVector);
+      }
+    
+    r = rows(rr);
+    c = cols(rr);
+    
+    PROTECT(ret=allocMatrix(REALSXP, r, c));
+    /* Loop through the data and display the same in matrix format */
+    k = 0;
+    for( i = 0; i < c; i++ )
+      {
+	for( j = 0; j < r; j++ )
+	  {
+	    // REAL(ret)[k] = rr(j,i);
+	    // REAL(ret)[k] = rr[j*c+i];
+	    /* Use Macro to Index */
+	    REAL(ret)[k] = rr[M(j, i, c)];
+	    k++;
+	  }
+      }
+    UNPROTECT(1);
+    return(ret);    
+  } //end of MatchLoopC
+
+
+/*---------------------------------------------------------------------------
+   Function : MatchLoopCfast
+
+   In       : I_N: the number of observations
+
+              I_xvars: the number of columns in the 'X' matrix---i.e.,
+                       the number of variables to match on.
+
+              I_All: what we are estimating---i.e.,the 'estmand' argument to GenMatch()
+
+              I_M: 1-to-M matching---i.e., this is the 'M' option to GenMatch()
+
+	       I_cdd: Distance tolerance
+
+	       I_caliper: indicator for if we are using a caliper
+
+	       I_replace: indicator for if we doing matching with replacement?
+
+	       I_ties: indicator for if are we ignoring ties?
+
+              I_ww: Weight.matrix, GenMatch assumes that it is diagonal
+
+              I_Tr: the treatment indicator--i.e., the 'Tr' argument to GenMatch()
+
+              I_X: The matrix containing the variable we are going to
+              match on, the 'X' option to GenMatch().
+
+              I_weight: the observation specific weights---i.e, the 'weight' argument 
+                        to GenMatch()
+
+	       I_CaliperVec: A vector which contains the caliper which we must fit in
+            
+              I_Xorig: The X matrix unscaled (we need this to make caliper comparisons)
+
+              I_restrict_trigger: an indicator for if we are using the restriction matrix
+
+              I_restrict_nrow: the number of restriction we have
+
+              I_restrict: the actual restriction matrix
+
+              I_DaigWeightMatrixFlag: is our I_ww matrix diagonal?
+
+
+   OUT: A matrix of number of matches rows and 5 columns. The first
+   column contains the treatment observations being matched, the
+   second the control observations and the third the weights (adjusted
+   for ties).
+
+   JOB: This function is called by Match() when there are no
+   observation specific weights, and by GenMatch() when there are no
+   observational specific weights but one or more of no replacement,
+   no ties, exact matching, caliper matching or use of the restriction
+   matrix.
+
+ ---------------------------------------------------------------------------*/
+
+  SEXP MatchLoopCfast(SEXP I_N, SEXP I_xvars, SEXP I_All, SEXP I_M, SEXP I_cdd,
+		      SEXP I_caliper, SEXP I_replace, SEXP I_ties,
+		      SEXP I_ww, SEXP I_Tr, SEXP I_X, 
+		      SEXP I_CaliperVec, SEXP I_Xorig,
+		      SEXP I_restrict_trigger, SEXP I_restrict_nrow, SEXP I_restrict,
+		      SEXP I_DiagWeightMatrixFlag)
+  {
+    SEXP ret;
+    
+    long N, xvars, All, M, caliper, replace, ties, restrict_trigger, restrict_nrow, DiagWeightMatrixFlag,
+      sum_caliper_drops=0, replace_count=0;
+    double cdd, diff, Distmax, Wi_ratio, dfoo;
+    
+    long i, j, k, r, c;
+    
+    N = asInteger(I_N);
+    xvars = asInteger(I_xvars);
+    All = asInteger(I_All);
+    M = asInteger(I_M);
+    cdd = asReal(I_cdd);
+    caliper = (long) asReal(I_caliper);
+    replace = asInteger(I_replace);
+    ties = asInteger(I_ties);
+    restrict_nrow = asInteger(I_restrict_nrow);
+    restrict_trigger = asInteger(I_restrict_trigger);
+    DiagWeightMatrixFlag = asInteger(I_DiagWeightMatrixFlag);
+    
+    Matrix ww = Matrix(xvars, xvars);
+    Matrix Tr = Matrix(N, 1);
+    Matrix X = Matrix(N, xvars);
+    
+    k=0;
+    //rows and colums are fliped!! j,i != i,j
+    for(j=0;j<xvars; j++)
+      {
+	for(i=0;i<xvars; i++)
+	  {
+	    //ww(i,j) = REAL(I_ww)[k];
+	    ww[M(i,j,xvars)] = REAL(I_ww)[k];
+	    k++;
+	  }
+      }
+    
+    for(i=0;i<N; i++)
+      {
+	Tr[i] = REAL(I_Tr)[i];
+      }
+    
+    //rows and colums are fliped!! j,i != i,j
+    k=0;
+    for(j=0;j<xvars; j++)
+      {
+	for(i=0;i<N; i++)
+	  {
+	    //X(i,j) = REAL(I_X)[k];
+	    X[M(i,j,xvars)] = REAL(I_X)[k];
+	    k++;
+	  }
+      }
+    
+    Matrix IMi;
+    Matrix Xorig;
+    Matrix CaliperVec;
+    if(caliper==1)
+    {
+      Xorig = Matrix(N, xvars);
+      CaliperVec = Matrix(xvars, 1);
+      
+      for (i=0; i<xvars; i++)
+      {
+        CaliperVec[i] = REAL(I_CaliperVec)[i];
+      }
+      
+      //rows and colums are fliped!! j,i != i,j
+      k=0;
+      for(j=0;j<xvars; j++)
+      {
+        for(i=0;i<N; i++)
+	      {
+          //X(i,j) = REAL(I_X)[k];
+          Xorig[M(i,j,xvars)] = REAL(I_Xorig)[k];
+          k++;
+	      }
+      }	
+    } // end of caliper==1
+    
+    Matrix restrict; 
+    if (restrict_trigger==1)
+    {
+      restrict = Matrix(restrict_nrow, 3);
+      
+      k=0;
+      for(j=0;j<3; j++)
+      {
+        for(i=0;i<restrict_nrow; i++)
+	      {
+		restrict[M(i,j,3)] = REAL(I_restrict)[k];
+		k++;
+	      }
+      }	
+    } /* if (restrict_trigger==1) */
+
+    // required for replace=0, to keep track of obs already used
+    long *ReplaceVector;
+    if(replace==0)
+      {
+	ReplaceVector = (long *) malloc(N*sizeof(long));
+      }
+
+    //Start random number generator if we are breaking ties
+    if (ties==0)
+      GetRNGstate();
+
+    Matrix INN = Matrix::seqa(1, 1, N);
+    // TT is just equal to INN
+
+#ifdef __NBLAS__
+    Matrix DX, ZX(N, xvars), Dist(N, 1);
+    if (DiagWeightMatrixFlag!=1) {
+      /* ctor zeros data so this does not add any computational time and maintains the dims outside 
+	 the scope of this if statement */
+      DX = Matrix::zeros(N, xvars);
+    }
+#else
+    Matrix index_onesN = Matrix::ones(N, 1);
+    Matrix xx;
+    Matrix DX, Dist;
+
+    Matrix foo1;
+#endif
+
+    /* set misc */
+    int TREATi = 0;
+
+    Matrix IMt;
+    Matrix ACTMAT, POTMAT(N, 1);
+
+    // Temporary size for these matrices to avoid rbind
+    int NM = N*M*100;
+    if (ties==0)
+      NM = N*M;
+
+    Matrix I  = Matrix(NM,1);
+    Matrix IM = Matrix(NM,1);
+    Matrix W  = Matrix(NM,1);
+
+    //These are larger than needed; it is just easier this way
+    int *order_DistPot = (int *) malloc(N*sizeof(int));  
+    //double *S = (double *) malloc(N*sizeof(double));  
+    Matrix DistPot=Matrix(N, 1);
+
+    int MatchCount=0;
+    int MCindx=0;
+    int overFirstNM=1;
+
+    for(i=0; i < N; i++)
+      {
+	// treatment indicator for observation to be matched        
+	TREATi = (int) Tr[i];
+	
+	// proceed with all observations if All==1
+	// but only with treated observations if All=0        
+	if ( (TREATi==1 & All!=1) | (All==1) )
+	  {
+#ifdef __NBLAS__
+	    if (DiagWeightMatrixFlag!=1)
+	      {
+		// this loop is equivalent to the matrix X less the matrix A, which is
+		// the product of N rows by 1 column of 1.0 and row R of X.
+		double *dest = ZX.data;
+		double *src  = X.data;
+		double *row  = X.data + (i * xvars);
+		for (int jj = 0; jj < N; ++jj) {
+		  for (int kk = 0; kk < xvars; ++kk, ++dest, ++src) {
+		    *dest = *src - row[kk];
+		  }
+		}
+
+		/* note that xvars must be > 1 */
+		//JSS
+		// do the second multiplication with dgemm, multiplying the matrix
+		// above, D, by the transpose of matrix W.
+		cblas_dgemm(CblasRowMajor,// column major
+			    CblasNoTrans, // A not transposed
+			    CblasTrans,   // B transposed
+			    xvars,        // M
+			    N,            // N
+			    xvars,        // K
+			    1.0,          // alpha, (alpha * A * B)
+			    ww.data,      // A
+			    xvars,        // leading dimension for A
+			    ZX.data,      // B
+			    xvars,        // leading dimension for B
+			    0.0,          // beta, (beta * C)
+			    DX.data,      // C
+			    N);           // leading dimension for C
+		
+		DX.multi_scalar(DX);
+		
+		std::swap(DX.colsize, DX.rowsize);
+		    
+		Dist = sumc(DX);
+		
+		std::swap(Dist.colsize, Dist.rowsize); // transpose 1 x N -> N x 1
+		std::swap(DX.colsize, DX.rowsize);
+	      } else 
+	      {
+#ifdef __GenMatchBLAS__
+		// this loop is equivalent to the matrix X less the matrix A, which is
+		// the product of N rows by 1 column of 1.0 and row R of X.
+		double *dest = ZX.data;
+		double *src  = X.data;
+		double *row  = X.data + (i * xvars);
+		for (int jj = 0; jj < N; ++jj) {
+		  for (int kk = 0; kk < xvars; ++kk, ++dest, ++src) {
+		    *dest = *src - row[kk];
+		  }
+		}
+
+		//http://docs.sun.com/source/819-3691/dscal.html
+		for (int kk=0; kk < xvars; kk++)
+		  {
+		    cblas_dscal(N, ww.data[M(kk,kk,xvars)], ZX.data+kk, xvars);
+		  }
+		
+		ZX.multi_scalar(ZX);
+		
+		//http://docs.sun.com/source/819-3691/dasum.html 
+		for (int jj=0; jj < N; jj++)
+		  {
+		    Dist.data[jj] = cblas_dasum(xvars, ZX.data+M(jj, 0, xvars), 1);
+		  }
+#else
+		// Don't calculate Distance for observations with of the same treatment assignment
+		// Original No BLAS version from Matching 197, this version from 4.4-52
+		for (int jj = 0; jj < N; jj++) {
+		  if( abs(TREATi-Tr[jj]) > TOL )
+		    {
+		      Dist.data[jj] = 0.0;
+		      for (int kk=0; kk < xvars; kk++)
+			{
+			  ZX.data[M(jj,kk,xvars)] = X.data[M(jj,kk,xvars)] - X.data[M(i,kk,xvars)];
+			  dfoo  = ZX.data[M(jj,kk,xvars)] * ww.data[M(kk,kk,xvars)];
+			  Dist.data[jj] += dfoo*dfoo;
+			}
+		    } // if TR
+		} //end of jj loop
+#endif /* end of __GenMatchBLAS__ ifdef */
+	      } /* end of if (DiagWeightMatrixFlag!=1) */
+#else
+	    // covariate value for observation to be matched                        
+	    xx = X(i,_);
+	    
+	    
+	    DX = (X - (index_onesN * xx)) * t(ww);
+	    
+	    if (xvars>1)
+	      {
+		//JSS
+		foo1 = t(multi_scalar(DX, DX));
+		Dist = t(sumc(foo1));
+		
+	      } 
+	    else 
+	      {
+		Dist = multi_scalar(DX, DX);
+	      } // end of xvars
+#endif /* end __NBLAS__ */
+	    
+	    // Dist distance to observation to be matched
+	    // is N by 1 vector	    
+
+	    if (restrict_trigger==1)
+	      {
+		for(j=0; j<restrict_nrow; j++)
+		  {
+		    if ( ((long) restrict[M(j,0,3)])-1 ==i )
+		      {
+			
+			if (restrict[M(j,2,3)] < 0) {
+			  Dist[ ((long) restrict[M(j,1,3)])-1 ] = DOUBLE_XMAX;
+			}
+			else {
+			  Dist[ ((long) restrict[M(j,1,3)])-1 ] = restrict[M(j,2,3)];
+			}
+		      }
+		    else if ( ((long) restrict[M(j,1,3)])-1 ==i ) 
+		      {
+			
+			if (restrict[M(j,2,3)] < 0) {
+			  Dist[ ((long) restrict[M(j,0,3)])-1 ] = DOUBLE_XMAX;
+			}
+			else {
+			  Dist[ ((long) restrict[M(j,0,3)])-1 ] = restrict[M(j,2,3)];
+			}
+		      }
+		  }
+	      } /* if (restrict_trigger==1) */
+
+	    // Don't match observations we have already matched
+	    if(replace_count > 0)
+	      {
+		for(j=0; j<replace_count; j++)
+		  {
+		    Dist[ ( ReplaceVector[j] - 1) ] = DOUBLE_XMAX;
+		  }
+	      } // end of replace_count
+
+            // set of potential matches (all observations with other treatment)
+            // JSS, note:logical vector
+	    POTMAT = EqualityTestScalar(Tr, 1-TREATi);
+
+	    if (caliper==1)
+	      {
+		for (j=0; j<N; j++)
+		  {
+		    if((int) POTMAT[j]==1)
+		      {
+			for (k=0; k<xvars; k++)
+			  {
+			    diff = abs(Xorig[M(i, k, xvars)] - Xorig[M(j,k,xvars)]); 
+			    if (diff > CaliperVec[k])
+			      {
+				Dist[j] = DOUBLE_XMAX;
+				break;
+			      }
+			  }
+		      }
+		  } 
+	      }//end of if caliper
+
+            // X's for potential matches
+            DistPot = selif(Dist, POTMAT);
+	    //DistPot_size is a constant!! Fix it
+	    long DistPot_size = size(DistPot);
+
+	    //rsort_with_index(DistPot.data, order_DistPot, DistPot_size);
+	    //R_rsort(DistPot.data, DistPot_size);
+	    //rPsort(DistPot.data, DistPot_size, M);
+
+	    Distmax = kth_smallest(DistPot.data, DistPot_size, (M-1));
+
+	    if (restrict_trigger==1 | caliper==1)
+	      {
+		if ( (Distmax+cdd) > DOUBLE_XMAX_CHECK)
+		  {
+		    sum_caliper_drops++;
+		    continue;
+		  }
+	      } 
+
+            // selection of actual matches 
+            // logical index
+	    ACTMAT = LessEqualTestScalar(Dist,  (Distmax+cdd));
+	    ACTMAT = VectorAnd(POTMAT, ACTMAT);
+
+	    if (ties==0)
+	      {
+		int Mii = (int) sum(ACTMAT);
+		//Do we have ties?
+		if (Mii > M)
+		  {
+		    IMt = selif(INN, ACTMAT);
+		    int nties_broken = 0;
+		    int ntiesToBreak = Mii - M;
+		    while (nties_broken < ntiesToBreak) {
+		      int idrop = (int) ( unif_rand()*(double) Mii);
+		      k = (int) IMt[idrop];
+		      if (k > (-1+TOL) )
+			{
+			  ACTMAT[k - 1] = 0;
+			  IMt[idrop] = -1;
+			  nties_broken++;
+			} // end if
+		    }// end of while loop
+		  }
+	      }// end of ties loop	    
+	    
+	    // distance to actual matches.  This is NEVER used.
+	    // ACTDIST = selif(Dist, ACTMAT);
+	    
+            // counts how many times each observation is matched.
+	    double Mi = sum(ACTMAT);
+	    //ACTMATsum = (int) sumc(ACTMAT)[0];
+
+	    Wi_ratio = 1/Mi;
+	    //Wi = Matrix::ones(ACTMATsum, 1)*1/Mi;
+
+	    //if no replacement
+	    if(replace==0)
+	      {
+		IMt = selif(INN, ACTMAT);
+		for (j=0; j<IMt.rowsize; j++)
+		  {
+		    ReplaceVector[replace_count] = (long) IMt.data[j];
+		    replace_count++;
+		  }
+	      }//end of replace==0
+
+	    // collect results
+	    MatchCount = MatchCount + (int) Mi;
+
+	    if(MatchCount > NM)
+	      {
+		
+		NM = NM+N*M*100;
+
+		if(overFirstNM > 0)
+		  {
+		    Rprintf("Increasing memory because of ties: allocating a matrix of size 3 times %d doubles.\n", NM);
+		    Rprintf("I would be faster with the ties=FALSE option.\n");
+		    warning("Increasing memory because of ties.  I would be faster with the ties=FALSE option.");
+		  }
+		else 
+		  {
+		    Rprintf("Increasing memory because of ties: allocating a matrix of size 3 times %d doubles.", NM);
+		  }
+		
+		int OldMatchCount = MatchCount - (int) Mi;
+		
+		Matrix tI_tmp  = Matrix(NM,1);
+		Matrix tIM_tmp = Matrix(NM,1);
+		Matrix tW_tmp  = Matrix(NM,1);
+		
+		memcpy(tI_tmp.data, I.data, OldMatchCount*sizeof(double));
+		memcpy(tIM_tmp.data, IM.data, OldMatchCount*sizeof(double));
+		memcpy(tW_tmp.data, W.data, OldMatchCount*sizeof(double));
+		
+		I = tI_tmp;
+		IM = tIM_tmp;
+		W = tW_tmp;
+	      }
+
+	    for (j=0; j < (int) Mi; j++)
+	      {
+		I.data[MCindx+j] = i+1;
+		W.data[MCindx+j] = Wi_ratio;
+	      }
+	    
+	    if(replace==0)
+	      {
+		memcpy(IM.data+MCindx, IMt.data, IMt.size*sizeof(double));
+		MCindx = MCindx+IMt.size;
+	      }
+	    else
+	      {
+		k=0;
+		for (j=0; j<N; j++)
+		  {
+		    if(ACTMAT.data[j] > (1-TOL))
+		      {
+			IM.data[MCindx+k] = j+1;
+			k++;
+		      }
+		  }
+		MCindx = MCindx+k;
+	      }
+	  } // end of (TREATi==1 & All!=1) | (All==1) )
+      } //END OF i MASTER LOOP!
+
+    //Stop random number generator if we are breaking ties
+    if (ties==0)
+      PutRNGstate();
+
+    // subset matrices to get back to the right dims
+    long orig_rowsize = I.rowsize;
+    if (MatchCount > 0)
+      {
+	if (orig_rowsize != MatchCount)
+	  {
+	    I.rowsize = MatchCount;
+	    IM.rowsize = MatchCount;
+	    W.rowsize = MatchCount;
+	  }
+      }
+    else
+      {
+	I=Matrix(1, 1);
+	IM=Matrix(1, 1);
+	W=Matrix(1, 1);
+      }
+
+    Matrix rr = cbind(I, IM);
+    rr = cbind(rr, W);
+
+    long tl  = rows(I);
+
+    /*ATT is okay already */
+    /* ATE*/
+    if((All==1) & (I[0]!=0))
+      {
+	Matrix I2  = Matrix::zeros(tl, 1);
+	Matrix IM2 = Matrix::zeros(tl, 1);
+	Matrix trt = Matrix::zeros(tl, 1);
+
+	for(i=0; i<tl; i++)
+	  {
+	    k =(int) I[i] -1 ;
+	    trt[i] = Tr[k];
+	  }
+	for (i=0; i<tl; i++)
+	  {
+	    if (trt[i]==1)
+	      {
+		I2[i] = I[i];
+		IM2[i] = IM[i];
+	      } 
+	    else
+	      {
+		I2[i] = IM[i];
+		IM2[i] = I[i];		
+	      }
+	  }
+	I = I2;
+	IM = IM2;
+      } 
+    else if(All==2)     /* ATC */
+      {
+	Matrix Itmp = I;
+	Matrix IMtmp = IM;
+	
+	I = IMtmp;
+	IM = Itmp;
+      }
+
+    rr = cbind(rr, I);
+    rr = cbind(rr, IM);
+
+    if (caliper==1)
+      {
+	Matrix scalar_returns = Matrix::zeros(tl, 1);
+	scalar_returns[0] = sum_caliper_drops;
+	rr = cbind(rr, scalar_returns);
+      }
+    
+    // rr key
+    // 1] I (unadjusted); 2] IM (unadjusted); 3] weight; 4] I (adjusted); 5] IM (adjusted);
+    // scalar returns [0]: caliper drops
+
+    /* Free Memory */
+    //free(S);
+    free(order_DistPot);
+    if(replace==0)
+      {
+	free(ReplaceVector);
+      }
+    
+    r = rows(rr);
+    c = cols(rr);
+
+    PROTECT(ret=allocMatrix(REALSXP, r, c));
+    /* Loop through the data and display the same in matrix format */
+    k = 0;
+    for( i = 0; i < c; i++ )
+      {
+	for( j = 0; j < r; j++ )
+	  {
+	    // REAL(ret)[k] = rr(j,i);
+	    // REAL(ret)[k] = rr[j*c+i];
+	    /* Use Macro to Index */
+	    REAL(ret)[k] = rr[M(j, i, c)];
+	    k++;
+	  }
+      }
+    UNPROTECT(1);
+    return(ret);    
+  } //end of MatchLoopCfast
+
+
+/*---------------------------------------------------------------------------
+   Function : VarCalcMatchC
+
+   In       : I_N: the number of observations
+
+              I_xvars: the number of columns in the 'X' matrix---i.e.,
+                       the number of variables to match on.
+
+              I_M: 1-to-Var.calc this is the 'Var.calc' option to Match()
+
+	       I_cdd: Distance tolerance
+
+	       I_caliper: indicator for if we are using a caliper
+
+              I_ww: Weight.matrix, GenMatch assumes that it is diagonal
+
+              I_Tr: the treatment indicator--i.e., the 'Tr' argument to GenMatch()
+
+              I_X: The matrix containing the variable we are going to
+              match on, the 'X' option to GenMatch().
+
+              I_weight: the observation specific weights---i.e, the 'weight' argument 
+                        to GenMatch()
+
+	       I_CaliperVec: A vector which contains the caliper which we must fit in
+            
+              I_Xorig: The X matrix unscaled (we need this to make caliper comparisons)
+
+              I_restrict_trigger: an indicator for if we are using the restriction matrix
+
+              I_restrict_nrow: the number of restriction we have
+
+              I_restrict: the actual restriction matrix
+
+              I_DaigWeightMatrixFlag: is our I_ww matrix diagonal?
+
+
+   OUT: Sigs, the key component of the variance estimate for AI SEs when Var.calc > 0
+
+   JOB: This function is modeled after MatchLoopCfast, but it is used
+   to calculated AI SEs when Var.calc > 0. This requires matching treated
+   to treated, and controls to controls.
+
+ ---------------------------------------------------------------------------*/
+
+  SEXP VarCalcMatchC(SEXP I_N, SEXP I_xvars, SEXP I_M, SEXP I_cdd,
+		     SEXP I_caliper, 
+		     SEXP I_ww, SEXP I_Tr, SEXP I_X, 
+		     SEXP I_CaliperVec, SEXP I_Xorig,
+		     SEXP I_restrict_trigger, SEXP I_restrict_nrow, SEXP I_restrict,
+		     SEXP I_DiagWeightMatrixFlag, 
+		     SEXP I_Y, 
+		     SEXP I_weightFlag, SEXP I_weight)
+  {
+    SEXP ret;
+    
+    long N, xvars, M, caliper, restrict_trigger, restrict_nrow, DiagWeightMatrixFlag,
+      sum_caliper_drops=0;
+    double cdd, diff, Distmax, dfoo;
+    
+    long i, j, k;
+    
+    N = asInteger(I_N);
+    xvars = asInteger(I_xvars);
+    M = asInteger(I_M);
+    cdd = asReal(I_cdd);
+    caliper = (long) asReal(I_caliper);
+    restrict_nrow = asInteger(I_restrict_nrow);
+    restrict_trigger = asInteger(I_restrict_trigger);
+    DiagWeightMatrixFlag = asInteger(I_DiagWeightMatrixFlag);
+    
+    Matrix ww = Matrix(xvars, xvars);
+    Matrix Tr = Matrix(N, 1);
+    Matrix X = Matrix(N, xvars);
+    Matrix Y = Matrix(N, 1);
+    
+    k=0;
+    //rows and colums are fliped!! j,i != i,j
+    for(j=0;j<xvars; j++)
+      {
+	for(i=0;i<xvars; i++)
+	  {
+	    //ww(i,j) = REAL(I_ww)[k];
+	    ww[M(i,j,xvars)] = REAL(I_ww)[k];
+	    k++;
+	  }
+      }
+    
+    for(i=0;i<N; i++)
+      {
+	Tr[i] = REAL(I_Tr)[i];
+      }
+    
+    //rows and colums are fliped!! j,i != i,j
+    k=0;
+    for(j=0;j<xvars; j++)
+      {
+	for(i=0;i<N; i++)
+	  {
+	    //X(i,j) = REAL(I_X)[k];
+	    X[M(i,j,xvars)] = REAL(I_X)[k];
+	    k++;
+	  }
+      }
+    
+    Matrix IMi;
+    Matrix Xorig;
+    Matrix CaliperVec;
+    if(caliper==1)
+    {
+      Xorig = Matrix(N, xvars);
+      CaliperVec = Matrix(xvars, 1);
+      
+      for (i=0; i<xvars; i++)
+      {
+        CaliperVec[i] = REAL(I_CaliperVec)[i];
+      }
+      
+      //rows and colums are fliped!! j,i != i,j
+      k=0;
+      for(j=0;j<xvars; j++)
+      {
+        for(i=0;i<N; i++)
+	      {
+          //X(i,j) = REAL(I_X)[k];
+          Xorig[M(i,j,xvars)] = REAL(I_Xorig)[k];
+          k++;
+	      }
+      }	
+    } // end of caliper==1
+    
+    Matrix restrict; 
+    if (restrict_trigger==1)
+    {
+      restrict = Matrix(restrict_nrow, 3);
+      
+      k=0;
+      for(j=0;j<3; j++)
+      {
+        for(i=0;i<restrict_nrow; i++)
+	      {
+		restrict[M(i,j,3)] = REAL(I_restrict)[k];
+		k++;
+	      }
+      }	
+    } /* if (restrict_trigger==1) */
+
+    for(i=0;i<N; i++)
+      {
+	Y.data[i] = REAL(I_Y)[i];
+      }
+
+    Matrix weight, weightPot, tt, weightPot_sort, weightPot_sum, foo1, foo2;
+    int weightFlag = asInteger(I_weightFlag);
+    if(weightFlag==1)
+      {
+	weight = Matrix::zeros(N, 1);
+
+	for(i=0;i<N; i++)
+	  {
+	    weight.data[i] = REAL(I_weight)[i];
+	  }	
+      }
+
+    Matrix INN = Matrix::seqa(1, 1, N);
+    // TT is just equal to INN
+
+#ifdef __NBLAS__
+    Matrix DX, ZX(N, xvars), Dist(N, 1);
+    if (DiagWeightMatrixFlag!=1) {
+      /* ctor zeros data so this does not add any computational time and maintains the dims outside 
+	 the scope of this if statement */
+      DX = Matrix::zeros(N, xvars);
+    }
+#else
+    Matrix index_onesN = Matrix::ones(N, 1);
+    Matrix xx;
+    Matrix DX, Dist;
+#endif
+
+    /* set misc */
+    int TREATi = 0;
+
+    Matrix IMt;
+    Matrix ACTMAT, POTMAT(N, 1), Sigs(N,1);
+
+    // Temporary size for these matrices to avoid rbind, in the Var.calc case this IS the max
+    int NM = N*M;
+
+    Matrix I  = Matrix(NM,1);
+    Matrix IM = Matrix(NM,1);
+    Matrix W  = Matrix(NM,1);
+
+    //These are larger than needed; it is just easier this way
+    int *order_DistPot = (int *) malloc(N*sizeof(int));  
+    double *S = (double *) malloc(N*sizeof(double));  
+    Matrix DistPot=Matrix(N, 1);
+
+    for(i=0; i < N; i++)
+      {
+	// treatment indicator for observation to be matched        
+	TREATi = (int) Tr[i];
+	
+#ifdef __NBLAS__
+	if (DiagWeightMatrixFlag!=1)
+	  {
+	    // this loop is equivalent to the matrix X less the matrix A, which is
+	    // the product of N rows by 1 column of 1.0 and row R of X.
+	    double *dest = ZX.data;
+	    double *src  = X.data;
+	    double *row  = X.data + (i * xvars);
+	    for (int jj = 0; jj < N; ++jj) {
+	      for (int kk = 0; kk < xvars; ++kk, ++dest, ++src) {
+		*dest = *src - row[kk];
+	      }
+	    }
+	    
+	    /* note that xvars must be > 1 */
+	    //JSS
+	    // do the second multiplication with dgemm, multiplying the matrix
+	    // above, D, by the transpose of matrix W.
+	    cblas_dgemm(CblasRowMajor,// column major
+			CblasNoTrans, // A not transposed
+			CblasTrans,   // B transposed
+			xvars,        // M
+			N,            // N
+			xvars,        // K
+			1.0,          // alpha, (alpha * A * B)
+			ww.data,      // A
+			xvars,        // leading dimension for A
+			ZX.data,      // B
+			xvars,        // leading dimension for B
+			0.0,          // beta, (beta * C)
+			DX.data,      // C
+			N);           // leading dimension for C
+	    
+	    DX.multi_scalar(DX);
+	    
+	    std::swap(DX.colsize, DX.rowsize);
+	    
+	    Dist = sumc(DX);
+	    
+	    std::swap(Dist.colsize, Dist.rowsize); // transpose 1 x N -> N x 1
+	    std::swap(DX.colsize, DX.rowsize);
+	  } else 
+	  {
+#ifdef __GenMatchBLAS__
+	    // this loop is equivalent to the matrix X less the matrix A, which is
+	    // the product of N rows by 1 column of 1.0 and row R of X.
+	    double *dest = ZX.data;
+	    double *src  = X.data;
+	    double *row  = X.data + (i * xvars);
+	    for (int jj = 0; jj < N; ++jj) {
+	      for (int kk = 0; kk < xvars; ++kk, ++dest, ++src) {
+		*dest = *src - row[kk];
+	      }
+	    }
+	    
+	    //http://docs.sun.com/source/819-3691/dscal.html
+	    for (int kk=0; kk < xvars; kk++)
+	      {
+		cblas_dscal(N, ww.data[M(kk,kk,xvars)], ZX.data+kk, xvars);
+	      }
+	    
+	    ZX.multi_scalar(ZX);
+	    
+	    //http://docs.sun.com/source/819-3691/dasum.html 
+	    for (int jj=0; jj < N; jj++)
+	      {
+		Dist.data[jj] = cblas_dasum(xvars, ZX.data+M(jj, 0, xvars), 1);
+	      }
+#else
+	    // Don't calculate Distance for observations with of a 
+	    // DIFFERENT treatment assignment
+	    for (int jj = 0; jj < N; jj++) {
+	      if( abs(TREATi-Tr[jj]) < TOL )
+		{
+		  Dist.data[jj] = 0.0;
+		  for (int kk=0; kk < xvars; kk++)
+		    {
+		      ZX.data[M(jj,kk,xvars)] = X.data[M(jj,kk,xvars)] - X.data[M(i,kk,xvars)];
+		      dfoo  = ZX.data[M(jj,kk,xvars)] * ww.data[M(kk,kk,xvars)];
+		      Dist.data[jj] += dfoo*dfoo;
+		    }
+		} // if TR
+	    } //end of jj loop
+#endif /* end of __GenMatchBLAS__ ifdef */
+	  } /* end of if (DiagWeightMatrixFlag!=1) */
+#else
+	// covariate value for observation to be matched                        
+	xx = X(i,_);
+	
+	
+	DX = (X - (index_onesN * xx)) * t(ww);
+	
+	if (xvars>1)
+	  {
+	    //JSS
+	    foo1 = t(multi_scalar(DX, DX));
+	    Dist = t(sumc(foo1));
+	    
+	  } 
+	else 
+	  {
+	    Dist = multi_scalar(DX, DX);
+	  } // end of xvars
+#endif /* end __NBLAS__ */
+
+	//Remove self as a potential match
+	Dist[i] = DOUBLE_XMAX;
+	
+	// Dist distance to observation to be matched
+	// is N by 1 vector	    
+	if (restrict_trigger==1)
+	  {
+	    for(j=0; j<restrict_nrow; j++)
+	      {
+		if ( ((long) restrict[M(j,0,3)])-1 ==i )
+		  {
+		    
+		    if (restrict[M(j,2,3)] < 0) {
+		      Dist[ ((long) restrict[M(j,1,3)])-1 ] = DOUBLE_XMAX;
+		    }
+		    else {
+		      Dist[ ((long) restrict[M(j,1,3)])-1 ] = restrict[M(j,2,3)];
+		    }
+		  }
+		else if ( ((long) restrict[M(j,1,3)])-1 ==i ) 
+		  {
+		    
+		    if (restrict[M(j,2,3)] < 0) {
+		      Dist[ ((long) restrict[M(j,0,3)])-1 ] = DOUBLE_XMAX;
+		    }
+		    else {
+		      Dist[ ((long) restrict[M(j,0,3)])-1 ] = restrict[M(j,2,3)];
+		    }
+		  }
+	      }
+	  } /* if (restrict_trigger==1) */
+
+        // set of potential matches (all observations with the *SAME* treatment)
+	POTMAT = EqualityTestScalar(Tr, TREATi);
+	
+	if (caliper==1)
+	  {
+	    for (j=0; j<N; j++)
+	      {
+		if((int) POTMAT[j]==1)
+		  {
+		    for (k=0; k<xvars; k++)
+		      {
+			diff = abs(Xorig[M(i, k, xvars)] - Xorig[M(j,k,xvars)]); 
+			if (diff > CaliperVec[k])
+			  {
+			    Dist[j] = DOUBLE_XMAX;
+			    break;
+			  }
+		      }
+		  }
+	      } 
+	  }//end of if caliper
+
+	if(weightFlag==0)
+	  {
+	    // X's for potential matches
+	    DistPot = selif(Dist, POTMAT);
+	    long DistPot_size = size(DistPot);
+	    
+	    Distmax = kth_smallest(DistPot.data, DistPot_size, (M-1));
+	    
+	    if (restrict_trigger==1 | caliper==1)
+	      {
+		if ( (Distmax+cdd) > DOUBLE_XMAX_CHECK)
+		  {
+		    sum_caliper_drops++;
+		    continue;
+		  }
+	      } 
+	    
+	    // selection of actual matches 
+	    // logical index
+	    ACTMAT = LessEqualTestScalar(Dist,  (Distmax+cdd));
+	    ACTMAT = VectorAnd(POTMAT, ACTMAT);
+	    
+	    // counts how many times each observation is matched.
+	    double Mi = sum(ACTMAT);
+
+	    /**********************************************/
+	    /* ESTIMATE Sigs */
+	    double fm=0, sm=0;
+	    double sumweightactmat = Mi + 1.0;
+	    
+	    //Add self back in
+	    ACTMAT.data[i] = 1.0;
+	    for(j=0; j<N; j++)
+	      {
+		if ( abs(ACTMAT.data[j] - 1.0) < TOL)
+		  {
+		    fm += Y.data[j];
+		    sm += (Y.data[j]*Y.data[j]);
+		  }
+	      }
+	    fm = fm/sumweightactmat;
+	    sm = sm/sumweightactmat;
+	    Sigs[i] = (sm - fm * fm)*sumweightactmat/(sumweightactmat-1.0);
+	  } else {
+	  // X's for potential matches
+	  DistPot = selif(Dist, POTMAT);
+	  weightPot = selif(weight, POTMAT);
+
+	  long weightPot_size = size(weightPot);
+	  
+	  for(j=0; j< weightPot_size; j++)
+	    {
+	      // assume that weightPot_size = size(DistPot)
+	      order_DistPot[j] = j;
+	      S[j] = (double) DistPot[j];
+	    }
+
+	  rsort_with_index (S, order_DistPot, weightPot_size);
+	  
+	  weightPot_sort = Matrix(weightPot_size, 1);
+	  for(j=0; j < weightPot_size; j++)
+	    {
+	      weightPot_sort[j] = weightPot[order_DistPot[j]];
+	    }
+	  weightPot_sum = cumsum(weightPot_sort);
+
+	  tt = Matrix::seqa(1, 1, rows(weightPot_sum));
+	  
+	  foo1 = GreaterEqualTestScalar(weightPot_sum, M);
+	  foo2 = selif(tt, foo1);
+	  
+	  long MMM = (long) min(foo2) - 1;
+	  
+	  // distance at last match
+	  double Distmax = S[MMM];
+	  
+	  if (restrict_trigger==1 | caliper==1)
+	    {
+	      if ( (Distmax+cdd) > DOUBLE_XMAX_CHECK)
+		{
+		  sum_caliper_drops++;
+		  continue;
+		}
+	    } 
+	  
+	  // selection of actual matches 
+	  // logical index
+	  ACTMAT = LessEqualTestScalar(Dist,  (Distmax+cdd));
+	  ACTMAT = VectorAnd(POTMAT, ACTMAT);
+	  
+	  /**********************************************/
+	  /* ESTIMATE Sigs */
+	  double fm=0, sm=0, ws=0;
+	  
+	  //Add self back in
+	  ACTMAT.data[i] = 1.0;
+	  for(j=0; j<N; j++)
+	    {
+	      if ( abs(ACTMAT.data[j] - 1.0) < TOL)
+		{
+		  fm += Y.data[j]*weight[j];
+		  sm += (Y.data[j]*Y.data[j]*weight[j]);
+		  ws += weight[j];
+		}
+	    }
+	  fm = fm/ws;
+	  sm = sm/ws;
+	  Sigs[i] = (sm - fm * fm)*ws/(ws-1.0);
+	} //end of weightFlag
+      } //END OF i MASTER LOOP!
+    
+    /* Free Memory */
+    free(S);
+    free(order_DistPot);
+    
+    PROTECT(ret=allocMatrix(REALSXP, N, 1));
+    /* Loop through the data and display the same in matrix format */
+    for( j = 0; j < N; j++ )
+      {
+	REAL(ret)[j] = Sigs[j];
+      }
+    UNPROTECT(1);
+    return(ret);    
+  } //end of VarCalcMatchC
+
+
+} //end of extern "C"
+
+double min_scalar (double a, double b)
+{
+  if (a < b)
+    return(a);
+  
+  return(b);
+} // end of min_scalar
+
+double max_scalar (double a, double b)
+{
+  if (a > b)
+    return(a);
+
+  return(b);
+} // end of max_scalar
+
+//previously in a __NBLAS__ wrapper, but it should always be used
+Matrix EqualityTestScalar(Matrix a, double s)
+{
+  for (long i = 0; i < a.size; ++i)
+    a.data[i] = (a.data[i] < (s+TOL)) && (a.data[i] > (s-TOL)) ? 1 : 0;
+  return a;
+} //end of EqualityTestScalar
+
+
+//previously in a __NBLAS__ wrapper, but it should always be used
+Matrix GreaterEqualTestScalar(Matrix a, long s)
+{
+  for (long i = 0; i < a.size; ++i)
+    a.data[i] = (a.data[i] >= (s-TOL)) ? 1 : 0;
+  return a;
+} //end of GreaterEqualTestScalar
+
+
+//previously in a __NBLAS__ wrapper, but it should always be used
+Matrix LessEqualTestScalar(Matrix a, double s)
+{
+  for (long i = 0; i < a.size; ++i)
+    a.data[i] = (a.data[i] <= (s+TOL)) ? 1 : 0;
+  return a;
+} //end of LessEqualTestScalar
+
+
+Matrix VectorAnd(Matrix a, Matrix b)
+{
+  long nrows = rows(a);
+  Matrix ret =  Matrix::zeros(nrows, 1);
+
+  for (long i =0; i< nrows; i++)
+    {
+      if( (a[i] == 1) &&  (b[i]== 1) )
+	{
+	  ret[i] = 1;
+	}
+    }
+  return(ret);
+} //end of VectorAnd
+
+Matrix EqualityTestMatrix(Matrix a, Matrix s)
+{
+  long nrows = rows(a);
+  long ncols = cols(a);
+  Matrix ret =  Matrix::zeros(nrows, ncols);
+
+  long scols = cols(s);
+
+  if (scols==1)
+    {
+      for (long i =0; i< nrows; i++)
+	{
+	  for (long j =0; j< ncols; j++)
+	    {
+	      if( (a[M(i, j, ncols)] < (s[i]+TOL)) &  (a[M(i, j, ncols)] > (s[i]-TOL)) )
+		{
+		  ret[M(i, j, ncols)] = 1;
+		}
+	    }
+	}
+    }
+  else if (scols==ncols)
+    {
+      for (long i =0; i< nrows; i++)
+	{
+	  for (long j =0; j< ncols; j++)
+	    {
+	      if( (a[M(i, j, ncols)] < (s[M(i, j, ncols)]+TOL)) &  
+		  (a[M(i, j, ncols)] > (s[M(i, j, ncols)]-TOL)) )
+		{
+		  ret[M(i, j, ncols)] = 1;
+		}
+	    }
+	}
+    }
+  else 
+    {
+      Rprintf("ASSERTION in EqualityTestMatrix\n");
+    }
+
+  return(ret);
+} //end of EqualityTestMatrix
+
+/* cumsum */
+Matrix cumsum(Matrix a)
+{
+  long nrows = rows(a);
+  Matrix ret = Matrix::zeros(nrows, 1);
+  
+  ret[0] = a[0];
+  for (long i = 1;  i < nrows; i++) 
+  {
+    ret[i] = ret[i-1] + a[i];
+  }
+  
+  return ret;
+} //end of cumsum
+
+//! Calculate the sum of all of the elements in a  Matrix
+double sum (const Matrix & A)
+{
+  double ret=0;
+  long ncols = cols(A);
+  long i;
+  
+  Matrix sumvec = sumc(A);
+  
+  for (i=0; i<ncols; i++)
+  {
+    ret = ret + sumvec[i];
+  }
+  
+  return ret;
+}
+
+/*DISPLAY This function will display the double matrix stored in an mxArray.
+* This function assumes that the mxArray passed as input contains double
+* array.
+*/
+void display(Matrix A)
+{
+  int i=0, j=0; /* loop index variables */
+  int r=0, c=0; /* variables to store the row and column length of the matrix */
+  int count=0;
+  
+  /* Get the size of the matrix */
+  r = rows(A);
+  c = cols(A);
+  
+  /* Loop through the data and display the same in matrix format */
+  for( i = 0; i < r; i++ ){
+    for( j = 0; j < c; j++){
+      Rprintf("%e\t",A[count]);
+      count++;
+    }
+    Rprintf("\n");
+  }
+  Rprintf("\n");
+}
+
+//previously in a __NBLAS__ wrapper, but it should always be used
+Matrix multi_scalar (Matrix a, Matrix b)
+{
+  a.multi_scalar(b);
+  return a;
+} 
diff --git a/src/matching.h b/src/matching.h
new file mode 100644
index 0000000..4c6d710
--- /dev/null
+++ b/src/matching.h
@@ -0,0 +1,27 @@
+#define M(ROW,COL,NCOLS) (((ROW)*(NCOLS))+(COL))
+#define TOL 0.0000000001
+
+#define DOUBLE_XMAX_CHECK DOUBLE_XMAX/1000 - 1000
+
+/* Use CBLAS and Nate Optimizations. Note that uses of BLAS in
+   FasterMatchC() and FastMatchC() also requires that
+   __GenMatchBLAS__ is also defined in matching.cc
+*/
+#define __NBLAS__
+
+// my function declarations
+double sum (const Matrix & A);
+double min_scalar (double a, double b);
+double max_scalar (double a, double b);
+Matrix multi_scalar (Matrix a, Matrix b);
+Matrix col_assign (Matrix a, Matrix b, long col);
+Matrix row_assign (Matrix a, Matrix b, long row);
+Matrix diagCreate (Matrix a);
+Matrix EqualityTestScalar(Matrix a, double s);
+Matrix EqualityTestMatrix(Matrix a, Matrix s);
+Matrix GreaterEqualTestScalar(Matrix a, long s);
+Matrix LessEqualTestScalar(Matrix a, double s);
+Matrix VectorAnd(Matrix a, Matrix b);
+Matrix cumsum(Matrix a);
+void display(Matrix A);
+
diff --git a/src/scythematrix.cc b/src/scythematrix.cc
new file mode 100644
index 0000000..6565e70
--- /dev/null
+++ b/src/scythematrix.cc
@@ -0,0 +1,2639 @@
+/* Edited by Jasjeet S. Sekhon <jasjeet_sekhon at berkeley.edu> */
+/* HTTP://sekhon.berkeley.edu                                */
+/*                                                           */
+/* April 26, 2013                                            */
+/* get rid of friend-injection for ones, zero, seqa          */
+/* January 9, 2012                                           */
+/* May 9, 2010: Solaris compatibility issues                 */
+/* October 24, 2006                                          */
+/* May 25, 2006                                              */
+/* __NATE__ additions by Nate Begeman (Apple)                */
+
+//
+// Memeber function definitions for the Scythe_Double_Matrix.h
+// header file.  These functions make up the Matrix class as used
+// in the Scythe project.  
+//
+// Scythe C++ Library
+// Copyright (C) 2000 Kevin M. Quinn and Andrew D. Martin
+//
+// This code written by:
+//
+// Kevin Quinn
+// Assistant Professor
+// Dept. of Political Science and 
+// Center for Statistics and the Social Sciences
+// Box 354322
+// University of Washington
+// Seattle, WA  98195-4322
+// quinn at stat.washington.edu
+//
+// Andrew D. Martin
+// Assistant Professor
+// Dept. of Political Science
+// Campus Box 1063
+// Washington University
+// St. Louis, MO 63130
+// admartin at artsci.wustl.edu
+// 
+// This program is free software; you can redistribute it and/or
+// modify it under the terms of the GNU General Public License as
+// published by the Free Software Foundation; either version 2 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
+// USA
+
+#ifndef SCYTHE_DOUBLE_MATRIX_CC
+#define SCYTHE_DOUBLE_MATRIX_CC
+
+#include "scythematrix.h"
+
+/*! \class Matrix
+ *  \brief The Matrix Class that is the cornerstone of the Scythe 
+ *	Statistical Library
+ 
+ *  The Matrix class contains functions that modify the Matrix object 
+ *	in a variety of ways.
+ */
+// Avoid NameSpace Pollution
+namespace SCYTHE {
+    using namespace std;
+    
+/********************     BASIC FUNCTIONS     *************************/
+/**********************************************************************/
+    
+  /*!
+  * \brief CONSTRUCTOR:  Matrix  - Creates Matrix obj. with specificed 
+   * rows and columns, sets each element = 0
+   * \param rows An integer that reflects the number of rows.
+   * \param cols An integer that reflects the numbef of columns.
+   */
+  // #ifdef __NATE__
+  Matrix::Matrix (const int& rows, const int& cols) {
+    if (rows < 1 || cols < 1) {
+      error("Improper row or column dimension in Matrix constructor");
+    }
+    rowsize = rows;    // assign Matrix rowsize
+    colsize = cols;    // assign Matrix colsize 
+    size = rows * cols;    // assign Matrix size
+    //data = new double[size];
+    data = (double *) malloc(size * sizeof(double));
+    memset(data, 0, size * sizeof(double));
+  }
+
+
+/*!
+ * \brief CONSTRUCTOR:  Matrix - Creates Matrix object filled with data 
+ * from array
+ * \param inputarray An array containing the data for the Matrix in 
+ * row major order.
+ * \param rows An integer reflecting the number of rows.
+ * \param cols An integer that reflects the numbef of columns.
+ */
+    Matrix::Matrix (const double *inputarray, const int& rows, const int& cols)
+    {
+	if (rows < 1 || cols < 1) {
+	  error("Improper row or column dimension in Matrix constructor");
+	}
+	rowsize = rows;    // assign Matrix rowsize
+	colsize = cols;    // assign Matrix colsize
+	size = rows * cols;    // assign Matrix size
+	// data = new double[size];
+	data = (double *) malloc(size * sizeof(double));
+	
+	/*
+	for (int i = 0; i < size; ++i) {
+	    data[i] = inputarray[i];
+	}
+	*/
+	memcpy(data, inputarray, size*sizeof(double));
+    }
+    
+/*! 
+ * \brief CONSTRUCTOR:  Matrix - Creates Matrix object from old Matrix
+ * \param old_Matrix A Matrix object that contains the data from 
+ * another Matrix.
+ */
+    Matrix::Matrix (const Matrix & old_Matrix)
+    {
+	rowsize = old_Matrix.rowsize;  // assign Matrix rowsize
+	colsize = old_Matrix.colsize;  // assign Matrix colsize
+	size = old_Matrix.size;  // assign Matrix size
+	//data = new double[size];
+	data = (double *) malloc(size * sizeof(double));
+	
+	/*
+	for (int i = 0; i < size; ++i) {
+	    data[i] = old_Matrix.data[i];
+	}
+	*/
+	memcpy(data, old_Matrix.data, size*sizeof(double));
+    }
+    
+/*!
+ * \brief OPERATOR:  Matrix operator '=' - Allows for the copying of a 
+ * Matrix
+ * \param B A Matrix from which the data will be copied.
+ * \return A Matrix object.
+ */
+    
+    Matrix & 
+    Matrix::operator = (const Matrix & B)
+    {
+	rowsize = B.rowsize;
+	colsize = B.colsize;
+	size = B.size;
+	
+	// delete[]data;
+	free(data);
+	//data = new double[size];
+	data = (double *) malloc(size * sizeof(double));
+	memcpy(data, B.data, size * sizeof(double));
+	
+	return *this;
+    }
+    
+    
+    
+    
+/*!
+ * \brief OPERATOR: Matrix operator () - Retrieves all Matrix elements 
+ * in row \a i.  Please Note: Indexing starts at 0.
+ * \param i a constant integer referring to the number of the 
+ * row to be retrived.
+ * \param a a constant all_elements 
+ *  \return Matrix all elements in row \a i.
+ */
+    
+    Matrix 
+    Matrix::operator () (const int& i, const all_elements& a)
+    {
+	if (i >= rowsize || i < 0) {
+	  error("Index out of range in () operator");
+	}
+	
+	int newrowsize = 1;
+	int newcolsize = colsize;
+	Matrix newdata(newrowsize, newcolsize);
+
+	/*
+	for (int j = 0; j < newcolsize; ++j) {
+	    newdata.data[j] = data[j + i*colsize];
+	}
+	*/
+	memcpy(newdata.data, data+i*colsize, newcolsize*sizeof(double));
+	return newdata;
+    }
+    
+    
+    
+/*! 
+ * \brief OPERATOR: Matrix operator () - Retrieves all Matrix elements 
+ * in column \a j. Please Note: Indexing starts at 0.
+ * \param _ a constant of type all_elements.
+ * \param j a constant integer referring to the number of the 
+ * column to be retrived.
+ *  \return Matrix all elements in column \a j.
+ */
+    
+    Matrix 
+    Matrix::operator () (const all_elements& a, const int& j)
+    {
+	if (j >= colsize || j < 0) {
+	  error("Index out of range in () operator");
+	}
+	
+	int newrowsize = rowsize;
+	int newcolsize = 1;
+	Matrix newdata(newrowsize, newcolsize);
+	
+	for (int i = 0; i < newrowsize; ++i) {
+	    newdata.data[i] = data[j + i*colsize];
+	}
+	
+	return newdata;
+    }
+    
+    
+    
+/*!
+ * \brief OPERATOR: Matrix operator () - Retrieves Matrix elements 
+ * in row \a i.  Please Note: Indexing starts at 0.
+ * \param i a constant integer referring to the number of the 
+ * row to be retrived.
+ * \param J a constant reference to the Matrix from which the 
+ * data will be extracted.
+ *  \return Matrix elements in row \a i.
+ */
+    
+    Matrix
+    Matrix::operator () (const int& i, const Matrix& J)
+    {
+	
+	if (i >= rowsize || i < 0) {
+	  error("Index out of range in () operator");
+	}
+	
+	if (J.colsize != 1 && J.rowsize != 1) {
+	  error("Either rows or cols of J != 1 in () operator");
+	}
+	
+	int newrowsize = 1;
+	int newcolsize = J.size;
+	Matrix newdata(newrowsize, newcolsize);
+
+	/*
+	for (int j = 0; j < newcolsize; ++j) {
+	    int index = static_cast < int >(J.data[j]);
+	    if (index >= colsize || index < 0) {
+		error("Index out of range in () operator");
+	    }
+	    index = index + i * colsize;
+	    newdata.data[j] = data[index];
+	}
+	*/
+	memcpy(newdata.data, data+i*colsize, newcolsize*sizeof(double));
+	
+	return newdata;
+    }
+    
+/*! 
+ * \brief OPERATOR: Matrix operator () - Retrieves Matrix elements 
+ * in column \a j. Please Note: Indexing starts at 0.
+ * \param I a constant reference to the Matrix from which the data 
+ * will be extracted.
+ * \param j a constant integer referring to the number of the 
+ * column to be retrived.
+ *  \return Matrix elements in column \a j.
+ */
+    Matrix
+    Matrix::operator () (const Matrix& I, const int& j)
+    {
+	
+	if (j >= colsize || j < 0) {
+	  error("Index out of range in () operator");
+	}
+	
+	if (I.colsize != 1 && I.rowsize != 1) {
+	  error("Either rows or cols of I != 1 in () operator");
+	}
+	
+	int newrowsize = I.size;
+	int newcolsize = 1;
+	Matrix newdata(newrowsize, newcolsize);
+	
+	for (int i = 0; i < newrowsize; ++i) {
+	    int index = static_cast < int >(I.data[i]);
+	    if (index >= rowsize || index < 0) {
+	      error("Index out of range in () operator");
+	    }
+	    index = j + index * colsize;
+	    newdata.data[i] = data[index];
+	}
+
+	return newdata;
+    }
+    
+    
+    
+/*! 
+ * \brief OPERATOR: Matrix operator () - Extracts submatrix 
+ * from existing matrix
+ 
+ * OPERATOR: Matrix operator () - Extracts submatrix from existing matrix.  
+ * Get elements \a i,\a j from a Matrix where \a i in \a I and \a j 
+ * in \a J.  Indexing starts at 0.
+ * \param I a constant reference to the Matrix from which the data 
+ * will be extracted.
+ * \param J a constant reference to another Matrix from which the 
+ * data will be extracted.
+ * \return a new Matrix created from the selected data from the 
+ * previous two.
+ */
+    Matrix 
+    Matrix::operator () (const Matrix& I, const Matrix& J){
+	if (I.colsize != 1 && I.rowsize != 1) {
+	  error("Either Rows or Cols of I != 1 in () operator");
+	}
+	if (J.colsize != 1 && J.rowsize != 1) {
+	  error("Either rows or cols of J != 1 in () operator");
+	}
+	if (I.size > rowsize){
+	  error("size(I) > rowsize of Matrix in Matrix operator ()");
+	}
+	if (J.size > colsize){
+	  error("size(J) > colsize of Matrix in Matrix operator ()");
+	}
+	
+	int place = 0;
+	int indexi, indexj;
+	Matrix newdata(I.size,  J.size);
+
+	for (int i = 0; i < I.size; i++) {
+	    for (int j = 0; j < J.size; j++) {
+		indexi = static_cast < int > (I.data[i]);
+		indexj = static_cast < int > (J.data[j]);
+		if (indexi >= rowsize || indexi < 0) {
+		  error("Row index out of range in () operator");
+		}
+		if (indexj >= colsize || indexj < 0) {
+		  error("Column index out of range in () operator");
+		}
+		newdata.data[place] = data[indexi * colsize + indexj];
+		place++;
+	    }
+	}
+	
+	return newdata;
+    }
+    
+    
+    
+/*!
+ * \brief Prints the Matrix to the screen
+ * \param width a constant integer reflecting the screen width 
+ * (in characters) for each element of the Matrix.  This is used 
+ * in the C++ \e setw() function.
+ * \param prec a constant integer reflecting the decimal precision 
+ * of each element in the Matrix.  This is used in the C++ \e 
+ * setprecision() function.
+ * \return void
+ */
+/*
+    void
+    Matrix::print (const int width, const int prec)
+    {
+	
+	int count = 0;
+	
+	for (int i = 0; i < rowsize; ++i) {
+	    if (i > 0) {
+		cout << endl;
+	    }
+	    for (int j = 0; j < colsize; ++j) {
+		cout << setw (width) << setprecision (prec) 
+		     << data[i * colsize + j] << " ";
+		++count;
+	    }
+	}
+	cout << endl << endl;
+    }
+*/
+    
+/********************   MORE ADVANCED FUNCTIONS  **********************/
+/**********************************************************************/
+    
+//  FUNCTION: c  - concatenates a sequence of doubles into a Matrix
+/*!
+ * \brief Concatenates a sequence of doubles into a Matrix.
+ * 
+ * Concatenates a sequence of doubles into a Matrix.
+ * \param a first double to be concatenated.
+ * \param b second double to be concatenated.
+ * \param ... other doubles (number determined by user (up to 26)).
+ * \return A Matrix object, the column vector formed by concatenating the 
+ * input doubles.
+ */
+    Matrix c (const double& a, const double& b){
+      Matrix newdata(2, 1);
+	newdata.data[0] = a;
+	newdata.data[1] = b;
+	
+	return newdata;
+    }
+    
+    Matrix c (const double& a, const double& b, const double& c){
+      Matrix newdata(3, 1);
+	newdata.data[0] = a;
+	newdata.data[1] = b;
+	newdata.data[2] = c;
+	
+	return newdata;
+    }
+    
+    Matrix c (const double& a, const double& b, const double& c, 
+	      const double& d){ 
+      Matrix newdata(4, 1);
+	newdata.data[0] = a;
+	newdata.data[1] = b;
+	newdata.data[2] = c;
+	newdata.data[3] = d;
+	
+	return newdata;
+    }
+    
+    Matrix c (const double& a, const double& b, const double& c, 
+	      const double& d, const double& e){ 
+      Matrix newdata(5, 1);
+	newdata.data[0] = a;
+	newdata.data[1] = b;
+	newdata.data[2] = c;
+	newdata.data[3] = d;
+	newdata.data[4] = e;
+	
+	return newdata;
+    }
+    
+    Matrix c (const double& a, const double& b, const double& c, 
+	      const double& d, const double& e, const double& f){ 
+      Matrix newdata(6, 1);
+	newdata.data[0] = a;
+	newdata.data[1] = b;
+	newdata.data[2] = c;
+	newdata.data[3] = d;
+	newdata.data[4] = e;
+	newdata.data[5] = f;
+	
+	return newdata;
+    }
+    
+    Matrix c (const double& a, const double& b, const double& c, 
+	      const double& d, const double& e, const double& f,
+	      const double& g){ 
+      Matrix newdata(7, 1);
+	newdata.data[0] = a;
+	newdata.data[1] = b;
+	newdata.data[2] = c;
+	newdata.data[3] = d;
+	newdata.data[4] = e;
+	newdata.data[5] = f;
+	newdata.data[6] = g;
+	
+	return newdata;
+    }
+    
+    Matrix c (const double& a, const double& b, const double& c, 
+	      const double& d, const double& e, const double& f,
+	      const double& g, const double& h){ 
+      Matrix newdata(8, 1);
+	newdata.data[0] = a;
+	newdata.data[1] = b;
+	newdata.data[2] = c;
+	newdata.data[3] = d;
+	newdata.data[4] = e;
+	newdata.data[5] = f;
+	newdata.data[6] = g;
+	newdata.data[7] = h;
+	
+	return newdata;
+    }
+    
+    Matrix c (const double& a, const double& b, const double& c, 
+	      const double& d, const double& e, const double& f,
+	      const double& g, const double& h, const double& i){ 
+      Matrix newdata(9, 1);
+	newdata.data[0] = a;
+	newdata.data[1] = b;
+	newdata.data[2] = c;
+	newdata.data[3] = d;
+	newdata.data[4] = e;
+	newdata.data[5] = f;
+	newdata.data[6] = g;
+	newdata.data[7] = h;
+	newdata.data[8] = i;
+	
+	return newdata;
+    }
+    
+    Matrix c (const double& a, const double& b, const double& c, 
+	      const double& d, const double& e, const double& f,
+	      const double& g, const double& h, const double& i,
+	      const double& j){ 
+      Matrix newdata(10, 1);
+	newdata.data[0] = a;
+	newdata.data[1] = b;
+	newdata.data[2] = c;
+	newdata.data[3] = d;
+	newdata.data[4] = e;
+	newdata.data[5] = f;
+	newdata.data[6] = g;
+	newdata.data[7] = h;
+	newdata.data[8] = i;
+	newdata.data[9] = j;
+	
+	return newdata;
+    }
+    
+    Matrix c (const double& a, const double& b, const double& c, 
+	      const double& d, const double& e, const double& f,
+	      const double& g, const double& h, const double& i,
+	      const double& j, const double& k){ 
+      Matrix newdata(11, 1);
+	newdata.data[0] = a;
+	newdata.data[1] = b;
+	newdata.data[2] = c;
+	newdata.data[3] = d;
+	newdata.data[4] = e;
+	newdata.data[5] = f;
+	newdata.data[6] = g;
+	newdata.data[7] = h;
+	newdata.data[8] = i;
+	newdata.data[9] = j;
+	newdata.data[10] = k;
+	
+	return newdata;
+    }
+    
+    Matrix c (const double& a, const double& b, const double& c, 
+	      const double& d, const double& e, const double& f,
+	      const double& g, const double& h, const double& i,
+	      const double& j, const double& k, const double& l){ 
+      Matrix newdata(12, 1);
+	newdata.data[0] = a;
+	newdata.data[1] = b;
+	newdata.data[2] = c;
+	newdata.data[3] = d;
+	newdata.data[4] = e;
+	newdata.data[5] = f;
+	newdata.data[6] = g;
+	newdata.data[7] = h;
+	newdata.data[8] = i;
+	newdata.data[9] = j;
+	newdata.data[10] = k;
+	newdata.data[11] = l;
+	
+	return newdata;
+    }
+    
+    Matrix c (const double& a, const double& b, const double& c, 
+	      const double& d, const double& e, const double& f,
+	      const double& g, const double& h, const double& i,
+	      const double& j, const double& k, const double& l,
+	      const double& m){ 
+      Matrix newdata(13, 1);
+	newdata.data[0] = a;
+	newdata.data[1] = b;
+	newdata.data[2] = c;
+	newdata.data[3] = d;
+	newdata.data[4] = e;
+	newdata.data[5] = f;
+	newdata.data[6] = g;
+	newdata.data[7] = h;
+	newdata.data[8] = i;
+	newdata.data[9] = j;
+	newdata.data[10] = k;
+	newdata.data[11] = l;
+	newdata.data[12] = m;
+	
+	return newdata;
+    }
+    
+    Matrix c (const double& a, const double& b, const double& c, 
+	      const double& d, const double& e, const double& f,
+	      const double& g, const double& h, const double& i,
+	      const double& j, const double& k, const double& l,
+	      const double& m, const double& n){ 
+      Matrix newdata(14, 1);
+	newdata.data[0] = a;
+	newdata.data[1] = b;
+	newdata.data[2] = c;
+	newdata.data[3] = d;
+	newdata.data[4] = e;
+	newdata.data[5] = f;
+	newdata.data[6] = g;
+	newdata.data[7] = h;
+	newdata.data[8] = i;
+	newdata.data[9] = j;
+	newdata.data[10] = k;
+	newdata.data[11] = l;
+	newdata.data[12] = m;
+	newdata.data[13] = n;
+	
+	return newdata;
+    }
+    
+    Matrix c (const double& a, const double& b, const double& c, 
+	      const double& d, const double& e, const double& f,
+	      const double& g, const double& h, const double& i,
+	      const double& j, const double& k, const double& l,
+	      const double& m, const double& n, const double& o){ 
+      Matrix newdata(15, 1);
+	newdata.data[0] = a;
+	newdata.data[1] = b;
+	newdata.data[2] = c;
+	newdata.data[3] = d;
+	newdata.data[4] = e;
+	newdata.data[5] = f;
+	newdata.data[6] = g;
+	newdata.data[7] = h;
+	newdata.data[8] = i;
+	newdata.data[9] = j;
+	newdata.data[10] = k;
+	newdata.data[11] = l;
+	newdata.data[12] = m;
+	newdata.data[13] = n;
+	newdata.data[14] = o;
+	
+	return newdata;
+    }
+    
+    Matrix c (const double& a, const double& b, const double& c, 
+	      const double& d, const double& e, const double& f,
+	      const double& g, const double& h, const double& i,
+	      const double& j, const double& k, const double& l,
+	      const double& m, const double& n, const double& o,
+	      const double& p){ 
+      Matrix newdata(16, 1);
+	newdata.data[0] = a;
+	newdata.data[1] = b;
+	newdata.data[2] = c;
+	newdata.data[3] = d;
+	newdata.data[4] = e;
+	newdata.data[5] = f;
+	newdata.data[6] = g;
+	newdata.data[7] = h;
+	newdata.data[8] = i;
+	newdata.data[9] = j;
+	newdata.data[10] = k;
+	newdata.data[11] = l;
+	newdata.data[12] = m;
+	newdata.data[13] = n;
+	newdata.data[14] = o;
+	newdata.data[15] = p;
+	
+	return newdata;
+    }
+    
+    Matrix c (const double& a, const double& b, const double& c, 
+	      const double& d, const double& e, const double& f,
+	      const double& g, const double& h, const double& i,
+	      const double& j, const double& k, const double& l,
+	      const double& m, const double& n, const double& o,
+	      const double& p, const double& q){ 
+      Matrix newdata(17, 1);
+	newdata.data[0] = a;
+	newdata.data[1] = b;
+	newdata.data[2] = c;
+	newdata.data[3] = d;
+	newdata.data[4] = e;
+	newdata.data[5] = f;
+	newdata.data[6] = g;
+	newdata.data[7] = h;
+	newdata.data[8] = i;
+	newdata.data[9] = j;
+	newdata.data[10] = k;
+	newdata.data[11] = l;
+	newdata.data[12] = m;
+	newdata.data[13] = n;
+	newdata.data[14] = o;
+	newdata.data[15] = p;
+	newdata.data[16] = q;
+	
+	return newdata;
+    }
+    
+    Matrix c (const double& a, const double& b, const double& c, 
+	      const double& d, const double& e, const double& f,
+	      const double& g, const double& h, const double& i,
+	      const double& j, const double& k, const double& l,
+	      const double& m, const double& n, const double& o,
+	      const double& p, const double& q, const double& r){ 
+      Matrix newdata(18, 1);
+	newdata.data[0] = a;
+	newdata.data[1] = b;
+	newdata.data[2] = c;
+	newdata.data[3] = d;
+	newdata.data[4] = e;
+	newdata.data[5] = f;
+	newdata.data[6] = g;
+	newdata.data[7] = h;
+	newdata.data[8] = i;
+	newdata.data[9] = j;
+	newdata.data[10] = k;
+	newdata.data[11] = l;
+	newdata.data[12] = m;
+	newdata.data[13] = n;
+	newdata.data[14] = o;
+	newdata.data[15] = p;
+	newdata.data[16] = q;
+	newdata.data[17] = r;
+	
+	return newdata;
+    }
+    
+    Matrix c (const double& a, const double& b, const double& c, 
+	      const double& d, const double& e, const double& f,
+	      const double& g, const double& h, const double& i,
+	      const double& j, const double& k, const double& l,
+	      const double& m, const double& n, const double& o,
+	      const double& p, const double& q, const double& r,
+	      const double& s){ 
+      Matrix newdata(19, 1);
+	newdata.data[0] = a;
+	newdata.data[1] = b;
+	newdata.data[2] = c;
+	newdata.data[3] = d;
+	newdata.data[4] = e;
+	newdata.data[5] = f;
+	newdata.data[6] = g;
+	newdata.data[7] = h;
+	newdata.data[8] = i;
+	newdata.data[9] = j;
+	newdata.data[10] = k;
+	newdata.data[11] = l;
+	newdata.data[12] = m;
+	newdata.data[13] = n;
+	newdata.data[14] = o;
+	newdata.data[15] = p;
+	newdata.data[16] = q;
+	newdata.data[17] = r;
+	newdata.data[18] = s;
+	
+	return newdata;
+    }
+    
+    Matrix c (const double& a, const double& b, const double& c, 
+	      const double& d, const double& e, const double& f,
+	      const double& g, const double& h, const double& i,
+	      const double& j, const double& k, const double& l,
+	      const double& m, const double& n, const double& o,
+	      const double& p, const double& q, const double& r,
+	      const double& s, const double& t){ 
+      Matrix newdata(20, 1);
+	newdata.data[0] = a;
+	newdata.data[1] = b;
+	newdata.data[2] = c;
+	newdata.data[3] = d;
+	newdata.data[4] = e;
+	newdata.data[5] = f;
+	newdata.data[6] = g;
+	newdata.data[7] = h;
+	newdata.data[8] = i;
+	newdata.data[9] = j;
+	newdata.data[10] = k;
+	newdata.data[11] = l;
+	newdata.data[12] = m;
+	newdata.data[13] = n;
+	newdata.data[14] = o;
+	newdata.data[15] = p;
+	newdata.data[16] = q;
+	newdata.data[17] = r;
+	newdata.data[18] = s;
+	newdata.data[19] = t;
+	
+	return newdata;
+    }
+    
+    Matrix c (const double& a, const double& b, const double& c, 
+	      const double& d, const double& e, const double& f,
+	      const double& g, const double& h, const double& i,
+	      const double& j, const double& k, const double& l,
+	      const double& m, const double& n, const double& o,
+	      const double& p, const double& q, const double& r,
+	      const double& s, const double& t, const double& u){ 
+      Matrix newdata(21, 1);
+	newdata.data[0] = a;
+	newdata.data[1] = b;
+	newdata.data[2] = c;
+	newdata.data[3] = d;
+	newdata.data[4] = e;
+	newdata.data[5] = f;
+	newdata.data[6] = g;
+	newdata.data[7] = h;
+	newdata.data[8] = i;
+	newdata.data[9] = j;
+	newdata.data[10] = k;
+	newdata.data[11] = l;
+	newdata.data[12] = m;
+	newdata.data[13] = n;
+	newdata.data[14] = o;
+	newdata.data[15] = p;
+	newdata.data[16] = q;
+	newdata.data[17] = r;
+	newdata.data[18] = s;
+	newdata.data[19] = t;
+	newdata.data[20] = u;
+	
+	return newdata;
+    }
+    
+    Matrix c (const double& a, const double& b, const double& c, 
+	      const double& d, const double& e, const double& f,
+	      const double& g, const double& h, const double& i,
+	      const double& j, const double& k, const double& l,
+	      const double& m, const double& n, const double& o,
+	      const double& p, const double& q, const double& r,
+	      const double& s, const double& t, const double& u,
+	      const double& v){ 
+      Matrix newdata(22, 1);
+	newdata.data[0] = a;
+	newdata.data[1] = b;
+	newdata.data[2] = c;
+	newdata.data[3] = d;
+	newdata.data[4] = e;
+	newdata.data[5] = f;
+	newdata.data[6] = g;
+	newdata.data[7] = h;
+	newdata.data[8] = i;
+	newdata.data[9] = j;
+	newdata.data[10] = k;
+	newdata.data[11] = l;
+	newdata.data[12] = m;
+	newdata.data[13] = n;
+	newdata.data[14] = o;
+	newdata.data[15] = p;
+	newdata.data[16] = q;
+	newdata.data[17] = r;
+	newdata.data[18] = s;
+	newdata.data[19] = t;
+	newdata.data[20] = u;
+	newdata.data[21] = v;
+	
+	return newdata;
+    }
+    
+    Matrix c (const double& a, const double& b, const double& c, 
+	      const double& d, const double& e, const double& f,
+	      const double& g, const double& h, const double& i,
+	      const double& j, const double& k, const double& l,
+	      const double& m, const double& n, const double& o,
+	      const double& p, const double& q, const double& r,
+	      const double& s, const double& t, const double& u,
+	      const double& v, const double& w){ 
+      Matrix newdata(23, 1);
+	newdata.data[0] = a;
+	newdata.data[1] = b;
+	newdata.data[2] = c;
+	newdata.data[3] = d;
+	newdata.data[4] = e;
+	newdata.data[5] = f;
+	newdata.data[6] = g;
+	newdata.data[7] = h;
+	newdata.data[8] = i;
+	newdata.data[9] = j;
+	newdata.data[10] = k;
+	newdata.data[11] = l;
+	newdata.data[12] = m;
+	newdata.data[13] = n;
+	newdata.data[14] = o;
+	newdata.data[15] = p;
+	newdata.data[16] = q;
+	newdata.data[17] = r;
+	newdata.data[18] = s;
+	newdata.data[19] = t;
+	newdata.data[20] = u;
+	newdata.data[21] = v;
+	newdata.data[22] = w;
+	
+	return newdata;
+    }
+    
+    Matrix c (const double& a, const double& b, const double& c, 
+	      const double& d, const double& e, const double& f,
+	      const double& g, const double& h, const double& i,
+	      const double& j, const double& k, const double& l,
+	      const double& m, const double& n, const double& o,
+	      const double& p, const double& q, const double& r,
+	      const double& s, const double& t, const double& u,
+	      const double& v, const double& w, const double& x){ 
+      Matrix newdata(24, 1);
+	newdata.data[0] = a;
+	newdata.data[1] = b;
+	newdata.data[2] = c;
+	newdata.data[3] = d;
+	newdata.data[4] = e;
+	newdata.data[5] = f;
+	newdata.data[6] = g;
+	newdata.data[7] = h;
+	newdata.data[8] = i;
+	newdata.data[9] = j;
+	newdata.data[10] = k;
+	newdata.data[11] = l;
+	newdata.data[12] = m;
+	newdata.data[13] = n;
+	newdata.data[14] = o;
+	newdata.data[15] = p;
+	newdata.data[16] = q;
+	newdata.data[17] = r;
+	newdata.data[18] = s;
+	newdata.data[19] = t;
+	newdata.data[20] = u;
+	newdata.data[21] = v;
+	newdata.data[22] = w;
+	newdata.data[23] = x;
+	
+	return newdata;
+    }
+    
+    Matrix c (const double& a, const double& b, const double& c, 
+	      const double& d, const double& e, const double& f,
+	      const double& g, const double& h, const double& i,
+	      const double& j, const double& k, const double& l,
+	      const double& m, const double& n, const double& o,
+	      const double& p, const double& q, const double& r,
+	      const double& s, const double& t, const double& u,
+	      const double& v, const double& w, const double& x,
+	      const double& y){ 
+      Matrix newdata(25, 1);
+	newdata.data[0] = a;
+	newdata.data[1] = b;
+	newdata.data[2] = c;
+	newdata.data[3] = d;
+	newdata.data[4] = e;
+	newdata.data[5] = f;
+	newdata.data[6] = g;
+	newdata.data[7] = h;
+	newdata.data[8] = i;
+	newdata.data[9] = j;
+	newdata.data[10] = k;
+	newdata.data[11] = l;
+	newdata.data[12] = m;
+	newdata.data[13] = n;
+	newdata.data[14] = o;
+	newdata.data[15] = p;
+	newdata.data[16] = q;
+	newdata.data[17] = r;
+	newdata.data[18] = s;
+	newdata.data[19] = t;
+	newdata.data[20] = u;
+	newdata.data[21] = v;
+	newdata.data[22] = w;
+	newdata.data[23] = x;
+	newdata.data[24] = y;
+	
+	return newdata;
+    }
+    
+    Matrix c (const double& a, const double& b, const double& c, 
+	      const double& d, const double& e, const double& f,
+	      const double& g, const double& h, const double& i,
+	      const double& j, const double& k, const double& l,
+	      const double& m, const double& n, const double& o,
+	      const double& p, const double& q, const double& r,
+	      const double& s, const double& t, const double& u,
+	      const double& v, const double& w, const double& x,
+	      const double& y, const double& z){ 
+      Matrix newdata(26, 1);
+	newdata.data[0] = a;
+	newdata.data[1] = b;
+	newdata.data[2] = c;
+	newdata.data[3] = d;
+	newdata.data[4] = e;
+	newdata.data[5] = f;
+	newdata.data[6] = g;
+	newdata.data[7] = h;
+	newdata.data[8] = i;
+	newdata.data[9] = j;
+	newdata.data[10] = k;
+	newdata.data[11] = l;
+	newdata.data[12] = m;
+	newdata.data[13] = n;
+	newdata.data[14] = o;
+	newdata.data[15] = p;
+	newdata.data[16] = q;
+	newdata.data[17] = r;
+	newdata.data[18] = s;
+	newdata.data[19] = t;
+	newdata.data[20] = u;
+	newdata.data[21] = v;
+	newdata.data[22] = w;
+	newdata.data[23] = x;
+	newdata.data[24] = y;
+	newdata.data[25] = z;
+	
+	return newdata;
+    }
+    
+    
+    
+//  FUNCTION: Transpose  - computes the transpose of a Matrix
+/*!
+ * \brief Computes the transpose of the given Matrix.
+ * 
+ * Computes the transpose of the given Matrix.
+ * \param old_matrix a constant reference to a Matrix object.  
+ * This Matrix will be transposed.
+ * \return A Matrix object, the transpose of the input Matrix object.
+ */
+// #ifdef __NATE__
+Matrix t (const Matrix & old_matrix)
+{
+  int newrowsize = old_matrix.colsize;
+  int newcolsize = old_matrix.rowsize;
+  Matrix temp(newrowsize, newcolsize);
+  for (int i = 0; i < newcolsize; ++i) {
+    for (int j = 0; j < newrowsize; ++j) {
+      temp.data[i + newcolsize * j] = old_matrix.data[j + newrowsize * i];
+    }
+  }
+  return temp;
+}
+    
+/*!
+ * \brief Creates a Matrix of Ones
+ *
+ * Creates a Matrix filled with Ones, given a specified size.
+ * \param rows a constant int reflecting the number of rows in the Matrix.
+ * \param cols a constant int reflecting the number of columns in the Matrix.
+ * \return a new Matrix filled with 1's.
+ */
+  Matrix Matrix::ones (const int& rows, const int& cols)
+ {
+   if (rows < 1 || cols < 1) {
+     error("improper row or column dimension in ones()");
+   }
+   Matrix newdata(rows, cols);
+   int size = rows * cols;
+      for (int i = 0; i < size; ++i) {
+	newdata.data[i] = 1.0;
+      }
+      return newdata;
+ }
+
+    
+/*!
+ * \brief Creates a Matrix of Zeros
+ *
+ * Creates a Matrix filled with Zeros, given a specified size.
+ * \param rows a constant int reflecting the number of rows in the Matrix.
+ * \param cols a constant int reflecting the number of columns in the Matrix.
+ * \return a new Matrix filled with 1's.
+ */
+// #ifdef __NATE__
+  Matrix Matrix::zeros (const int& rows, const int& cols)
+{
+  if (rows < 1 || cols < 1) {
+    error("Error 0018: improper row or column dimension in ones()");
+  }
+  Matrix temp(rows, cols); // ctor zeros data
+  return temp;
+} // end of zeros
+    
+//  FUNCTION: Eye - creates an Identity Matrix of size k x k
+/*! 
+ * \brief Creates an Identity Matrix
+ *
+ * Creates an Identity Matrix of size \a k \a x \a k.
+ * \param k a constant integer reflecting the length and width 
+ * of the identity matrix.
+ * \return the Identity Matrix
+ */
+    Matrix eye (const int& k)
+    {
+      Matrix newdata(k, k);
+	double hold;
+	for (int i = 0; i < k; ++i) {
+	    for (int j = 0; j < k; ++j) {
+		if (i == j)
+		    hold = 1.0;
+		else
+		    hold = 0.0;
+		newdata.data[k * i + j] = hold;
+	    }
+	}
+	return newdata;
+    }
+    
+/*! 
+ * \brief Creates a Vector-additive sequence Matrix
+ *
+ * Creates a Vector-additive sequence Matrix of (\a size x 1)
+ * \param start a constant double reflecting the start value of 
+ * the first element in the vector.
+ * \param incr a double constant reflecting the incremental step 
+ * value between each matrix element.
+ * \param size a constant integer reflecting the size of the vector.
+ * \return a new Matrix (vector).
+ */
+Matrix Matrix::seqa (const double& start, const double& incr, const int& size)
+    {
+      Matrix newdata(size, 1);
+	double val = start;
+	for (int i = 0; i < size; ++i) {
+	    newdata.data[i] = val;
+	    val += incr;
+	}
+	return newdata;
+    }
+    
+    
+/*! 
+ * \brief Sorts all elements of a Matrix (not column by column) using 
+ * shellsort
+ *
+ * Sorts all elements of a Matrix (not column by column) using shellsort
+ * \param A the Matrix to be sorted.
+ * \return a new Matrix the same size as the original in 
+ * which all elements have been sorted.
+ */
+    Matrix sort(const Matrix& A){
+	int i, j, h;
+	double v;
+	
+	Matrix newdata(A.rowsize, A.colsize);
+	for (i = 0; i<A.size; ++i)
+	    newdata.data[i] = A.data[i];
+	for (h = 1; h <= A.size/9; h = 3*h+1);
+	for (; h > 0; h /= 3)
+	    for (i = h+1; i <= A.size; i += 1){
+		v = newdata.data[i-1]; 
+		j = i;
+		while (j>h && newdata.data[j-h-1] > v)
+		{newdata.data[j-1] = newdata.data[j-h-1]; j -= h;}
+		newdata.data[j-1] = v;
+	    }
+	return newdata;     
+    }
+    
+    
+    
+/*! 
+ * \brief Sorts all columns of a Matrix using shellsort
+ *
+ * Sorts all columns of a Matrix using shellsort
+ * \param A the Matrix to be sorted.
+ * \return a new Matrix the same size as the original in 
+ * which all elements have been sorted.
+ */
+    Matrix sortc(const Matrix& A){
+	int i, j, h;
+	double v;
+	
+	Matrix newdata(A.rowsize, A.colsize);
+	for (i = 0; i<A.size; ++i)
+	    newdata.data[i] = A.data[i];
+	
+	for (int colindex=0; colindex<A.colsize; ++colindex){
+	    
+	    for (h = 1; h <= A.rowsize/9; h = 3*h+1);
+	    for (; h > 0; h /= 3)
+		for (i = h+1; i <= A.rowsize; i += 1){
+		    v = newdata.data[(i-1)*A.colsize + colindex]; 
+		    j = i;
+		    while (j>h && newdata.data[(j-h-1)*A.colsize + colindex] > v){
+			newdata.data[(j-1)*A.colsize + colindex] = 
+			    newdata.data[(j-h-1)*A.colsize + colindex]; 
+			j -= h;
+		    }
+		    newdata.data[(j-1)*A.colsize + colindex] = v;
+		}
+	    
+	}
+	return newdata;     
+    }
+    
+    
+//  4/29/2001 (KQ)
+/*! 
+ * \brief Interchanges the rows of \a A with those in vector \a p
+ *
+ * Interchanges the rows of \a A with those in vector \a p and 
+ * returns the modified Matrix. Useful for putting \a A into the form 
+ * of its permuted LU factorization.
+ * \param A a constant reference to the Matrix \a A.
+ * \param pp a constant reference to the Matrix (vector) \a p from 
+ * which the interchange row will come from.
+ * \return the modified Matrix \a A.
+ */
+    Matrix row_interchange(const Matrix& A, const Matrix& pp){
+	Matrix PA = A;
+	Matrix p = pp;
+	if (p.colsize != 1){
+	  error("Vector p not a column vector in row_interchange()");
+	}
+	if ( (p.rowsize +1) != A.rowsize){
+	  error("Matrices A and p not of consistent sizes in row_interchange()");
+	}
+	
+	for (int i=0; i<(A.rowsize-1); ++i){
+	    //swap A(i,.) and A(p[i],.)
+	    int swap_row = static_cast<int>(p.data[i]);
+	    for (int j=0; j<A.colsize; ++j){
+		double temp = PA.data[j+A.colsize*i];
+		PA.data[j+A.colsize*i] = PA.data[j+A.colsize*swap_row];
+		PA.data[j+A.colsize*swap_row] = temp;
+	    }
+	}
+	
+	return PA;
+    }
+    
+    
+//  4/29/2001 (KQ)
+/*! 
+ * \brief Calculate the Inverse of a square Matrix \a A
+ *
+ * Calculate the Inverse of a square Matrix \a A via LU decomposition.
+ * \param AA a constant reference to the Matrix \a A to be inverted.
+ * \return the inverted Matrix \a A.
+ */
+    Matrix inv (const Matrix & AA)
+    {
+	if (AA.rowsize != AA.colsize){
+	  error("Matrix A not square in SCYTHE::inv()");
+	}
+	
+	Matrix b = Matrix (AA.rowsize, 1); 
+	Matrix Ainv = Matrix(AA.rowsize, AA.rowsize);    
+	
+	// step 1 compute the LU factorization 
+	// taken from lu_decomp()
+	Matrix A = AA;
+	Matrix L, U, perm_vec;
+	
+	if (A.rowsize == 1){
+	  L = Matrix::ones(1,1);
+	  U = AA;
+	  perm_vec = Matrix(1,1);
+	} else {
+	    L = U = Matrix(A.rowsize, A.rowsize);
+	    perm_vec = Matrix(A.rowsize-1,1);
+	    
+	    for (int k=0; k<A.rowsize-1; ++k){
+		int pivot = k;
+		// find pivot
+		for (int i=k; i<A.rowsize; ++i){
+		    if ( std::fabs(A(pivot,k)) < std::fabs(A(i,k)) ) pivot = i;  
+		}
+		
+		if(A(pivot,k) == 0.0){
+		  error("Matrix A is singular in SCYTHE::inv()");
+		}
+		
+		// permute 
+		if (k != pivot){
+		    for (int i=0; i<A.rowsize; ++i){
+			double temp = A(pivot,i);
+			A(pivot,i) = A(k,i);
+			A(k,i) = temp;
+		    }
+		}
+		perm_vec[k] = pivot;
+		
+		for (int i = k+1; i<A.rowsize; ++i){
+		    A(i,k) = A(i,k)/A(k,k);
+		    for (int j = k+1; j <A.rowsize; ++j){
+			A(i,j) = A(i,j) - A(i,k)*A(k,j);
+		    }
+		}
+	    }
+	    
+	    L = A; 
+	    for (int i=0; i<A.rowsize; ++i){
+		for (int j=i; j<A.rowsize; ++j){
+		    U(i,j) = A(i,j);
+		    L(i,j) = 0.0;
+		    L(i,i) = 1.0;
+		}
+	    }
+	}
+	
+	// step 2 repeated solving of A*hold = b
+	for (int j = 0; j < A.rowsize; ++j) {
+	    b.data[j] = 1.0;
+	    //Matrix hold = lu_solve(A, b, L, U, p);
+	    
+	    // step 2.1 solve L*y = Pb via forward substitution
+	    Matrix bb = row_interchange(b, perm_vec);
+	    Matrix y = Matrix(A.rowsize,1);
+	    for (int i=0; i<A.rowsize; ++i){
+		double sum = 0.0;
+		for (int j=0; j<i; ++j)
+		    sum += L.data[j+A.colsize*i]*y.data[j];
+		y.data[i] = (bb.data[i] - sum)/L.data[i+A.colsize*i];
+	    }
+	    
+	    // step 2.2 solve U*x = y via backsubstitution
+	    Matrix x = Matrix(A.rowsize,1);
+	    for (int i=A.rowsize-1; i>=0; --i){
+		double sum = 0.0;
+		for (int j=i+1; j<A.rowsize; ++j)
+		    sum += U.data[j+A.colsize*i] * x.data[j];
+		x.data[i] = (y.data[i] - sum)/U.data[i+A.colsize*i];
+	    }
+	    
+	    // step 3 reset b and put the solution in Ainv
+	    b.data[j] = 0.0;
+	    for (int k=0; k<A.rowsize; ++k)
+		Ainv(k,j) = x[k];
+	}
+	
+	return Ainv;
+    }
+    
+    
+//  NOTE: LU decomposition algorithm is based on  Algorithm 3.4.1 
+//      of Golub and Van Loan 3rd edition, 1996. 
+/*! 
+ * \brief Calculate the determinant of a square Matrix \a A
+ *
+ * Calculate the determinant of a square Matrix \a A via LU decomposition.
+ * \param AA a constant reference to the Matrix.
+ * \return the determinant of \a A.
+ */
+    double det(const Matrix& AA){
+	
+	Matrix A = AA;
+	
+	if (A.rowsize != A.colsize){
+	  error("Matrix A not square in SCYTHE::det()");
+	}
+	
+	if(A.rowsize == 1)
+	    return A(0,0);
+	
+	Matrix L = Matrix(A.rowsize, A.rowsize);
+	Matrix U = L;
+	double sign = 1.0;
+	
+	for (int k=0; k<A.rowsize-1; ++k){
+	    int pivot = k;
+	    // find pivot
+	    for (int i=k; i<A.rowsize; ++i){
+		if ( A(pivot,k) < std::fabs(A(i,k)) ) pivot = i;  
+	    }
+	    
+	    if(A(pivot,k) == 0.0){
+		return 0.0;
+	    }
+	    
+	    // permute 
+	    if (k != pivot){
+		sign = -1*sign;
+		for (int i=k; i<A.rowsize; ++i){
+		    double temp = A(pivot,i);
+		    A(pivot,i) = A(k,i);
+		    A(k,i) = temp;
+		}
+	    }
+	    
+	    for (int i = k+1; i<A.rowsize; ++i){
+		A(i,k) = A(i,k)/A(k,k);
+		for (int j = k+1; j <A.rowsize; ++j){
+		    A(i,j) = A(i,j) - A(i,k)*A(k,j);
+		}
+	    }
+	}
+	
+	double det = 1.0;
+	for (int i = 0; i<A.rowsize; ++i)
+	    det = det*A(i,i);
+	
+	return sign*det;
+    }
+    
+//! Column bind 2 matrices
+/*!
+ * Column bind 2 matrices,\a A and \a B.
+ * \param A a constant reference to a Matrix \a A.
+ * \param B a constant reference to a Matrix \a B.
+ * \return the new Matrix \a A
+ */
+    Matrix cbind (const Matrix & A, const Matrix & B)
+    {
+	if (A.rowsize != B.rowsize) {
+	  error("Matrices A and B do not have some number of rows in SCYTHE::cbind()");
+	}
+	
+	int totalcols = A.colsize + B.colsize;
+	//double *newdata = new double[A.rowsize * totalcols];
+	Matrix newdata(A.rowsize, totalcols);
+	
+	for (int i = 0; i < A.rowsize; ++i) {
+	    for (int j = 0; j < A.colsize; ++j) {
+		newdata.data[i * totalcols + j] = A.data[i * A.colsize + j];
+	    }
+	    for (int k = 0; k < B.colsize; ++k) {
+		newdata.data[i * totalcols + k + A.colsize] = B.data[i * B.colsize + k];
+	    }
+	}
+	
+	return newdata;
+    }
+    
+//! Row bind 2 matrices
+/*!
+ * Row bind 2 matrices,\a A and \a B.
+ * \param A a constant reference to a Matrix \a A.
+ * \param B a constant reference to a Matrix \a B.
+ * \return the new Matrix \a A.
+ */
+    Matrix rbind (const Matrix & A, const Matrix & B)
+    {
+	if (A.colsize != B.colsize) {
+	  error("Matrices A and B do not have some number of cols in SCYTHE::rbind()");
+	}
+	
+	int totalrows = A.rowsize + B.rowsize;
+	//double *newdata = new double[totalrows * A.colsize];
+	Matrix newdata(totalrows, A.colsize);
+	
+	for (int i = 0; i < A.rowsize; ++i) {
+	    for (int j = 0; j < A.colsize; ++j)  {
+		newdata.data[i * A.colsize + j] = A.data[i * A.colsize + j];
+	    }
+	}
+	for (int k = 0; k < B.rowsize; ++k) {
+	    for (int j = 0; j < B.colsize; ++j) {
+		newdata.data[k * B.colsize + (A.rowsize * A.colsize) + j] =
+		    B.data[k * B.colsize + j];
+	    }
+	}
+	
+	return newdata;
+    }
+    
+//! Calculate the sum of each column of a Matrix
+/*!
+ * Calculate the sum of each column of a Matrix.  
+ * Returns the row vector of sums.
+ * \param A a constant reference to a Matrix \a A.
+ * \return the vector of sums for each corresponding column.
+ */
+// #ifdef __NATE__
+Matrix sumc (const Matrix & A)
+{
+  Matrix temp = Matrix::zeros(1, A.colsize);
+  
+  for (int i = 0; i < A.rowsize; ++i) {
+    double *rowptr = A.data + (A.colsize * i);
+    for (int j = 0; j < A.colsize; ++j) {
+      temp.data[j] += rowptr[j];
+    }
+  }
+  return temp;
+}
+
+    
+//! Calculate the product of each column of a Matrix
+/*!
+ * Calculate the product of each column of a Matrix.  
+ * Returns the row vector of products.
+ * \param A a constant reference to a Matrix \a A.
+ * \return the vector of products for each corresponding column.
+ */
+    Matrix prodc (const Matrix & A)
+    {
+      Matrix newdata(1, A.colsize);
+	
+	for (int i = 0; i < A.colsize; ++i)
+	    newdata.data[i] = 1.0;
+	
+	for (int i = 0; i < A.rowsize; ++i) {
+	    for (int j = 0; j < A.colsize; ++j) {
+		newdata.data[j] = newdata.data[j] * A.data[A.colsize * i + j];
+	    }
+	}
+	
+	return newdata;
+    }
+    
+//! Calculate the mean of each column of a Matrix
+/*!
+ * Calculate the mean of each column of a Matrix.  
+ * Returns the row vector of means.
+ * \param A a constant reference to a Matrix \a A.
+ * \return the vector of means for each corresponding column.
+ */
+    Matrix meanc (const Matrix & A)
+    {
+      Matrix newdata(1, A.colsize);
+	for (int i = 0; i < A.colsize; ++i)
+	    newdata.data[i] = 0.0;
+	
+	for (int i = 0; i < A.rowsize; ++i) {
+	    for (int j = 0; j < A.colsize; ++j) {
+		newdata.data[j] += A.data[A.colsize * i + j];
+	    }
+	}
+	for (int i = 0; i < A.colsize; ++i) {
+	    newdata.data[i] = (1.0 / A.rowsize) * newdata[i];
+	}
+	
+	return newdata;
+    }
+    
+//! Calculate the variances of each column of a Matrix
+/*!
+ * Calculate the variances of each column of a Matrix.  
+ * Returns the row vector of variances.
+ * \param A a constant reference to a Matrix \a A.
+ * \return the vector of variances for each corresponding column.
+ */
+    Matrix varc (const Matrix & A)
+    {
+	Matrix mu = meanc (A);
+	Matrix newdata(1, A.colsize);
+	for (int i = 0; i < A.colsize; ++i)
+	    newdata.data[i] = 0.0;
+	
+	for (int i = 0; i < A.rowsize; ++i) {
+	    for (int j = 0; j < A.colsize; ++j) {
+		newdata.data[j] += std::pow (mu.data[j] - A.data[A.colsize * i + j], 2) *
+		    (1.0 / (A.rowsize-1));
+	    }
+	}
+	
+	return newdata;
+    }
+    
+//! Calculate the standard deviation of each column of a Matrix
+/*!
+ * Calculate the standard deviation of each column of a Matrix.  
+ * Returns the row vector of standard deviations.
+ * \param A a constant reference to a Matrix \aA.
+ * \return the vector of standard deviations for each corresponding column.
+ */
+    Matrix stdc (const Matrix & A)
+    {
+	Matrix mu = meanc (A);
+	Matrix newdata(1, A.colsize);
+	for (int i = 0; i < A.colsize; ++i)
+	    newdata.data[i] = 0.0;
+	
+	for (int i = 0; i < A.rowsize; ++i) {
+	    for (int j = 0; j < A.colsize; ++j) {
+		newdata.data[j] += std::pow (mu.data[j] - A.data[A.colsize * i + j], 2) *
+		    (1.0 / (A.rowsize-1));
+	    }
+	}
+	
+	for (int i = 0; i < A.colsize; ++i)
+	    newdata.data[i] = std::sqrt (newdata[i]);
+	
+	return newdata;
+    }
+    
+//! Calculate the square root of each element of a Matrix
+/*!
+ * Calculate the square root of each element of a Matrix.
+ * \param A a constant reference to a Matrix \a A.
+ * \return the Matrix of square roots.
+ */
+    Matrix sqrt (const Matrix & A)
+    {
+      Matrix newdata(A.rowsize, A.colsize);
+	
+	for (int i = 0; i < A.size; ++i)
+	    newdata.data[i] = std::sqrt (A.data[i]);
+	
+	return newdata;
+    }
+    
+//! Calculate the absolute value of each element of a Matrix
+/*!
+ * Calculate the absolute value of each element of a Matrix.
+ * \param A a constant reference to a Matrix \a A.
+ * \return the Matrix of absolute values.
+ */
+    Matrix fabs (const Matrix & A)
+    {
+      Matrix newdata(A.rowsize, A.colsize);
+	
+	for (int i = 0; i < A.size; ++i)
+	    newdata.data[i] = std::fabs (A.data[i]);
+	
+	return newdata;
+    }
+    
+    
+//! Calculate the value of \a e^x for each individual Matrix element
+/*!
+ * Calculate the value of \a e^x for each individual Matrix element.
+ * \param A a constant reference to a Matrix \a A.
+ * \return the new Matrix of exponentials.
+ */
+    Matrix exp(const Matrix& A){
+      Matrix newdata(A.rowsize, A.colsize);
+	
+	for (int i = 0; i < A.size; ++i)
+	    newdata.data[i] = std::exp (A.data[i]);
+	
+	return newdata;
+    }
+    
+//! Calculate the natural log of each individual Matrix element
+/*!
+ * Calculate the natural log of each individual Matrix element.
+ * \param A a constant reference to a Matrix \a A.
+ * \return the new Matrix of natural logs.
+ */
+    Matrix log(const Matrix& A){
+      Matrix newdata(A.rowsize, A.colsize);
+	
+	for (int i = 0; i < A.size; ++i)
+	    newdata.data[i] = std::log (A.data[i]);
+	
+	return newdata;
+    }
+    
+//! Calculate the Base 10 Log of each Matrix element
+/*!
+ * Calculate the Base 10 Log of each Matrix element.
+ * \param A a constant reference to a Matrix \a A.
+ * \return the new Matrix of Base 10 logs.
+ */
+    Matrix log10(const Matrix& A){
+      Matrix newdata(A.rowsize, A.colsize);
+
+	for (int i = 0; i < A.size; ++i)
+	    newdata.data[i] = std::log10(A.data[i]);
+	
+	return newdata;
+    }
+    
+//! Raises each Matrix element to a specified power
+/*!
+ * Raises each Matrix element to a specified power.
+ * \param A a constant reference to a Matrix \a A.
+ * \return the new modified Matrix.
+ */
+    Matrix pow(const Matrix& A, const double& e){
+      Matrix newdata(A.rowsize, A.colsize);
+	
+	for (int i = 0; i < A.size; ++i)
+	    newdata.data[i] = std::pow(A.data[i], e);
+	
+	return newdata;
+    }
+    
+    
+//! Calculates the maximum element in a Matrix
+/*!
+ * Calculates the maximum element in a Matrix.
+ * \param A a constant reference to a Matrix \a A.
+ * \return the maximum element (a double).
+ */
+    double max (const Matrix & A)
+    {
+	double max = A.data[0];
+	for (int i = 1; i < A.size; ++i) {
+	    if (A.data[i] > max)
+		max = A.data[i];
+	}
+	return max;
+    }
+    
+//! Calculates the minimum element in a Matrix
+/*!
+ * Calculates the minimum element in a Matrix.
+ * \param A a constant reference to a Matrix \a A.
+ * \return the minimum element (a double).
+ */
+    double min (const Matrix & A)
+    {
+	double min = A.data[0];
+	for (int i = 1; i < A.size; ++i) {
+	    if (A.data[i] < min)
+		min = A.data[i];
+	}
+	return min;
+    }
+    
+//! Calculates the maximum of each Matrix column
+/*!
+ * Calculates the maximum of each Matrix column.
+ * \param A a constant reference to a Matrix \a A.
+ * \return a Matrix (vector) of the maximum elements.
+ */
+    Matrix maxc (const Matrix & A)
+    {
+      Matrix newdata(1, A.colsize);
+	
+	for (int i = 0; i < A.rowsize; ++i) {
+	    for (int j = 0; j < A.colsize; ++j) {
+		if (i == 0) {
+		    newdata.data[j] = A.data[A.colsize * i + j];
+		} else if (A.data[A.colsize * i + j] > newdata.data[j]) {
+		    newdata.data[j] = A.data[A.colsize * i + j];
+		}
+	    }
+	}
+	
+	return newdata;
+    }
+    
+//! Calculates the minimum of each Matrix column
+/*!
+ * Calculates the minimum of each Matrix column.
+ * \param A a constant reference to a Matrix \a A.
+ * \return a Matrix (vector) of the minimum elements.
+ */
+    Matrix minc (const Matrix & A)
+    {
+      Matrix newdata(1, A.colsize);
+	
+	for (int i = 0; i < A.rowsize; ++i) {
+	    for (int j = 0; j < A.colsize; ++j) {
+		if (i == 0) {
+		    newdata.data[j] = A.data[A.colsize * i + j];
+		} else if (A.data[A.colsize * i + j] < newdata.data[j]) {
+		    newdata.data[j] = A.data[A.colsize * i + j];
+		}
+	    }
+	}
+	return newdata;
+    }
+    
+    
+//! Finds the index of the maximum of each Matrix column
+/*!
+ * Finds the index of the maximum of each Matrix column.
+ * \param A a constant reference to a Matrix \a A.
+ * \return a Matrix (vector) of the index of each maximum element.
+ */
+    Matrix maxindc(const Matrix& A){
+      Matrix newdata(1, A.colsize);
+	Matrix maxvec = Matrix(1,A.colsize);
+	
+	for (int i = 0; i < A.rowsize; ++i){
+	    for (int j = 0; j < A.colsize; ++j){
+		if (i == 0){
+		    maxvec[j] = A.data[A.colsize * i + j]; 
+		    newdata.data[j] = 0;
+		} else if (A.data[A.colsize * i + j] > maxvec[j]){
+		    maxvec[j] = A.data[A.colsize * i + j];
+		    newdata.data[j] = i;
+		}
+	    }
+	}
+	return newdata;
+    }
+    
+    
+//! Finds the index of the minimum of each Matrix column
+/*!
+ * Finds the index of the minimum of each Matrix column.
+ * \param A a constant reference to a Matrix \a A.
+ * \return a Matrix (vector) of the index of each minimum element.
+ */
+    Matrix minindc(const Matrix& A){
+        Matrix newdata(1, A.colsize);
+	Matrix minvec = Matrix(1,A.colsize);
+	
+	for (int i = 0; i < A.rowsize; ++i){
+	    for (int j = 0; j < A.colsize; ++j){
+		if (i == 0){
+		    minvec[j] = A.data[A.colsize * i + j]; 
+		    newdata.data[j] = 0;
+		} else if (A.data[A.colsize * i + j] < minvec[j]){
+		    minvec[j] = A.data[A.colsize * i + j];
+		    newdata.data[j] = i;
+		}
+	    }
+	}
+	return newdata;
+    }
+    
+    
+//! Calculates the order of each element in a Matrix
+/*!
+ * Calculates the order of each element in a Matrix.
+ * \param A a constant reference to a Matrix A.
+ * \return a Matrix (vector) in which the \e i'th element 
+ * gives the order position of the \e i'th element of \a A.
+ */
+    Matrix order(const Matrix& A){
+	if (A.colsize != 1){
+	  error("Matrix A not a column vector in SCYTHE::order()");
+	}
+	Matrix newdata(A.rowsize, 1);
+	
+	for (int i=0; i<A.rowsize; ++i){
+	    newdata.data[i] = sumc(A << A.data[i])[0];    
+	}
+	
+	return newdata;
+    }
+    
+    
+//! Selects all the rows of Matrix \a A for which binary column vector \a e has an element equal to 1
+/*!
+ * Selects all the rows of Matrix \a A for which binary column 
+ * vector \a e has an element equal to 1.
+ * \param A a constant reference to a Matrix \a A (n x k).
+ * \param e a constant reference to a vector \a e (n x 1).
+ * \return a Matrix of all rows of \a A for \a e equal to one.
+ */
+    Matrix selif(const Matrix& A, const Matrix& e){
+	
+	// check to see if rowsize matches  
+	if (A.rowsize != e.rowsize){
+	  error("Matrices not conformable in SCYTHE::selif()");
+	}
+	
+	// check to see if e is a column vector
+	if (e.colsize > 1){
+	  error("Not a column vector in SCYTHE::selif()");
+	}
+	
+	// loop to check if e contains binary data, and count number
+	// of output rows 
+	int N = 0;
+	for (int i=0; i<e.rowsize; ++i){
+	    if (e.data[i] != 0 && e.data[i] != 1){
+	      error("Vector contains non binary data in SCYTHE::selif()");
+	    }
+	    if (e.data[i] == 1) {
+		N += 1;
+	    }
+	}
+	
+	// declare and form output Matrix
+	Matrix newdata(N, A.colsize);
+	int count = 0;
+	for (int i=0; i<A.rowsize; ++i){
+	    if (e.data[i] == 1){
+		for (int j=0; j<A.colsize; ++j){
+		    newdata.data[count] = A.data[A.colsize*i + j]; 
+		    ++count;
+		}
+	    }
+	}
+	return newdata;
+    }
+    
+    
+//! Finds unique elements in a Matrix
+/*!
+ * Finds unique elements in a Matrix.
+ * \param A a constant reference to a Matrix \a A.
+ * \return a Matrix of all unique elements.
+ */
+    Matrix unique(const Matrix& A){
+      // double *newdata = new double[A.size];
+      double *newdata = (double *) malloc( (A.size)*sizeof(double));
+	
+	newdata[0] = A.data[0];
+	int count = 1;
+	for (int i=1; i<A.size; ++i){
+	    int uniq = 1;
+	    for (int j=0; j<count; ++j){
+		if (newdata[j] == A.data[i]){
+		    uniq = 0;
+		    break;
+		}
+	    }
+	    if (uniq==1){
+		newdata[count] = A.data[i];
+		++count;
+	    }
+	}
+	
+	Matrix temp = Matrix(newdata, count, 1);
+	// delete[] newdata;
+	free(newdata);
+	return temp;
+    }
+    
+//! Turn Matrix into Column vector by stacking columns
+/*!
+ * Turn Matrix into Column vector by stacking columns. 
+ * NOTE: \e Vecr() is much faster than \e Vecc().
+ * \param A a constant reference to a Matrix \a A.
+ * \return a Column vector.
+ */
+    Matrix vecc(const Matrix& A){
+	// first transposes the input Matrix's data 
+	int newrowsize = A.colsize;
+	int newcolsize = A.rowsize;
+	Matrix newdata(A.size, 1);
+	for (int i = 0; i < newcolsize; ++i) {
+	    for (int j = 0; j < newrowsize; ++j) {
+		newdata.data[i + newcolsize * j] = A.data[j + newrowsize * i];
+	    }
+	}
+	// then takes this transposed data and vecrs
+	return newdata;
+    }
+    
+    
+//! Reshapes a row major order Matrix or Vector
+/*!
+ * Reshapes a row major order Matrix or Vector.
+ * \param A a constant reference to a Matrix \a A.
+ * \param r a constant integer reflecting the new number of rows.
+ * \param c a constant integer reflecting the new number of columns.
+ * \return a new Matrix with the specified dimensions.
+ */
+    Matrix reshape(const Matrix& A, const int r, const int c){
+	if (A.size != r*c){
+	  error("Input dimensions to SCYTHE::reshape() not consistent with size of input Matrix");
+	}
+	Matrix temp = Matrix(A.data, r, c);
+	return temp;
+    }
+    
+//! Make vector out of unique elements of a symmetric Matrix
+/*!
+ * Make vector out of unique elements of a symmetric Matrix.  
+ * NOTE: DOES NOT CHECK FOR SYMMETRY!!!
+ * \param A a constant reference to a Matrix \a A.
+ * \return a Column vector.
+ */
+    Matrix vech(const Matrix& A){
+	if (A.rowsize != A.colsize){
+	  error("Input Matrix not square in SCYTHE::vech()");
+	}
+	
+	int newsize = static_cast<int>(0.5*(A.size - A.rowsize) + A.rowsize);
+	Matrix newdata(newsize, 1);
+	int count = 0;
+	for (int i=0; i<A.rowsize; ++i){
+	    for(int j=i; j<A.colsize; ++j){
+		newdata.data[count] = A.data[i*A.colsize + j];
+		++count;
+	    }
+	}
+	
+	return newdata;
+    }
+    
+    
+//! Get symmetric Matrix B back from \a A = \a vech(B)
+/*!
+ * Get symmetric Matrix \a B back from \a A = \a vech(B)
+ * \param A a constant reference to a Matrix \a A.
+ * \return a Symmetric Matrix.
+ */
+/* 
+    Matrix xpnd(const Matrix& A){
+	double newrowsize_d = -.5 + .5*std::sqrt(1+8*A.size);
+	if (fmod(newrowsize_d,1.0) != 0.0){
+	    error("Not possible to make square Matrix out of input Matrix to SCYTHE::xpnd()");
+	}
+	int newrowsize = static_cast<int>(newrowsize_d);
+	Matrix newdata(newrowsize, newrowsize);
+	int count = 0;
+	for (int i=0; i<newrowsize; ++i){
+	    for (int j=i; j<newrowsize; ++j){
+		newdata.data[i*newrowsize +j] = newdata.data[j*newrowsize + i] = A.data[count];
+		++count;
+	    }
+	}
+	return newdata;
+    }
+*/
+    
+    
+//! Get the diagonal of a Matrix
+/*!
+ * Get the diagonal of a Matrix.
+ * \param A a constant reference to a Matrix \a A.
+ * \return a Matrix (vector) containing the diagonal of \a A.
+ */
+    Matrix diag(const Matrix& A){
+	if (A.rowsize != A.colsize){
+	  error("Matrix is not square in SCYTHE::diag()");
+	}
+	Matrix newdata(A.rowsize, 1);
+	for (int i=0; i<A.rowsize; ++i){
+	    newdata.data[i] = A.data[i*A.colsize + i];
+	}
+	return newdata;
+    }
+    
+    
+//! Fast calculation of \a A * \a B + \a C
+/*!
+ * Fast calculation of \a A * \a B + \a C
+ * \param A a constant reference to a Matrix \a A.
+ * \return the final Matrix (the value of \a A * \a B + \a C).
+ */
+    Matrix gaxpy(const Matrix& A, const Matrix& B, const Matrix& C){
+	// Case 1: A is 1 x 1 and B is n x k
+	if (A.rowsize == 1 && A.colsize == 1) {
+	    if (B.rowsize == C.rowsize && B.colsize == C.colsize){
+	      Matrix prod(B.rowsize, B.colsize);
+		for (int i = 0; i < B.size; ++i) {
+		    prod.data[i] = A.data[0] * B.data[i] + C.data[i];
+		}
+		return prod;
+	    } else {
+	      error("A*B and C not conformable in SCYTHE::gaxpy()");
+	    }
+	} else if (B.rowsize == 1 && B.colsize == 1) {
+	    // Case 2: A is n x k and B is 1 x 1
+	    if (A.rowsize == C.rowsize && A.colsize == C.colsize){
+	      Matrix prod(A.rowsize, A.colsize);
+		for (int i = 0; i < A.size; ++i) {
+		    prod.data[i] = A.data[i] * B.data[0] + C.data[i];
+		}
+		return prod;
+	    } else {
+	      error("A*B and C not conformable in SCYTHE::gaxpy()");
+	    }
+	} else if (A.colsize != B.rowsize) {
+	    // Case 3: A is n x k and B is m x j (m !=j)
+	  error("Matrices not conformable for multiplication in SCYTHE::gaxpy()");
+	} else if (A.rowsize == C.rowsize && B.colsize == C.colsize){
+	    // Case 4: A is n x k and B is k x j
+	  register Matrix newdata(A.rowsize, B.colsize);
+	    for (int i = 0; i < A.rowsize; ++i){
+		for (int j = 0; j < B.colsize; ++j){
+		    newdata.data[i*B.colsize + j] = C.data[i*B.colsize + j];
+		    for (int k = 0; k < B.rowsize; ++k){
+			newdata.data[i * B.colsize + j] += A.data[i * A.colsize + k] *
+			    B.data[k * B.colsize + j];
+		    }
+		}
+	    }
+	    
+	    return newdata;
+	} else {
+	  error("A*B and C not conformable in SCYTHE::gaxpy()");
+	}
+    }
+    
+    
+//! Fast calculation of \a A'A
+/*!
+ * Fast calculation of \a A'A
+ * \param A a constant reference to a Matrix \a A.
+ * \return the final Matrix (the value of \a A'A). 
+ */
+// original
+    Matrix crossprod(const Matrix& A){
+      register Matrix newdata(A.colsize, A.colsize);
+
+	for (int i = 0; i < A.colsize; ++i){
+	    for (int j = i; j < A.colsize; ++j){
+		newdata.data[i*A.colsize + j] = 0.0;
+		for (int k = 0; k < A.rowsize; ++k){
+		    newdata.data[i * A.colsize + j] += A.data[k * A.colsize + i] *
+			A.data[k * A.colsize + j];
+		    newdata.data[j*A.colsize + i] = newdata.data[i*A.colsize + j];
+		}
+	    }
+	}
+	
+	return newdata;
+    }
+    
+    // better loop ordering
+    Matrix crossprod2(const Matrix& A){
+      register Matrix newdata(A.colsize, A.colsize);
+	const int nr = A.rowsize;
+	const int nc = A.colsize;
+	
+	for (int k = 0; k < nr; ++k){
+	    for (int i = 0; i < nc; ++i){
+		for (int j = i; j < nc; ++j){
+		    newdata.data[i * nc + j] += A.data[k * nc + i] *
+			A.data[k * nc + j];
+		    newdata.data[j*nc + i] = newdata[i*nc + j];
+		}
+	    }
+	}
+	
+	/*
+	  for (int i = 0; i < A.colsize; ++i){
+	  for (int j = i; j < A.colsize; ++j){
+	  newdata[i*A.colsize + j] = 0.0;
+	  for (int k = 0; k < A.rowsize; ++k){
+	  newdata[i * A.colsize + j] += A.data[k * A.colsize + i] *
+	  A.data[k * A.colsize + j];
+	  newdata[j*A.colsize + i] = newdata[i*A.colsize + j];
+	  }
+	  }
+	  }
+	*/
+	
+	return newdata;
+
+    }
+    
+    
+/************************    OPERATORS     ****************************/
+    
+// ADDITION OPERATORS IN ALL THEIR MANY FLAVORS
+    
+/*!
+ * \brief OPERATOR: Addition  (Matrix + Matrix).
+ * \param A a constant reference to a Matrix \a A.
+ * \param B a constant reference to a Matrix \a B.
+ * \return the sum of the two Matrices.
+ */
+    Matrix operator + (const Matrix & A, const Matrix & B)
+    {
+	if (A.rowsize == 1 && A.colsize == 1) {
+	    // Case 1: A is 1 x 1 and B is n x k
+	  Matrix sum(B.rowsize, B.colsize);
+	    for (int i = 0; i < B.size; ++i) {
+		sum.data[i] = A.data[0] + B.data[i];
+	    }
+	    return sum;
+	} else if (B.rowsize == 1 && B.colsize == 1) {
+	    // Case 2: A is n x k and B is 1 x 1
+	  Matrix sum(A.rowsize, A.colsize);
+	    for (int i = 0; i < A.size; ++i) {
+		sum.data[i] = A.data[i] + B.data[0];
+	    }
+	    return sum;
+	} else if (A.rowsize != B.rowsize || A.colsize != B.colsize) {
+	    // Case 3: A is n x k and B is m x j (n != m or k != m)
+	  error("Matrices not conformable for addition");
+	} else {
+	    // Case 4: A is n x k and B is also n x k
+  	  Matrix sum(A.rowsize, A.colsize);
+	    for (int i = 0; i < A.size; ++i) {
+		sum.data[i] = A.data[i] + B.data[i];
+	    }
+	    return sum;
+	}
+    }
+    
+//  OPERATOR: Addition
+//  NOTE: This operator is overloaded
+//  Matrix + scalar
+/*!
+  \overload Matrix operator + (const Matrix & A, const double &b)
+*/
+    Matrix operator + (const Matrix & A, const double &b)
+    {
+      Matrix sum(A.rowsize, A.colsize);
+	for (int i = 0; i < A.size; ++i) {
+	    sum.data[i] = A.data[i] + b;
+	}
+	return sum;
+    }
+    
+//  OPERATOR: Addition
+//  NOTE: This operator is overloaded
+//  scalar + Matrix
+/*!
+  \overload Matrix operator + (const double &a, const Matrix & B)
+*/
+    Matrix operator + (const double &a, const Matrix & B)
+    {
+      Matrix sum(B.rowsize, B.colsize);
+	for (int i = 0; i < B.size; ++i) {
+	    sum.data[i] = a + B.data[i];
+	}
+	return sum;
+    }
+    
+// SUBTRACTION OPERATORS IN ALL THEIR MANY FLAVORS
+    
+/*!
+ * \brief OPERATOR: Subtraction  (Matrix - Matrix).
+ * \param A a constant reference to a Matrix \a A.
+ * \param B a constant reference to a Matrix \a B.
+ * \return the difference of the two Matrices.
+ */
+    Matrix operator - (const Matrix & A, const Matrix & B)
+    {
+	// Case 1: A is 1 x 1 and B is n x k
+	if (A.rowsize == 1 && A.colsize == 1) {
+	  Matrix sum(B.rowsize, B.colsize);
+	    for (int i = 0; i < B.size; ++i) {
+		sum.data[i] = A.data[0] - B.data[i];
+	    }
+	    return sum;
+	} else if (B.rowsize == 1 && B.colsize == 1) {
+	    // Case 2: A is n x k and B is 1 x 1
+	  Matrix sum(A.rowsize, A.colsize);
+	    for (int i = 0; i < A.size; ++i) {
+		sum.data[i] = A.data[i] - B.data[0];
+	    }
+	    return sum;
+	} else if (A.rowsize != B.rowsize || A.colsize != B.colsize) {
+	    // Case 3: A is n x k and B is m x j (n != m or k != m)
+	  error("Matrices not conformable for subtraction");
+	} else {
+	    // Case 4: A is n x k and B is also n x k
+ 	  Matrix sum(A.rowsize, A.colsize);
+	    for (int i = 0; i < A.size; ++i) {
+		sum.data[i] = A.data[i] - B.data[i];
+	    }
+	    return sum;
+	}
+    }
+    
+//  OPERATOR: Subtraction
+//  NOTE: This operator is overloaded
+//  Matrix - scalar
+/*!
+  \overload Matrix operator - (const Matrix & A, const double &b)
+*/
+    Matrix operator - (const Matrix & A, const double &b)
+    {
+        Matrix sum(A.rowsize, A.colsize);
+	for (int i = 0; i < A.size; ++i) {
+	    sum.data[i] = A.data[i] - b;
+	}
+	return sum;
+    }
+    
+//  OPERATOR: Subtraction
+//  NOTE: This operator is overloaded
+//  scalar - Matrix
+/*!
+  \overload Matrix operator - (const double &a, const Matrix & B)
+*/
+    Matrix operator - (const double &a, const Matrix & B)
+    {
+      Matrix sum(B.rowsize, B.colsize);
+	for (int i = 0; i < B.size; ++i) {
+	    sum.data[i] = a - B.data[i];
+	}
+	return sum;
+    }
+    
+// MULTIPLICATION OPERATORS IN ALL THEIR MANY FLAVORS
+    
+/*!
+ * \brief OPERATOR: Multiplication  (Matrix * Matrix).
+ * \param A a constant reference to a Matrix \a A.
+ * \param B a constant reference to a Matrix \a B.
+ * \return the product of the two Matrices.
+ */
+    Matrix operator *(const Matrix & A, const Matrix & B)
+    {
+	// Case 1: A is 1 x 1 and B is n x k
+	if (A.rowsize == 1 && A.colsize == 1) {
+	  Matrix prod(B.rowsize, B.colsize);
+	    for (int i = 0; i < B.size; ++i) {
+		prod.data[i] = A.data[0] * B.data[i];
+	    }
+	    return prod;
+	} else if (B.rowsize == 1 && B.colsize == 1) {
+	    // Case 2: A is n x k and B is 1 x 1
+	  Matrix prod(A.rowsize, A.colsize);
+	    for (int i = 0; i < A.size; ++i) {
+		prod.data[i] = A.data[i] * B.data[0];
+	    }
+	    return prod;
+	} else if (A.colsize != B.rowsize) {
+	    // Case 3: A is n x k and B is m x j (m !=j)
+	  error("Matrices not conformable for multiplication");
+	} else {
+	    // Case 4: A is n x k and B is k x j
+	  register Matrix newdata(A.rowsize, B.colsize);
+	    for (int i = 0; i < A.rowsize; ++i) {
+		for (int j = 0; j < B.colsize; ++j) {
+		    newdata.data[i*B.colsize + j] = 0.0;
+		    for (int k = 0; k < B.rowsize; ++k) {
+			newdata.data[i * B.colsize + j] += A.data[i * A.colsize + k] *
+			    B.data[k * B.colsize + j];
+		    }
+		}
+	    }
+	    
+	    return newdata;
+	}
+    }
+    
+//  OPERATOR: Multiplication
+//  NOTE: This operator is overloaded
+// Matrix * scalar
+/*!
+  \overload Matrix operator *(const Matrix & A, const double &b)
+*/
+    Matrix operator *(const Matrix & A, const double &b)
+    {
+      Matrix prod(A.rowsize, A.colsize);
+	for (int i = 0; i < A.size; ++i) {
+	    prod.data[i] = A.data[i] * b;
+	}
+	return prod;
+    }
+    
+//  OPERATOR: Multiplication
+//  NOTE: This operator is overloaded
+// scalar * Matrix
+/*!
+  \overload Matrix operator *(const double &a, const Matrix & B)
+*/
+    Matrix operator *(const double &a, const Matrix & B)
+    {
+      Matrix prod(B.rowsize, B.colsize);
+	for (int i = 0; i < B.size; ++i) {
+	    prod.data[i] = a * B.data[i];
+	}
+	return prod;
+    }
+    
+// ELEMENT BY ELEMENT DIVISION
+/*!
+ * \brief OPERATOR: Division  (Matrix / Matrix).
+ * \param A a constant reference to a Matrix \a A.
+ * \param B a constant reference to a Matrix \a B.
+ * \return the dividend of each element of the two Matrices.
+ */
+    Matrix operator / (const Matrix & A, const Matrix & B)
+    {
+	// Case 1: A is 1 x 1 and B is n x k
+	if (A.rowsize == 1 && A.colsize == 1) {
+ 	  Matrix quot(B.rowsize, B.colsize);
+	    for (int i = 0; i < B.size; ++i) {
+		quot.data[i] = A.data[0] / B.data[i];
+	    }
+	    return quot;
+	} else if (B.rowsize == 1 && B.colsize == 1) {
+	    // Case 2: A is n x k and B is 1 x 1
+  	  Matrix quot(A.rowsize, A.colsize);
+	    for (int i = 0; i < A.size; ++i) {
+		quot.data[i] = A.data[i] / B.data[0];
+	    }
+	    return quot;
+	} else if (A.rowsize != B.rowsize || A.colsize != B.colsize) {
+	    // Case 3: A is n x k and B is m x j (n != m or k != m)
+	  error("Matrices not conformable for division");
+	} else {
+	    // Case 4: A is n x k and B is also n x k
+	  Matrix quot(A.rowsize, A.colsize);
+	    for (int i = 0; i < A.size; ++i) {
+		quot.data[i] = A.data[i] / B.data[i];
+	    }
+	    return quot;
+	}
+    }
+    
+//  OPERATOR: Division
+//  NOTE: This operator is overloaded
+//  Matrix / scalar
+/*!
+  \overload Matrix operator / (const Matrix & A, const double &b)
+*/
+    Matrix operator / (const Matrix & A, const double &b)
+    {
+	
+      Matrix quot(A.rowsize, A.colsize);
+	for (int i = 0; i < A.size; ++i) {
+	    quot.data[i] = A.data[i] / b;
+	}
+	return quot;
+    }
+    
+//  OPERATOR: Division
+//  NOTE: This operator is overloaded
+//  scalar / Matrix
+/*!
+  \overload Matrix operator / (const double &a, const Matrix & B)
+*/
+    Matrix operator / (const double &a, const Matrix & B)
+    {
+	
+      Matrix quot(B.rowsize, B.colsize);
+	for (int i = 0; i < B.size; ++i) {
+	    quot.data[i] = a / B.data[i];
+	}
+	return quot;
+    }
+    
+    
+//!  OPERATOR: Kronecker multiplication
+/*!
+ * OPERATOR: Kronecker Multiplication  (Matrix % Matrix).
+ * \param A a constant reference to a Matrix \a A.
+ * \param B a constant reference to a Matrix \a B.
+ * \return the result of the Kronecker Multiplication of the 2 Matrices.
+ */
+    Matrix operator % (const Matrix& A, const Matrix& B){
+      Matrix newdata(A.rowsize*B.rowsize, A.colsize*B.colsize);
+	int count = 0;
+	for (int i=0; i<A.rowsize; ++i){
+	    for (int j=0; j<B.rowsize; ++j){
+		for (int k=0; k<A.colsize; ++k){
+		    for (int m=0; m<B.colsize; ++m){
+			newdata.data[count] = A.data[i*A.colsize + k] * B.data[j*B.colsize + m];
+			++count;
+		    }
+		}
+	    }
+	}
+	return newdata;
+    }
+    
+    
+//!  OPERATOR: Equality
+/*!
+ * OPERATOR: Equality.
+ * \param A a constant reference to a Matrix \a A.
+ * \param B a constant reference to a Matrix \a B.
+ * \return an integer, 1 if the Matrices are the same, 0 otherwise.
+ */
+    int operator == (const Matrix& A, const Matrix & B){
+	if (A.rowsize != B.rowsize || A.colsize != B.colsize) return 0;
+	for(int i=0; i<A.size; ++i){
+	    if (A.data[i] != B.data[i]) return 0;
+	}
+	return 1;
+    }
+    
+//  OPERATOR: Inequality
+/*!
+ * OPERATOR: Inequality
+ * \param A a constant reference to a Matrix \a A.
+ * \param B a constant reference to a Matrix \a B.
+ * \return an integer, 1 if the Matrices are different, 0 if they are identical.
+ */
+    int operator != (const Matrix& A, const Matrix & B){
+	return !(A==B);
+    }
+    
+//!  OPERATOR: Element-by-element Greater Than
+/*!
+ * OPERATOR: Element-by-element Greater Than.
+ * \param A a constant reference to a Matrix \a A.
+ * \param B a constant reference to a Matrix \a B.
+ * \return A Matrix of 1's and 0's, 1's if the element is 
+ * greater than the other element, 0 otherwise.
+ */
+    Matrix operator >> (const Matrix& A, const Matrix& B){
+	if (A.rowsize != B.rowsize && A.colsize != B.colsize && (B.size > 1)){
+	  error("Matrices not conformable for >> operator");
+	}
+	
+	if (A.rowsize == B.rowsize && A.colsize == B.colsize){
+	  Matrix newdata(A.rowsize, A.colsize);
+	    for (int i = 0; i<A.size; ++i){
+		newdata.data[i] = A.data[i] > B.data[i];
+	    }
+	    return newdata;
+	}
+	
+	if (A.rowsize == B.rowsize && B.colsize == 1){
+    	    Matrix newdata(A.rowsize, A.colsize);
+	    for (int i=0; i<A.rowsize; ++i){
+		for (int j=0; j<A.colsize; ++j){
+		    newdata.data[i*A.colsize + j] = A.data[i*A.colsize + j] > B.data[i];
+		}
+	    }
+	    return newdata;
+	}
+	
+	if (A.colsize == B.colsize && B.rowsize == 1){
+    	    Matrix newdata(A.rowsize, A.colsize);
+	    for (int i=0; i<A.rowsize; ++i){
+		for (int j=0; j<A.colsize; ++j){
+		    newdata.data[i*A.colsize + j] = A.data[i*A.colsize + j] > B.data[j];
+		}
+	    }
+	    return newdata;
+	}
+	
+	if (B.size == 1){
+   	    Matrix newdata(A.rowsize, A.colsize);
+	    for (int i=0; i<A.size; ++i){
+		newdata.data[i] = A.data[i] > B.data[0];
+	    }
+	    return newdata;  
+	} else {
+	  error("Matrices not conformable for >> operator");
+	}  
+    }
+    
+//  OPERATOR: Element-by-element Greater Than
+/*!
+  \overload Matrix operator >> (const Matrix& A, const double& b)
+*/
+    Matrix operator >> (const Matrix& A, const double& b){
+	Matrix newdata(A.rowsize, A.colsize);
+	for (int i=0; i<A.size; ++i){
+	    newdata.data[i] = A.data[i] > b;
+	}
+	return newdata;
+    }
+    
+//!  OPERATOR: Element-by-scalar Less Than
+/*!
+ * OPERATOR: Element-by-element Less Than.
+ * \param A a constant reference to a Matrix \a A.
+ * \param B a constant reference to a Matrix \a B.
+ * \return A Matrix of 1's and 0's, 1's if the element 
+ * is less than the other element, 0 otherwise.
+ */
+    Matrix operator << (const Matrix& A, const Matrix& B){
+	if (A.rowsize != B.rowsize && A.colsize != B.colsize && (B.size > 1)){
+	  error("Matrices not conformable for << operator");
+	}
+	
+	if (A.rowsize == B.rowsize && A.colsize == B.colsize){
+  	  Matrix newdata(A.rowsize, A.colsize);
+	    for (int i = 0; i<A.size; ++i){
+		newdata.data[i] = A.data[i] < B.data[i];
+	    }
+	    return newdata;
+	}
+	
+	if (A.rowsize == B.rowsize && B.colsize == 1){
+	  Matrix newdata(A.rowsize, A.colsize);
+	    for (int i=0; i<A.rowsize; ++i){
+		for (int j=0; j<A.colsize; ++j){
+		    newdata.data[i*A.colsize + j] = A.data[i*A.colsize + j] < B.data[i];
+		}
+	    }
+	    return newdata;
+	}
+	
+	if (A.colsize == B.colsize && B.rowsize == 1){
+	  Matrix newdata(A.rowsize, A.colsize);
+	    for (int i=0; i<A.rowsize; ++i){
+		for (int j=0; j<A.colsize; ++j){
+		    newdata.data[i*A.colsize + j] = A.data[i*A.colsize + j] < B.data[j];
+		}
+	    }
+	    return newdata;
+	}
+	
+	if (B.size == 1){
+	  Matrix newdata(A.rowsize, A.colsize);
+	    for (int i=0; i<A.size; ++i){
+		newdata.data[i] = A.data[i] < B.data[0];
+	    }
+	    return newdata;  
+	}
+	
+	else {
+	  error("Matrices not conformable for << operator");
+	}  
+    }
+    
+//  OPERATOR: Element-by-scalar Less Than
+/*!
+  \overload Matrix operator << (const Matrix& A, const double& b)
+*/
+    Matrix operator << (const Matrix& A, const double& b)
+    {
+        Matrix newdata(A.rowsize, A.colsize);
+	for (int i=0; i<A.size; ++i){
+	    newdata.data[i] = A.data[i] < b;
+	}
+	return newdata;
+    }
+    
+    
+//!  OPERATOR: Element-by-element Equality
+/*!
+ * OPERATOR: Element-by-element Equality.
+ * \param A a constant reference to a Matrix \a A.
+ * \param B a constant reference to a Matrix \a B.
+ * \return A Matrix of 1's and 0's, 1's if the elements are equal, 
+ * 0 otherwise.
+ */
+    Matrix operator ^= (const Matrix& A, const Matrix& B){
+	if (A.rowsize != B.rowsize && A.colsize != B.colsize && (B.size > 1)){
+	  error("Matrices not conformable for ^= operator");
+	}
+	
+	if (A.rowsize == B.rowsize && A.colsize == B.colsize){
+	  Matrix newdata(A.rowsize, A.colsize);
+	    for (int i = 0; i<A.size; ++i){
+		newdata.data[i] = A.data[i] == B.data[i];
+	    }
+	    return newdata;
+	}
+	
+	if (A.rowsize == B.rowsize && B.colsize == 1){
+	  Matrix newdata(A.rowsize, A.colsize);
+	    for (int i=0; i<A.rowsize; ++i){
+		for (int j=0; j<A.colsize; ++j){
+		    newdata.data[i*A.colsize + j] = A.data[i*A.colsize + j] == B.data[i];
+		}
+	    }
+	    return newdata;
+	}
+	
+	if (A.colsize == B.colsize && B.rowsize == 1){
+	  Matrix newdata(A.rowsize, A.colsize);
+	    for (int i=0; i<A.rowsize; ++i){
+		for (int j=0; j<A.colsize; ++j){
+		    newdata.data[i*A.colsize + j] = A.data[i*A.colsize + j] == B.data[j];
+		}
+	    }
+	    return newdata;
+	}
+	
+	if (B.size == 1){
+	  Matrix newdata(A.rowsize, A.colsize);
+	    for (int i=0; i<A.size; ++i){
+		newdata.data[i] = A.data[i] == B.data[0];
+	    }
+	    return newdata;  
+	}
+	
+	else {
+	  error("Matrices not conformable for ^= operator");
+	}  
+    }
+    
+    
+//  OPERATOR: Element-by-element Equality
+/*!
+  \overload Matrix operator ^= (const Matrix& A, const double& b)
+*/
+    Matrix operator ^= (const Matrix& A, const double& b)
+    {
+      Matrix newdata(A.rowsize, A.colsize);
+	for (int i=0; i<A.size; ++i){
+	    newdata.data[i] = A.data[i] == b;
+	}
+	return newdata;
+    }
+    
+    
+    
+    
+} // namespace dec
+
+#endif /* SCYTHE_DOUBLE_MATRIX_CC */
diff --git a/src/scythematrix.h b/src/scythematrix.h
new file mode 100644
index 0000000..04ab019
--- /dev/null
+++ b/src/scythematrix.h
@@ -0,0 +1,1231 @@
+/* Edited by Jasjeet S. Sekhon <jasjeet_sekhon at berkeley.edu> */
+/* HTTP://sekhon.berkeley.edu                                */
+/*                                                           */
+/* April 26, 2013                                            */
+/* get rid of friend-injection for ones, zero, seqa          */
+/* January 9, 2012                                           */
+/* May 8, 2010, updated header files for Solaris             */
+/* remove xpnd to work on Solaris march 31, 2009             */
+
+/* June 26, 2008                                             */
+/* __NATE__ additions by Nate Begeman (Apple)                */
+
+
+//
+// This library is the class definition of the Matrix class, part of
+// the SCYTHE project.
+//
+// Scythe C++ Library
+// Copyright (C) 2000 Kevin M. Quinn and Andrew D. Martin
+//
+// This code written by:
+//
+// Kevin Quinn
+// Assistant Professor
+// Dept. of Political Science and 
+// Center for Statistics and the Social Sciences
+// Box 354322
+// University of Washington
+// Seattle, WA  98195-4322
+// quinn at stat.washington.edu
+//
+// Andrew D. Martin
+// Assistant Professor
+// Dept. of Political Science
+// Campus Box 1063
+// Washington University
+// St. Louis, MO 63130
+// admartin at artsci.wustl.edu
+// 
+// This program is free software; you can redistribute it and/or
+// modify it under the terms of the GNU General Public License as
+// published by the Free Software Foundation; either version 2 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
+// USA
+
+#ifndef SCYTHE_DOUBLE_MATRIX_H
+#define SCYTHE_DOUBLE_MATRIX_H
+
+#include <R.h> /* needed for the error() function */
+#include <iostream>
+#include <iomanip>
+#include <fstream>
+ /* Not needed and causes problem in pre 3.3 gcc #include <sstream> */
+ /* #include <new> we've moved to malloc */
+#include <numeric>
+#include <string>
+#include <climits>
+#include <cmath>
+
+ //explicit include needed for gcc4.3 because of header cleanup
+#include <cstdlib>
+ //needed for Solaris instead of simply #include <cstdlib>
+#include <stdlib.h>
+
+ //http://gcc.gnu.org/gcc-4.3/porting_to.html
+ //http://www.cyrius.com/journal/2007/05/10#gcc-4.3-include
+#include <cstring>
+
+// Avoid NameSpace Pollution
+namespace SCYTHE {
+  
+  struct all_elements{
+  }  const _ = {};
+  
+
+class Matrix
+{
+public:
+  int rowsize;    // # of rows in Matrix
+  int colsize;    // # of columns in Matrix
+  int size;    	  // # of element in Matrix
+    		  // in row major order
+
+  double *data;   // array holding the elements of the Matrix
+  // BASIC FUNCTIONS
+
+/**********************************************************************/
+//  CONSTRUCTOR:  Matrix - Creates empty Matrix object
+//  Input:  void
+//  Return:  empty Matrix object
+//  Usage:  Matrix();
+//  Errors:  none
+//  Dependencies:  none
+
+    inline Matrix (void) {
+			rowsize = 1;
+			colsize = 1;
+			size = 1;
+			//data = new double[1];
+			data = (double *) malloc(1*sizeof(double));
+			data[0] = 0.0;
+		}
+
+/**********************************************************************/
+//  CONSTRUCTOR:  Matrix  - Creates Matrix obj. with specificed rows
+//  and columns
+//  Input:  int rows, int columns
+//  Return:  empty Matrix object 
+//  Usage:  Matrix(int,int);
+//  Errors:  0001
+//  Dependencies:  none
+
+   Matrix (const int& rows, const int& cols);
+
+/**********************************************************************/
+//  CONSTRUCTOR:  Matrix - Creates Matrix obj. filled with data from
+//  array.  ( inputarray is in row major order)
+//  Input:  double * inputarray, int rows, int columns
+//  Return: Matrix object
+//  Usage:  Matrix(double *,int,int);
+//  Errors:  0002
+//  Dependencies:  none
+
+   Matrix (const double *inputarray, const int& rows, const int& cols);
+
+/**********************************************************************/
+//  CONSTRUCTOR:   Matrix - Creates Matrix object from old Matrix
+//  Input:  Matrix object
+//  Return: Matrix object (filled with same data as old_matrix)
+//  Usage:  Matrix(Matrix &);
+//  Errors:  none
+//  Dependencies:  none
+
+   Matrix (const Matrix & old_matrix);
+
+/**********************************************************************/
+//  OPERATOR:  Matrix operator '=' - Allows for the copying of a Matrix
+//  Input:  Matrix object referemce
+//  Return: Matrix object (filled with same data)
+//  Usage:  MatrixA = MatrixB
+//  Errors:  none
+//  Dependencies:  none
+
+    Matrix & operator = (const Matrix & B);
+
+/**********************************************************************/
+//  OPERATOR: Matrix operator [] - allows for retrieval of element using
+//  traditional mathematical notation (retrieves ith element)
+//  Input:  integer i
+//  Return: double (value from Matrix)
+//  Usage:  Matrix[i]
+//  Errors:  0003
+//  Dependencies:  none
+
+  inline double &operator[] (const int& i) {
+		if (i >= size || i < 0) {
+		  error("Index out of range in [] operator");
+		}
+		return (data[i]);
+  }
+
+
+/**********************************************************************/
+//  OPERATOR: Matrix operator () - Retrieves Matrix element using
+//    mathematical notation (retrieves (i,j) element).
+//    NOTE: Indexing starts at 0
+//  Input:  integer i, integer j
+//  Return: double (value from Matrix)
+//  Usage:  Matrix(integer, integer);
+//  Errors:  0004
+//  Dependencies:  none
+
+  inline double &operator () (const int& i, const int& j) {
+		if (rowsize < i || colsize < j || i < 0 || j < 0) {
+		  error("Index out of range in () operator");
+		}
+		return data[i * colsize + j];
+	}
+
+
+
+
+/**********************************************************************/
+//  OPERATOR: Matrix operator () - Retrieves Matrix elements using
+//    mathematical notation (retrieves (i,_) element).
+//    NOTE: Indexing starts at 0
+//  Input:  integer i, all_elements
+//  Return: Matrix 
+//  Usage:  Matrix(integer, _);
+//  Errors:  ????
+//  Dependencies:  struct all_elements
+  
+  Matrix operator () (const int& i, const all_elements& a);
+
+
+
+/**********************************************************************/
+//  OPERATOR: Matrix operator () - Retrieves Matrix elements using
+//    mathematical notation (retrieves (_,j) element).
+//    NOTE: Indexing starts at 0
+//  Input:  all_elements, integer j
+//  Return: Matrix 
+//  Usage:  Matrix(_,integer);
+//  Errors:  ????
+//  Dependencies:  struct all_elements
+  
+  Matrix operator () (const all_elements& a, const int& j);
+
+
+
+/**********************************************************************/
+//  OPERATOR: Matrix operator () - Retrieves Matrix elements in row i.
+//      Indexing starts at 0
+//  Input:  integer i, Matrix J
+//  Return: Matrix object (row i elements)
+//  Usage:  Matrix(integer, Matrix &);
+//  Errors:  0005 - 0007
+//  Dependencies:  none
+
+   Matrix operator () (const int& i, const Matrix& J);
+
+/**********************************************************************/
+//  OPERATOR: Matrix operator () - Retrieves Matrix elements in column j.
+//      Indexing starts at 0
+//  Input:  Matrix I, integer j
+//  Return: Matrix object (column j elements)
+//  Usage:  Matrix(Matrix &, integer);
+//  Errors:  0008 - 0010
+//  Dependencies:  none
+
+   Matrix operator () (const Matrix& I, const int& j);
+
+/**********************************************************************/
+//  OPERATOR: Matrix operator () - Extracts submatrix from existing
+//      Matrix.  Get elements i,j from a Matrix where i in I and j in J
+//  Indexing starts at 0
+//  Input:  Matrix I , Matrix J
+//  Return: Matrix object ()
+//  Usage:  Matrix(Matrix &, Matrix &);
+//  Errors:  0011-0017
+//  Dependencies:  none
+
+   Matrix operator () (const Matrix& I, const Matrix& J);
+
+
+/**********************************************************************/
+//  DESTRUCTOR: Matrix object destructor
+//  Input:  void
+//  Return: void
+//  Usage:  ~Matrix();
+//  Errors:  
+//  Dependencies:  none
+
+   inline ~Matrix (void) {
+     //delete[] data;
+     free(data);
+     data = NULL;
+   }
+
+/**********************************************************************/
+//  FUNCTION: Print Matrix to screen
+//  Input:  integer width, integer setprecision
+//  Return: void
+//  Usage:  print(int width, int precision);
+//  Errors:  
+//  Dependencies:  none
+
+   void print (const int width = 10, const int prec = 5);
+
+
+	 inline void getArray(double *out) const {
+		 for (int i = 0; i < size; i++) {
+			 out[i] = data[i];
+		 }
+	 }
+   
+ /**********************************************************************/
+ //  FUNCTION: multiply each scalar element of the matrix
+ //  Input:  Matrix I
+ //  Return: void
+ //  Usage:  multi_scalar(Matrix &);
+ //  Errors:  
+ //  Dependencies:  none
+ 
+   void multi_scalar (Matrix &I) {
+     for (int i = 0; i < rowsize * colsize; ++i)
+       data[i] *= I.data[i];
+   }
+   
+/*******************   MORE ADVANCED FUNCTIONS  **********************/
+/**********************************************************************/
+
+/**********************************************************************/
+//  FUNCTION: c -- concatenates a sequence of doubles into a Matrix
+//  Input:  a user determined number of doubles (up to 26)
+//  Return:  Matrix object (a column vector)
+//  Usage:  c(a,b,c,d)
+//  Errors:  
+//  Dependencies:
+
+   friend Matrix c (const double& a, const double& b);
+   friend Matrix c (const double& a, const double& b, const double& c);
+   friend Matrix c (const double& a, const double& b, const double& c, 
+		    const double& d);  
+   friend Matrix c (const double& a, const double& b, const double& c, 
+		    const double& d, const double& e);  
+   friend Matrix c (const double& a, const double& b, const double& c, 
+		    const double& d, const double& e, const double& f);  
+   friend Matrix c (const double& a, const double& b, const double& c, 
+		    const double& d, const double& e, const double& f,
+		    const double& g);  
+   friend Matrix c (const double& a, const double& b, const double& c, 
+		    const double& d, const double& e, const double& f,
+		    const double& g, const double& h);  
+   friend Matrix c (const double& a, const double& b, const double& c, 
+		    const double& d, const double& e, const double& f,
+		    const double& g, const double& h, const double& i);
+   friend Matrix c (const double& a, const double& b, const double& c, 
+		    const double& d, const double& e, const double& f,
+		    const double& g, const double& h, const double& i,
+		    const double& j);
+   friend Matrix c (const double& a, const double& b, const double& c, 
+		    const double& d, const double& e, const double& f,
+		    const double& g, const double& h, const double& i,
+		    const double& j, const double& k);
+   friend Matrix c (const double& a, const double& b, const double& c, 
+		    const double& d, const double& e, const double& f,
+		    const double& g, const double& h, const double& i,
+		    const double& j, const double& k, const double& l);
+   friend Matrix c (const double& a, const double& b, const double& c, 
+		    const double& d, const double& e, const double& f,
+		    const double& g, const double& h, const double& i,
+		    const double& j, const double& k, const double& l,
+		    const double& m);
+   friend Matrix c (const double& a, const double& b, const double& c, 
+		    const double& d, const double& e, const double& f,
+		    const double& g, const double& h, const double& i,
+		    const double& j, const double& k, const double& l,
+		    const double& m, const double& n);
+   friend Matrix c (const double& a, const double& b, const double& c, 
+		    const double& d, const double& e, const double& f,
+		    const double& g, const double& h, const double& i,
+		    const double& j, const double& k, const double& l,
+		    const double& m, const double& n, const double& o);
+   friend Matrix c (const double& a, const double& b, const double& c, 
+		    const double& d, const double& e, const double& f,
+		    const double& g, const double& h, const double& i,
+		    const double& j, const double& k, const double& l,
+		    const double& m, const double& n, const double& o, 
+		    const double& p);
+   friend Matrix c (const double& a, const double& b, const double& c, 
+		    const double& d, const double& e, const double& f,
+		    const double& g, const double& h, const double& i,
+		    const double& j, const double& k, const double& l,
+		    const double& m, const double& n, const double& o, 
+		    const double& p, const double& q);
+   friend Matrix c (const double& a, const double& b, const double& c, 
+		    const double& d, const double& e, const double& f,
+		    const double& g, const double& h, const double& i,
+		    const double& j, const double& k, const double& l,
+		    const double& m, const double& n, const double& o, 
+		    const double& p, const double& q, const double& r);
+   friend Matrix c (const double& a, const double& b, const double& c, 
+		    const double& d, const double& e, const double& f,
+		    const double& g, const double& h, const double& i,
+		    const double& j, const double& k, const double& l,
+		    const double& m, const double& n, const double& o, 
+		    const double& p, const double& q, const double& r, 
+		    const double& s);
+   friend Matrix c (const double& a, const double& b, const double& c, 
+		    const double& d, const double& e, const double& f,
+		    const double& g, const double& h, const double& i,
+		    const double& j, const double& k, const double& l,
+		    const double& m, const double& n, const double& o, 
+		    const double& p, const double& q, const double& r, 
+		    const double& s, const double& t);
+   friend Matrix c (const double& a, const double& b, const double& c, 
+		    const double& d, const double& e, const double& f,
+		    const double& g, const double& h, const double& i,
+		    const double& j, const double& k, const double& l,
+		    const double& m, const double& n, const double& o, 
+		    const double& p, const double& q, const double& r, 
+		    const double& s, const double& t, const double& u);
+   friend Matrix c (const double& a, const double& b, const double& c, 
+		    const double& d, const double& e, const double& f,
+		    const double& g, const double& h, const double& i,
+		    const double& j, const double& k, const double& l,
+		    const double& m, const double& n, const double& o, 
+		    const double& p, const double& q, const double& r, 
+		    const double& s, const double& t, const double& u,
+		    const double& v);
+   friend Matrix c (const double& a, const double& b, const double& c, 
+		    const double& d, const double& e, const double& f,
+		    const double& g, const double& h, const double& i,
+		    const double& j, const double& k, const double& l,
+		    const double& m, const double& n, const double& o, 
+		    const double& p, const double& q, const double& r, 
+		    const double& s, const double& t, const double& u,
+		    const double& v, const double& w);
+   friend Matrix c (const double& a, const double& b, const double& c, 
+		    const double& d, const double& e, const double& f,
+		    const double& g, const double& h, const double& i,
+		    const double& j, const double& k, const double& l,
+		    const double& m, const double& n, const double& o, 
+		    const double& p, const double& q, const double& r, 
+		    const double& s, const double& t, const double& u,
+		    const double& v, const double& w, const double& x);
+   friend Matrix c (const double& a, const double& b, const double& c, 
+		    const double& d, const double& e, const double& f,
+		    const double& g, const double& h, const double& i,
+		    const double& j, const double& k, const double& l,
+		    const double& m, const double& n, const double& o, 
+		    const double& p, const double& q, const double& r, 
+		    const double& s, const double& t, const double& u,
+		    const double& v, const double& w, const double& x,
+		    const double& y);
+   friend Matrix c (const double& a, const double& b, const double& c, 
+		    const double& d, const double& e, const double& f,
+		    const double& g, const double& h, const double& i,
+		    const double& j, const double& k, const double& l,
+		    const double& m, const double& n, const double& o, 
+		    const double& p, const double& q, const double& r, 
+		    const double& s, const double& t, const double& u,
+		    const double& v, const double& w, const double& x,
+		    const double& y, const double& z);
+  
+
+
+/**********************************************************************/
+//  FUNCTION: Transpose  - computes the transpose of a Matrix
+//  Input:  Matrix object
+//  Return:  Matrix object 
+//  Usage:  t(Matrix & old_matrix)
+//  Errors:  
+//  Dependencies:  none
+
+   friend Matrix t (const Matrix & old_matrix);
+
+/**********************************************************************/
+//  FUNCTION: Ones - creates a Matrix of ones
+//  Input:  int rows, int cols
+//  Return:  Matrix object 
+//  Usage:  ones(int rows, int cols)
+//  Errors:  0018
+//  Dependencies:  none
+
+   static Matrix ones (const int& rows, const int& cols);
+
+/**********************************************************************/
+//  FUNCTION: Zeros - creates a Matrix of zeros
+//  Input:  int rows, int cols
+//  Return:  Matrix object 
+//  Usage:  zeros(int rows, int cols)
+//  Errors:  0018
+//  Dependencies:  none
+
+   static Matrix zeros (const int& rows, const int& cols);
+
+/**********************************************************************/
+//  FUNCTION: Eye - creates an Identity Matrix of size k x k
+//  Input:  integer k
+//  Return:  Matrix object 
+//  Usage:  eye(int k)
+//  Errors:  
+//  Dependencies:  none
+
+   friend Matrix eye (const int& k);
+
+/**********************************************************************/
+//  FUNCTION: Seqa - creates a vector additive sequence Matrix (size x 1)
+//  Input:  double start, double incr (increment), int size
+//  Return:  Matrix object 
+//  Usage:  seqa( double, double, int)
+//  Errors:  
+//  Dependencies:  none
+
+   static Matrix seqa (const double& start, const double& incr,
+		       const int& size);
+
+/**********************************************************************/
+//  FUNCTION: sort - sorts all elements of a Matrix using shellsort
+//                   and places sorted elements in Matrix the same
+//                   size as the original. DOES NOT SORT COLUMN BY COLUMN
+//  Input:  Matrix A
+//  Return:  Matrix object 
+//  Usage:  sort(Matrix)
+//  Errors:  
+//  Dependencies:  none
+//  Notes: from Sedgewick, 1992, p. 109 with modifications (0 indexing)
+
+   friend Matrix sort (const Matrix& A);
+
+
+/**********************************************************************/
+//  FUNCTION: sortc - sorts all columns of a Matrix using shellsort
+//  Input:  Matrix A
+//  Return:  Matrix object 
+//  Usage:  sort(Matrix)
+//  Errors:  
+//  Dependencies:  none
+//  Notes: from Sedgewick, 1992, p. 109 with modifications (0 indexing)
+
+   friend Matrix sortc (const Matrix& A);
+
+
+/**********************************************************************/
+//  FUNCTION: Cholesky - Cholesky Decomposition of a Sym. Pos-Def. Matrix
+//  Input:  Matrix A
+//  Return:  Matrix object (the L Matrix s.t. L*L'=A)
+//  Usage:  cholesky (Matrix A)
+//  Errors:  0019-0020
+//  Dependencies:  none
+
+
+   friend Matrix cholesky (const Matrix & A);
+
+/**********************************************************************/
+//  FUNCTION: Chol_solve - Solves Ax=b for x via backsubstitution using
+//  Cholesky Decomposition  (NOTE: function is overloaded)
+//  A must be symmetric and positive definite
+//  Input:  Matrix A, Matrix b
+//  Return:  Matrix x  (solution to Ax=b)
+//  Usage:  chol_solve( Matrix A, Matrix b)
+//  Errors:  0021
+//  Dependencies:  cholesky()
+
+   friend Matrix chol_solve (const Matrix & A, const Matrix & b);
+
+/**********************************************************************/
+//  FUNCTION: Chol_solve - Solves Ax=b for x via backsubstitution using
+//  Cholesky Decomposition. This function takes in the lower
+//  triangular L as input and does not depend upon cholesky()
+//  A must be symmetric and positive definite
+//  NOTE: function is overloaded
+//  Input:  Matrix A, Matrix b, Matrix L
+//  Return:  Matrix x  (solution to Ax=b)
+//  Usage:  chol_solve( Matrix A, Matrix b, Matrix& L)
+//  Errors:  0022
+//  Dependencies:  none
+
+   friend Matrix chol_solve (const Matrix & A, const Matrix & b,
+    	    const Matrix & L);
+
+/**********************************************************************/
+//  FUNCTION: Invpd - Calculates the inverse of a Sym. Pos. Def. Matrix
+//  (NOTE: function is overloaded)
+//  Input:  Matrix A 
+//  Return:  Matrix A^(-1)
+//  Usage:  invpd(Matrix A)
+//  Errors:  0023-0024
+//  Dependencies:  none
+
+   friend Matrix invpd (const Matrix & A);
+
+/**********************************************************************/
+//  FUNCTION: Invpd - Calculates the inverse of a Sym. Pos. Def. Matrix
+//  (NOTE: function is overloaded)
+//  Input:  Matrix A, Matrix L
+//  Return:  Matrix A^(-1)
+//  Usage:  invpd(Matrix A, Matrix L)
+//  Errors: 
+//  Dependencies:  none
+
+   friend Matrix invpd (const Matrix & A, const Matrix & L);
+
+/**********************************************************************/
+//  FUNCTION: Lu_decomp - Calculates the LU Decomposition of a square
+//  Matrix
+//  Input:  Matrix A, Matrix L, Matrix U, Matrix perm_vec
+//  Return:  integer (0 signifies success)
+//  Usage:  lu_decomp(Matrix& A, Matrix& L, Matrix& U, Matrix& perm_vec)
+//  Errors:  0025-0026
+//  Dependencies:  fabs()
+
+   friend int lu_decomp(const Matrix& A, Matrix& L, Matrix& U, 
+           Matrix& perm_vec);  
+
+/**********************************************************************/
+//  FUNCTION: Lu_solve - Solve Ax=b for x via forward and
+//  backsubstitution using the LU Decomp of Matrix A
+//  NOTE: This function is overloaded
+//  Input:  Matrix A, Matrix b 
+//  Return:  Matrix x
+//  Usage:  lu_solve(Matrix& A, Matrix& b)
+//  Errors:  0027-0030
+//  Dependencies:  fabs()
+
+   friend Matrix lu_solve(const Matrix& A, const Matrix& b);
+
+/**********************************************************************/
+//  FUNCTION: Lu_solve - Solve Ax=b for x via forward and
+//  backsubstitution using the LU Decomp of Matrix A
+//  NOTE: This function is overloaded
+//  Input:  Matrix A, Matrix b, Matrix L, Matrix U, Matrix p 
+//  Return:  Matrix x
+//  Usage:  lu_solve(Matrix& A, Matrix& b, Matrix& L, Matrix& U,
+//    		Matrix& p)
+//  Errors:  0031-0035
+//  Dependencies:  fabs()
+
+   friend Matrix lu_solve(const Matrix& A, const Matrix& b, 
+    const Matrix& L, const Matrix& U, const Matrix& p);
+
+/**********************************************************************/
+//  FUNCTION: Row_interchange - Interchanges the rows of A with those
+//  in vector p and returns the modified Matrix.
+//  Input:  Matrix A, Matrix p 
+//  Return:  Matrix object
+//  Usage:  row_interchange(Matrix& A, Matrix& p)
+//  Errors:  0036-0037
+//  Dependencies:  
+
+   friend Matrix row_interchange(const Matrix& A, const Matrix& pp);
+
+/**********************************************************************/
+//  FUNCTION: Inv - Calculate the Inverse of a square Matrix A via
+//  LU decomposition
+//  Input:  Matrix A 
+//  Return:  Matrix object
+//  Usage:  inv(Matrix& A)
+//  Errors:  0038-0039
+//  Dependencies:  row_interchange(), det()
+
+  friend Matrix inv(const Matrix& A);
+
+/**********************************************************************/
+//  FUNCTION: Det - Calculates the determinant of Matrix A via
+//  LU Decomposition
+//  Input:  Matrix A 
+//  Return:  double determinant
+//  Usage:  det( Matrix& A)
+//  Errors:  0040
+//  Dependencies:  
+
+   friend double det(const Matrix& A);
+
+/**********************************************************************/
+//  FUNCTION: Cbind - Column bind 2 matrices
+//  Input:  Matrix A, Matrix B 
+//  Return:  Matrix object
+//  Usage:  cbind(Matrix& A, Matrix& B)
+//  Errors:  0041
+//  Dependencies:  
+
+   friend Matrix cbind (const Matrix & A, const Matrix & B);
+
+/**********************************************************************/
+//  FUNCTION: Rbind - Row bind 2 matrices
+//  Input:  Matrix A, Matrix B 
+//  Return:  Matrix object
+//  Usage:  rbind(Matrix& A, Matrix& B)
+//  Errors:  0042
+//  Dependencies:  
+
+  friend Matrix rbind (const Matrix & A, const Matrix & B);
+
+//  ACCESSOR: Rows - Returns the number of rows in a Matrix
+//  ACCESSOR: Cols - Returns the number of columns in a Matrix
+//  ACCESSOR: Size - Returns the size of a Matrix (size = rows x cols)
+/**********************************************************************/
+//  ACCESSOR: Rows - Returns the number of rows in a Matrix
+//  Input:  Matrix A
+//  Return:  integer
+//  Usage:  rows(Matrix& A)
+//  Errors:  
+//  Dependencies:  
+
+   friend inline int rows (const Matrix & A) {
+       return (A.rowsize);
+   }
+
+/**********************************************************************/
+//  ACCESSOR: Cols - Returns the number of columns in a Matrix
+//  Input:  Matrix A
+//  Return:  integer
+//  Usage:  cols(Matrix& A)
+//  Errors:  
+//  Dependencies:  
+
+   friend inline int cols (const Matrix & A) {
+      return (A.colsize);
+   }
+
+/**********************************************************************/
+//  ACCESSOR: Size - Returns the size of a Matrix (size = rows x cols)
+//  Input:  Matrix A
+//  Return:  integer
+//  Usage:  size(Matrix& A)
+//  Errors:  
+//  Dependencies:  
+
+   friend inline int size (const Matrix & A) {
+     	return (A.size);
+   }
+
+/**********************************************************************/
+//  FUNCTION: Sumc - Calculate the sum of each column of a Matrix
+//  Input:  Matrix A
+//  Return:  Matrix object (row vector)
+//  Usage:  sumc(Matrix& A)
+//  Errors:  
+//  Dependencies:  
+
+   friend Matrix sumc (const Matrix & A);
+
+/**********************************************************************/
+//  FUNCTION: Prodc - Calculate the product of each column of a Matrix
+//  Input:  Matrix A
+//  Return:  Matrix object (row vector)
+//  Usage:  prodc(Matrix& A)
+//  Errors:  
+//  Dependencies:  
+
+  friend Matrix prodc (const Matrix& A);
+
+/**********************************************************************/
+//  FUNCTION: Meanc - Calculate the mean of each column of a Matrix
+//  Input:  Matrix A
+//  Return:  Matrix object (row vector)
+//  Usage:  meanc(Matrix& A)
+//  Errors:  
+//  Dependencies:  
+
+   friend Matrix meanc (const Matrix & A);
+
+/**********************************************************************/
+//  FUNCTION: Varc - Calculate the variance of each Matrix column
+//  Input:  Matrix A
+//  Return:  Matrix object (row vector)
+//  Usage:  varc(Matrix& A)
+//  Errors:  
+//  Dependencies:  meanc()
+
+   friend Matrix varc (const Matrix & A);
+
+/**********************************************************************/
+//  FUNCTION: Stdc - Calculate the std deviation of each Matrix column
+//  Input:  Matrix A
+//  Return:  Matrix object (row vector)
+//  Usage:  stdc(Matrix& A)
+//  Errors:  
+//  Dependencies:  
+
+   friend Matrix stdc (const Matrix & A);
+
+/**********************************************************************/
+//  FUNCTION: Sqrt - Calculate the sqrt of each element of a Matrix
+//  Input:  Matrix A
+//  Return:  Matrix object
+//  Usage:  sqrt(Matrix& A)
+//  Errors:  
+//  Dependencies:  
+
+   friend Matrix sqrt (const Matrix & A);
+
+/**********************************************************************/
+//  FUNCTION: Fabs - Calculate the absolute value of each Matrix element
+//  Input:  Matrix A
+//  Return:  Matrix object
+//  Usage:  fabs(Matrix& A)
+//  Errors:  
+//  Dependencies:  
+
+   friend Matrix fabs (const Matrix & A);
+
+/**********************************************************************/
+//  FUNCTION: Exp - Calculate the value of e^x for each  individual
+//  Matrix element
+//  Input:  Matrix A
+//  Return:  Matrix object
+//  Usage:  exp(Matrix& A)
+//  Errors:  
+//  Dependencies:  
+
+   friend Matrix exp(const Matrix& A);
+
+/**********************************************************************/
+//  FUNCTION: Log - Calculate the natural log of each Matrix element
+//  Input:  Matrix A
+//  Return:  Matrix object
+//  Usage:  log(Matrix& A)
+//  Errors:  
+//  Dependencies:  
+
+   friend Matrix log(const Matrix& A);
+
+/**********************************************************************/
+//  FUNCTION: Log10 - Calculate the Base 10 Log of each Matrix element
+//  Input:  Matrix A
+//  Return:  Matrix object
+//  Usage:  log10(Matrix& A)
+//  Errors:  
+//  Dependencies:  
+
+   friend Matrix log10(const Matrix& A);
+
+/**********************************************************************/
+//  FUNCTION: Pow - Raise each Matrix element to a specified power
+//  Input:  Matrix A, double e
+//  Return:  Matrix object
+//  Usage:  pow(Matrix& A. double& e)
+//  Errors:  
+//  Dependencies:  
+
+   friend Matrix pow(const Matrix& A, const double& e);
+
+/**********************************************************************/
+//  FUNCTION: Max - Calculates the maximum element in a Matrix
+//  Input:  Matrix A
+//  Return:  double max
+//  Usage:  max(Matrix& A)
+//  Errors:  
+//  Dependencies:  
+
+   friend double max (const Matrix & A);
+
+/**********************************************************************/
+//  FUNCTION: Min - Calculates the minimum element in a Matrix
+//  Input:  Matrix A
+//  Return:  double min
+//  Usage:  min(Matrix& A)
+//  Errors:  
+//  Dependencies:  
+
+   friend double min (const Matrix & A);
+
+/**********************************************************************/
+//  FUNCTION: Maxc - Calculates the maximum of each Matrix column
+//  Input:  Matrix A
+//  Return:  Matrix object (row vector)
+//  Usage:  maxc(Matrix& A)
+//  Errors:  
+//  Dependencies:  
+
+   friend Matrix maxc (const Matrix & A);
+
+/**********************************************************************/
+//  FUNCTION: Minc - Calculates the minimum of each Matrix column
+//  Input:  Matrix A
+//  Return:  Matrix object (row vector)
+//  Usage:  minc(Matrix& A)
+//  Errors:  
+//  Dependencies:  
+
+   friend Matrix minc (const Matrix & A);
+
+/**********************************************************************/
+//  FUNCTION: Maxindc - Finds the index of the max of each Matrix column
+//  Input:  Matrix A
+//  Return:  Matrix object (row vector)
+//  Usage:  maxindc(Matrix& A)
+//  Errors:  
+//  Dependencies:  
+
+   friend Matrix maxindc(const Matrix& A);
+  
+/**********************************************************************/
+//  FUNCTION: Minindc - Finds the index of the min of each Matrix column
+//  Input:  Matrix A
+//  Return:  Matrix object (row vector)
+//  Usage:  minindc(Matrix& A)
+//  Errors:  
+//  Dependencies:  
+
+   friend Matrix minindc(const Matrix& A);
+
+/**********************************************************************/
+//  FUNCTION: Order - Calculates the order of each element in a Matrix
+//  Input:  Matrix A (must be column vector)
+//  Return:  Matrix object (column vector)
+//  Usage:  order(Matrix& A)
+//  Errors:  0043
+//  Dependencies:  sumc()
+
+   friend Matrix order(const Matrix& A);
+
+/**********************************************************************/
+//  FUNCTION: Selif - Selects all the rows of Matrix A for which
+//  binary column vector e has an element equal to 1
+//  Input:  Matrix A, Matrix e (binary data)
+//  Return:  Matrix object
+//  Usage:  selif(Matrix& A, MAtrix& e)
+//  Errors:  0044-0046
+//  Dependencies:  
+
+   friend Matrix selif(const Matrix& A, const Matrix& e);
+
+/**********************************************************************/
+//  FUNCTION: Unique - Finds unique elements in a Matrix
+//  Input:  Matrix A
+//  Return:  Matrix object (column vector)
+//  Usage:  unique(Matrix& A)
+//  Errors:  
+//  Dependencies:  
+
+   friend Matrix unique(const Matrix& A);
+
+/**********************************************************************/
+//  FUNCTION: Vecr - Turn Matrix into Column vector by stacking rows
+//  NOTE: Vecr is much faster than Vecc
+//  Input:  Matrix A
+//  Return:  Matrix object (column vector)
+//  Usage:  vecr(Matrix& A)
+//  Errors:  
+//  Dependencies:
+
+   inline friend Matrix vecr(const Matrix& A) {
+	   Matrix temp = Matrix(A.data, A.size, 1);
+	   return temp;
+   }
+
+/**********************************************************************/
+//  FUNCTION: Vecc - Turn Matrix into Column vector by stacking columns
+//  NOTE: Vecr is much faster than Vecc
+//  Input:  Matrix A
+//  Return:  Matrix object (column vector)
+//  Usage:  vecc(Matrix& A)
+//  Errors:  
+//  Dependencies:
+
+   friend Matrix vecc(const Matrix& A);
+
+/**********************************************************************/
+//  FUNCTION: Reshape - Reshapes a row major order Matrix or Vector
+//  Input:  Matrix A, int rows, int columns
+//  Return:  Matrix object (same size, but different # of rows/columns
+//  Usage:  reshape(Matrix& A, int rows, int cols)
+//  Errors:  0047
+//  Dependencies:
+
+   friend Matrix reshape(const Matrix& A, const int r, const int c);
+
+/**********************************************************************/
+//  FUNCTION: Vech - Make vector out of unique elements of a symmetric
+//  Matrix
+//  Input:  Matrix A
+//  Return:  Matrix object
+//  Usage:  vech(Matrix& A)
+//  Errors:  0048
+//  Dependencies:
+
+   friend Matrix vech(const Matrix& A);
+
+/**********************************************************************/
+//  FUNCTION: Xpnd - Get symmetric Matrix B back from A = vech(B)
+//  Input:  Matrix A
+//  Return:  Matrix object (symmetric)
+//  Usage:  xpnd(Matrix& A)
+//  Errors:  0049
+//  Dependencies: fmod()
+
+//   friend Matrix xpnd(const Matrix& A);
+
+/**********************************************************************/
+//  FUNCTION: Diag - get the diagonal of a Matrix
+//  Input:  Matrix A
+//  Return:  Matrix object (column vector)
+//  Usage:  diag(Matrix& A)
+//  Errors:  0050
+//  Dependencies:
+
+   friend Matrix diag(const Matrix& A);
+
+/**********************************************************************/
+//  FUNCTION: Gaxpy - Fast calculation of A*B + C
+//  Input:  Matrix A, Matrix B, Matrix C
+//  Return:  Matrix object (result of calculation)
+//  Usage:  gaxpy(Matrix& A, Matrix& B, Matrix& C)
+//  Errors:  0051-0054
+//  Dependencies:
+
+   friend Matrix gaxpy(const Matrix& A, const Matrix& B, const Matrix& C);
+
+/**********************************************************************/
+//  FUNCTION: Crossprod - Fast calculation of A'A
+//  Input:  Matrix A
+//  Return:  Matrix object (result of calculation)
+//  Usage:  crossprod(Matrix& A)
+//  Errors:  
+//  Dependencies:
+
+   friend Matrix crossprod(const Matrix& A);
+
+   friend Matrix crossprod2(const Matrix& A);
+
+
+/************************    OPERATORS     ****************************/
+/**********************************************************************/
+//  OPERATOR: Addition
+//  NOTE: This operator is overloaded
+//  Input:  Matrix A, Matrix B
+//  Return:  Matrix object (result of calculation)
+//  Usage:  A+B
+//  Errors:  0055
+//  Dependencies:
+
+   friend Matrix operator + (const Matrix & A, const Matrix & B);
+
+/**********************************************************************/
+//  OPERATOR: Addition
+//  NOTE: This operator is overloaded
+//  Input:  Matrix A, double b
+//  Return:  Matrix object (result of calculation)
+//  Usage:  A+b
+//  Errors:  
+//  Dependencies:
+
+   friend Matrix operator + (const Matrix & A, const double &b);
+
+/**********************************************************************/
+//  OPERATOR: Addition
+//  NOTE: This operator is overloaded
+//  Input:  double a, Matrix B
+//  Return:  Matrix object (result of calculation)
+//  Usage:  a+B
+//  Errors:  
+//  Dependencies:
+
+   friend Matrix operator + (const double &a, const Matrix & B);
+
+/**********************************************************************/
+//  OPERATOR: Subtraction
+//  NOTE: This operator is overloaded
+//  Input:  Matrix A, Matrix B
+//  Return:  Matrix object (result of calculation)
+//  Usage:  A-B
+//  Errors:  0056
+//  Dependencies:
+
+   friend Matrix operator - (const Matrix & A, const Matrix & B);
+
+/**********************************************************************/
+//  OPERATOR: Subtraction
+//  NOTE: This operator is overloaded
+//  Input:  Matrix A, double b
+//  Return:  Matrix object (result of calculation)
+//  Usage:  A-b
+//  Errors:  
+//  Dependencies:
+
+   friend Matrix operator - (const Matrix & A, const double &b);
+
+/**********************************************************************/
+//  OPERATOR: Subtraction
+//  NOTE: This operator is overloaded
+//  Input:  double a, Matrix B
+//  Return:  Matrix object (result of calculation)
+//  Usage:  a-B
+//  Errors:  
+//  Dependencies:
+
+   friend Matrix operator - (const double &a, const Matrix & B);
+
+/**********************************************************************/
+//  OPERATOR: Multiplication
+//  NOTE: This operator is overloaded
+//  Input:  Matrix A, Matrix B
+//  Return:  Matrix object (result of calculation)
+//  Usage:  A*B
+//  Errors:  0057
+//  Dependencies:
+
+  friend Matrix operator * (const Matrix & A, const Matrix & B);
+
+/**********************************************************************/
+//  OPERATOR: Multiplication
+//  NOTE: This operator is overloaded
+//  Input:  Matrix A, double b
+//  Return:  Matrix object (result of calculation)
+//  Usage:  A*b
+//  Errors:  
+//  Dependencies:
+
+  friend Matrix operator * (const Matrix & A, const double & b);
+
+/**********************************************************************/
+//  OPERATOR: Multiplication
+//  NOTE: This operator is overloaded
+//  Input:  double a, Matrix B
+//  Return:  Matrix object (result of calculation)
+//  Usage:  a*B
+//  Errors:  
+//  Dependencies:
+
+  friend Matrix operator * (const double & a, const Matrix & B);
+
+/**********************************************************************/
+//  OPERATOR: Division
+//  NOTE: This operator is overloaded
+//  Input:  Matrix A, Matrix B
+//  Return:  Matrix object (result of calculation)
+//  Usage:  A/B
+//  Errors:  
+//  Dependencies:
+
+   friend Matrix operator / (const Matrix& A, const Matrix& B);
+
+/**********************************************************************/
+//  OPERATOR: Division
+//  NOTE: This operator is overloaded
+//  Input:  Matrix A, double b
+//  Return:  Matrix object (result of calculation)
+//  Usage:  A/b
+//  Errors:  0058
+//  Dependencies:
+
+   friend Matrix operator / (const Matrix& A, const double& b);
+
+
+/**********************************************************************/
+//  OPERATOR: Division
+//  NOTE: This operator is overloaded
+//  Input:  double a, Matrix B
+//  Return:  Matrix object (result of calculation)
+//  Usage:  a/B
+//  Errors:  
+//  Dependencies:
+
+   friend Matrix operator / (const double& a, const Matrix& B);
+
+/**********************************************************************/
+//  OPERATOR: Kronecker multiplication
+//  Input:  Matrix A, Matrix B
+//  Return:  Matrix object (result of calculation)
+//  Usage:  A%B
+//  Errors:  
+//  Dependencies:
+
+   friend Matrix operator % (const Matrix& A, const Matrix& B);
+
+/**********************************************************************/
+//  OPERATOR: Equality
+//  Input:  Matrix A, Matrix B
+//  Return:  Integer (False=0, True=1)
+//  Usage:  A==B
+//  Errors:  
+//  Dependencies:
+
+   friend int operator == (const Matrix& A, const Matrix & B);
+
+/**********************************************************************/
+//  OPERATOR: Inequality
+//  Input:  Matrix A, Matrix B
+//  Return:  Integer (False=0, True=1)
+//  Usage:  A!=B
+//  Errors:  
+//  Dependencies:
+
+   friend int operator != (const Matrix& A, const Matrix & B);
+
+/**********************************************************************/
+//  OPERATOR: Element-by-element Greater Than
+//  NOTE: This operator is overloaded
+//  Input:  Matrix A, Matrix B
+//  Return:  Matrix of ints (False=0, True=1)
+//  Usage:  A>>B
+//  Errors:  0059-0060
+//  Dependencies:
+
+   friend Matrix operator >> (const Matrix& A, const Matrix& B);
+
+/**********************************************************************/
+//  OPERATOR: Element-by-scalar Greater Than
+//  NOTE: This operator is overloaded
+//  Input:  Matrix A, double b
+//  Return:  Matrix of ints (False=0, True=1)
+//  Usage:  A>>b
+//  Errors:  
+//  Dependencies:
+
+   friend Matrix operator >> (const Matrix& A, const double& b);
+
+/**********************************************************************/
+//  OPERATOR: Element-by-element Less Than
+//  NOTE: This operator is overloaded
+//  Input:  Matrix A, Matrix B
+//  Return:  Matrix of ints (False=0, True=1)
+//  Usage:  A>>B
+//  Errors:  0061-0062
+//  Dependencies:
+
+   friend Matrix operator << (const Matrix& A, const Matrix& B);
+
+/**********************************************************************/
+//  OPERATOR: Element-by-scalar Less Than
+//  NOTE: This operator is overloaded
+//  Input:  Matrix A, double b
+//  Return:  Matrix of ints (False=0, True=1)
+//  Usage:  A<<b
+//  Errors:  
+//  Dependencies:
+
+   friend Matrix operator << (const Matrix& A, const double& b);
+
+
+/**********************************************************************/
+//  OPERATOR: Element-by-element Equality
+//  NOTE: This operator is overloaded
+//  Input:  Matrix A, Matrix B
+//  Return:  Matrix of ints (False=0, True=1)
+//  Usage:  A^=B
+//  Errors:  0063-0064
+//  Dependencies:
+
+   friend Matrix operator ^= (const Matrix& A, const Matrix& B);
+
+/**********************************************************************/
+//  OPERATOR: Element-by-scalar Equality
+//  NOTE: This operator is overloaded
+//  Input:  Matrix A, double b
+//  Return:  Matrix of ints (False=0, True=1)
+//  Usage:  A^=b
+//  Errors:  
+//  Dependencies:
+
+   friend Matrix operator ^= (const Matrix& A, const double& b);
+
+};
+
+} // namespace declaration
+
+#endif /* SCYTHE_DOUBLE_MATRIX_H */
diff --git a/tests/AbadieImbens.R b/tests/AbadieImbens.R
new file mode 100644
index 0000000..f693f95
--- /dev/null
+++ b/tests/AbadieImbens.R
@@ -0,0 +1,119 @@
+# Replication of Guido Imbens lalonde_exper_04feb2.m file
+# See http://elsa.berkeley.edu/~imbens/estimators.shtml
+# with balance checks
+
+suppressMessages(library(Matching))
+
+data(lalonde)
+
+X  <- lalonde$age
+Z  <- X;             
+V  <- lalonde$educ;
+Y  <- lalonde$re78/1000;
+T  <- lalonde$treat;
+w.educ=exp((lalonde$educ-10.1)/2);
+
+res  <- matrix(nrow=1,ncol=3)
+
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=1,Var.calc=0,
+             sample=TRUE);
+summary(rr)
+
+res[1,]  <- cbind(1,rr$est,rr$se)
+
+
+X  <- cbind(lalonde$age, lalonde$educ, lalonde$re74, lalonde$re75)
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=1,Var.calc=0,
+             sample=TRUE);
+summary(rr)
+
+res  <- rbind(res,cbind(2,rr$est,rr$se))
+
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=3,BiasAdj=FALSE,Weight=1,Var.calc=0,
+             sample=TRUE);
+summary(rr)
+res  <- rbind(res,cbind(4,rr$est,rr$se))
+
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATT",M=1,BiasAdj=FALSE,Weight=1,Var.calc=0,
+             sample=TRUE);
+summary(rr)
+res  <- rbind(res,cbind(5,rr$est,rr$se))
+
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATC",M=1,BiasAdj=FALSE,Weight=1,Var.calc=0,
+             sample=TRUE);
+summary(rr)
+res  <- rbind(res,cbind(6,rr$est,rr$se))
+
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=2,Var.calc=0,
+             sample=TRUE);
+summary(rr)
+res  <- rbind(res,cbind(7,rr$est,rr$se))
+
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=3,Var.calc=0,
+             Weight.matrix=diag(4), sample=TRUE);
+summary(rr)
+res  <- rbind(res,cbind(8,rr$est,rr$se))
+
+
+rr  <- Match(Y=Y,Tr=T,X=X,Z=X,V=V,estimand="ATE",M=1,BiasAdj=TRUE,Weight=1,Var.calc=0,
+             sample=TRUE);
+summary(rr)
+res  <- rbind(res,cbind(9,rr$est,rr$se))
+
+Z  <- cbind(lalonde$married, lalonde$age)
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=TRUE,Weight=1,Var.calc=0,sample=TRUE);
+summary(rr)
+res  <- rbind(res,cbind(10,rr$est,rr$se))
+
+V  <- lalonde$age
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=1,Var.calc=0,exact=TRUE,
+             sample=TRUE);
+summary(rr)
+res  <- rbind(res,cbind(11,rr$est,rr$se))
+
+V  <- cbind(lalonde$married, lalonde$u74)
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=1,Var.calc=0,exact=TRUE,
+             sample=TRUE);
+summary(rr)
+res  <- rbind(res,cbind(12,rr$est,rr$se))
+
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=1,Var.calc=0,sample=FALSE);
+summary(rr)
+res  <- rbind(res,cbind(13,rr$est,rr$se))
+
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=1,Var.calc=3,sample=TRUE);
+summary(rr)
+res  <- rbind(res,cbind(14,rr$est,rr$se))
+
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=1,Var.calc=0,
+             weights=w.educ,sample=TRUE);
+summary(rr)
+res  <- rbind(res,cbind(15,rr$est,rr$se))
+
+
+V  <- lalonde$age
+Z  <- cbind(lalonde$married, lalonde$age)
+X  <- cbind(lalonde$age, lalonde$educ, lalonde$re74, lalonde$re75)
+weight  <- w.educ
+Weight.matrix  <- diag(4)
+
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,
+             sample=FALSE, M=3, estimand="ATT", BiasAdj=TRUE, Weight=3, exact=TRUE,Var.calc=3,
+             weights=w.educ, Weight.matrix=Weight.matrix);
+summary(rr)
+res  <- rbind(res,cbind(75,rr$est,rr$se))
+
+
+V  <- lalonde$married;
+Z  <- cbind(lalonde$age, lalonde$re75);
+X  <- cbind(lalonde$age, lalonde$educ, lalonde$re74);
+
+rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,
+             sample=TRUE, M=3, estimand="ATE", BiasAdj=TRUE, Weight=2, exact=TRUE,Var.calc=0,
+             weights=w.educ);
+summary(rr)
+res  <- rbind(res,cbind(76,rr$est,rr$se))
+
+cat("\nResults:\n")
+print(res)
+
diff --git a/tests/AbadieImbens.Rout.save b/tests/AbadieImbens.Rout.save
new file mode 100644
index 0000000..822dffe
--- /dev/null
+++ b/tests/AbadieImbens.Rout.save
@@ -0,0 +1,351 @@
+
+R Under development (unstable) (2013-06-27 r63079) -- "Unsuffered Consequences"
+Copyright (C) 2013 The R Foundation for Statistical Computing
+Platform: x86_64-apple-darwin10.8.0 (64-bit)
+
+R is free software and comes with ABSOLUTELY NO WARRANTY.
+You are welcome to redistribute it under certain conditions.
+Type 'license()' or 'licence()' for distribution details.
+
+R is a collaborative project with many contributors.
+Type 'contributors()' for more information and
+'citation()' on how to cite R or R packages in publications.
+
+Type 'demo()' for some demos, 'help()' for on-line help, or
+'help.start()' for an HTML browser interface to help.
+Type 'q()' to quit R.
+
+> # Replication of Guido Imbens lalonde_exper_04feb2.m file
+> # See http://elsa.berkeley.edu/~imbens/estimators.shtml
+> # with balance checks
+> 
+> suppressMessages(library(Matching))
+> 
+> data(lalonde)
+> 
+> X  <- lalonde$age
+> Z  <- X;             
+> V  <- lalonde$educ;
+> Y  <- lalonde$re78/1000;
+> T  <- lalonde$treat;
+> w.educ=exp((lalonde$educ-10.1)/2);
+> 
+> res  <- matrix(nrow=1,ncol=3)
+> 
+> rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=1,Var.calc=0,
++              sample=TRUE);
+> summary(rr)
+
+Estimate...  1.7852 
+AI SE......  0.68672 
+T-stat.....  2.5996 
+p.val......  0.0093332 
+
+Original number of observations..............  445 
+Original number of treated obs...............  185 
+Matched number of observations...............  445 
+Matched number of observations  (unweighted).  5251 
+
+> 
+> res[1,]  <- cbind(1,rr$est,rr$se)
+> 
+> 
+> X  <- cbind(lalonde$age, lalonde$educ, lalonde$re74, lalonde$re75)
+> rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=1,Var.calc=0,
++              sample=TRUE);
+> summary(rr)
+
+Estimate...  1.7144 
+AI SE......  0.74013 
+T-stat.....  2.3164 
+p.val......  0.020539 
+
+Original number of observations..............  445 
+Original number of treated obs...............  185 
+Matched number of observations...............  445 
+Matched number of observations  (unweighted).  733 
+
+> 
+> res  <- rbind(res,cbind(2,rr$est,rr$se))
+> 
+> rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=3,BiasAdj=FALSE,Weight=1,Var.calc=0,
++              sample=TRUE);
+> summary(rr)
+
+Estimate...  1.5363 
+AI SE......  0.66193 
+T-stat.....  2.3209 
+p.val......  0.02029 
+
+Original number of observations..............  445 
+Original number of treated obs...............  185 
+Matched number of observations...............  445 
+Matched number of observations  (unweighted).  1670 
+
+> res  <- rbind(res,cbind(4,rr$est,rr$se))
+> 
+> rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATT",M=1,BiasAdj=FALSE,Weight=1,Var.calc=0,
++              sample=TRUE);
+> summary(rr)
+
+Estimate...  1.7269 
+AI SE......  0.83663 
+T-stat.....  2.0641 
+p.val......  0.039005 
+
+Original number of observations..............  445 
+Original number of treated obs...............  185 
+Matched number of observations...............  185 
+Matched number of observations  (unweighted).  327 
+
+> res  <- rbind(res,cbind(5,rr$est,rr$se))
+> 
+> rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATC",M=1,BiasAdj=FALSE,Weight=1,Var.calc=0,
++              sample=TRUE);
+> summary(rr)
+
+Estimate...  1.7055 
+AI SE......  0.8201 
+T-stat.....  2.0796 
+p.val......  0.037558 
+
+Original number of observations..............  445 
+Original number of control obs...............  260 
+Matched number of observations...............  260 
+Matched number of observations  (unweighted).  406 
+
+> res  <- rbind(res,cbind(6,rr$est,rr$se))
+> 
+> rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=2,Var.calc=0,
++              sample=TRUE);
+> summary(rr)
+
+Estimate...  1.5926 
+AI SE......  0.68473 
+T-stat.....  2.3259 
+p.val......  0.020024 
+
+Original number of observations..............  445 
+Original number of treated obs...............  185 
+Matched number of observations...............  445 
+Matched number of observations  (unweighted).  729 
+
+> res  <- rbind(res,cbind(7,rr$est,rr$se))
+> 
+> rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=3,Var.calc=0,
++              Weight.matrix=diag(4), sample=TRUE);
+> summary(rr)
+
+Estimate...  1.7144 
+AI SE......  0.74013 
+T-stat.....  2.3164 
+p.val......  0.020539 
+
+Original number of observations..............  445 
+Original number of treated obs...............  185 
+Matched number of observations...............  445 
+Matched number of observations  (unweighted).  733 
+
+> res  <- rbind(res,cbind(8,rr$est,rr$se))
+> 
+> 
+> rr  <- Match(Y=Y,Tr=T,X=X,Z=X,V=V,estimand="ATE",M=1,BiasAdj=TRUE,Weight=1,Var.calc=0,
++              sample=TRUE);
+> summary(rr)
+
+Estimate...  1.6309 
+AI SE......  0.74523 
+T-stat.....  2.1885 
+p.val......  0.028636 
+
+Original number of observations..............  445 
+Original number of treated obs...............  185 
+Matched number of observations...............  445 
+Matched number of observations  (unweighted).  733 
+
+> res  <- rbind(res,cbind(9,rr$est,rr$se))
+> 
+> Z  <- cbind(lalonde$married, lalonde$age)
+> rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=TRUE,Weight=1,Var.calc=0,sample=TRUE);
+> summary(rr)
+
+Estimate...  1.7197 
+AI SE......  0.74361 
+T-stat.....  2.3126 
+p.val......  0.020743 
+
+Original number of observations..............  445 
+Original number of treated obs...............  185 
+Matched number of observations...............  445 
+Matched number of observations  (unweighted).  733 
+
+> res  <- rbind(res,cbind(10,rr$est,rr$se))
+> 
+> V  <- lalonde$age
+> rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=1,Var.calc=0,exact=TRUE,
++              sample=TRUE);
+> summary(rr)
+
+Estimate...  1.3693 
+AI SE......  0.40423 
+T-stat.....  3.3874 
+p.val......  0.00070554 
+
+Original number of observations..............  445 
+Original number of treated obs...............  185 
+Matched number of observations...............  169 
+Matched number of observations  (unweighted).  378 
+
+Number of obs dropped by 'exact' or 'caliper'  276 
+
+> res  <- rbind(res,cbind(11,rr$est,rr$se))
+> 
+> V  <- cbind(lalonde$married, lalonde$u74)
+> rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=1,Var.calc=0,exact=TRUE,
++              sample=TRUE);
+> summary(rr)
+
+Estimate...  1.3693 
+AI SE......  0.40423 
+T-stat.....  3.3874 
+p.val......  0.00070554 
+
+Original number of observations..............  445 
+Original number of treated obs...............  185 
+Matched number of observations...............  169 
+Matched number of observations  (unweighted).  378 
+
+Number of obs dropped by 'exact' or 'caliper'  276 
+
+> res  <- rbind(res,cbind(12,rr$est,rr$se))
+> 
+> rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=1,Var.calc=0,sample=FALSE);
+> summary(rr)
+
+Estimate...  1.7144 
+AI SE......  0.74338 
+T-stat.....  2.3062 
+p.val......  0.021098 
+
+Original number of observations..............  445 
+Original number of treated obs...............  185 
+Matched number of observations...............  445 
+Matched number of observations  (unweighted).  733 
+
+> res  <- rbind(res,cbind(13,rr$est,rr$se))
+> 
+> rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=1,Var.calc=3,sample=TRUE);
+> summary(rr)
+
+Estimate...  1.7144 
+AI SE......  0.69627 
+T-stat.....  2.4623 
+p.val......  0.013806 
+
+Original number of observations..............  445 
+Original number of treated obs...............  185 
+Matched number of observations...............  445 
+Matched number of observations  (unweighted).  733 
+
+> res  <- rbind(res,cbind(14,rr$est,rr$se))
+> 
+> rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,estimand="ATE",M=1,BiasAdj=FALSE,Weight=1,Var.calc=0,
++              weights=w.educ,sample=TRUE);
+> summary(rr)
+
+Estimate...  3.147 
+AI SE......  1.0709 
+T-stat.....  2.9386 
+p.val......  0.0032973 
+
+Original number of observations (weighted)...  661.147 
+Original number of observations..............  445 
+Original number of treated obs (weighted)....  322.71 
+Original number of treated obs...............  185 
+Matched number of observations...............  661.147 
+Matched number of observations  (unweighted).  1155 
+
+> res  <- rbind(res,cbind(15,rr$est,rr$se))
+> 
+> 
+> V  <- lalonde$age
+> Z  <- cbind(lalonde$married, lalonde$age)
+> X  <- cbind(lalonde$age, lalonde$educ, lalonde$re74, lalonde$re75)
+> weight  <- w.educ
+> Weight.matrix  <- diag(4)
+> 
+> rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,
++              sample=FALSE, M=3, estimand="ATT", BiasAdj=TRUE, Weight=3, exact=TRUE,Var.calc=3,
++              weights=w.educ, Weight.matrix=Weight.matrix);
+> summary(rr)
+
+Estimate...  3.1657 
+AI SE......  0.26566 
+T-stat.....  11.916 
+p.val......  < 2.22e-16 
+
+Original number of observations (weighted)...  661.147 
+Original number of observations..............  445 
+Original number of treated obs (weighted)....  322.71 
+Original number of treated obs...............  185 
+Matched number of observations...............  60.015 
+Matched number of observations  (unweighted).  130 
+
+Number of obs dropped by 'exact' or 'caliper'  152 
+Weighted #obs dropped by 'exact' or 'caliper'  262.694 
+
+> res  <- rbind(res,cbind(75,rr$est,rr$se))
+> 
+> 
+> V  <- lalonde$married;
+> Z  <- cbind(lalonde$age, lalonde$re75);
+> X  <- cbind(lalonde$age, lalonde$educ, lalonde$re74);
+> 
+> rr  <- Match(Y=Y,Tr=T,X=X,Z=Z,V=V,
++              sample=TRUE, M=3, estimand="ATE", BiasAdj=TRUE, Weight=2, exact=TRUE,Var.calc=0,
++              weights=w.educ);
+> summary(rr)
+
+Estimate...  3.5046 
+AI SE......  0.57461 
+T-stat.....  6.099 
+p.val......  1.0672e-09 
+
+Original number of observations (weighted)...  661.147 
+Original number of observations..............  445 
+Original number of treated obs (weighted)....  322.71 
+Original number of treated obs...............  185 
+Matched number of observations...............  135.212 
+Matched number of observations  (unweighted).  305 
+
+Number of obs dropped by 'exact' or 'caliper'  366 
+Weighted #obs dropped by 'exact' or 'caliper'  525.935 
+
+> res  <- rbind(res,cbind(76,rr$est,rr$se))
+> 
+> cat("\nResults:\n")
+
+Results:
+> print(res)
+      [,1]     [,2]      [,3]
+ [1,]    1 1.785191 0.6867167
+ [2,]    2 1.714407 0.7401292
+ [3,]    4 1.536303 0.6619304
+ [4,]    5 1.726913 0.8366296
+ [5,]    6 1.705509 0.8200959
+ [6,]    7 1.592617 0.6847298
+ [7,]    8 1.714407 0.7401292
+ [8,]    9 1.630915 0.7452336
+ [9,]   10 1.719687 0.7436085
+[10,]   11 1.369289 0.4042281
+[11,]   12 1.369289 0.4042281
+[12,]   13 1.714407 0.7433846
+[13,]   14 1.714407 0.6962724
+[14,]   15 3.146960 1.0709149
+[15,]   75 3.165660 0.2656573
+[16,]   76 3.504580 0.5746139
+> 
+> 
+> proc.time()
+   user  system elapsed 
+  0.841   0.056   0.881 
diff --git a/tests/DehejiaWahba.R b/tests/DehejiaWahba.R
new file mode 100644
index 0000000..00ae38c
--- /dev/null
+++ b/tests/DehejiaWahba.R
@@ -0,0 +1,47 @@
+#
+# Replication of Dehejia and Wahba psid3 model
+#
+# Dehejia, Rajeev and Sadek Wahba. 1999.``Causal Effects in Non-Experimental Studies: Re-Evaluating the
+# Evaluation of Training Programs.''Journal of the American Statistical Association 94 (448): 1053-1062.
+#
+
+suppressMessages(library(Matching))
+
+# Replication of Dehejia and Wahba psid3 model.  
+
+# Dehejia, Rajeev and Sadek Wahba. 1999.``Causal Effects in
+# Non-Experimental Studies: Re-Evaluating the # Evaluation of Training
+# Programs.''Journal of the American Statistical Association 94 (448):
+# 1053-1062.  
+
+set.seed(10391)
+data(lalonde)
+
+#
+# Estimate the propensity model
+#
+glm1  <- glm(treat~age + I(age^2) + educ + I(educ^2) + black +
+             hisp + married + nodegr + re74  + I(re74^2) + re75 + I(re75^2) +
+             u74 + u75, family=binomial, data=lalonde)
+
+#
+#save data objects
+#
+X  <- glm1$fitted
+Y  <- lalonde$re78
+Tr  <- lalonde$treat
+
+#
+# one-to-one matching with replacement (the "M=1" option).
+# Estimating the treatment effect on the treated (the "estimand" option which defaults ATT).
+#
+rr  <- Match(Y=Y,Tr=Tr,X=X,M=1);
+summary(rr)
+
+#
+# Let's check for balance
+#
+mb  <- MatchBalance(treat~age + I(age^2) + educ + I(educ^2) + black +
+                    hisp + married + nodegr + re74  + I(re74^2) + re75 + I(re75^2) +
+                    u74 + u75, data=lalonde, match.out=rr, nboots=0)
+
diff --git a/tests/DehejiaWahba.Rout.save b/tests/DehejiaWahba.Rout.save
new file mode 100644
index 0000000..0822e04
--- /dev/null
+++ b/tests/DehejiaWahba.Rout.save
@@ -0,0 +1,354 @@
+
+R Under development (unstable) (2013-06-27 r63079) -- "Unsuffered Consequences"
+Copyright (C) 2013 The R Foundation for Statistical Computing
+Platform: x86_64-apple-darwin10.8.0 (64-bit)
+
+R is free software and comes with ABSOLUTELY NO WARRANTY.
+You are welcome to redistribute it under certain conditions.
+Type 'license()' or 'licence()' for distribution details.
+
+R is a collaborative project with many contributors.
+Type 'contributors()' for more information and
+'citation()' on how to cite R or R packages in publications.
+
+Type 'demo()' for some demos, 'help()' for on-line help, or
+'help.start()' for an HTML browser interface to help.
+Type 'q()' to quit R.
+
+> #
+> # Replication of Dehejia and Wahba psid3 model
+> #
+> # Dehejia, Rajeev and Sadek Wahba. 1999.``Causal Effects in Non-Experimental Studies: Re-Evaluating the
+> # Evaluation of Training Programs.''Journal of the American Statistical Association 94 (448): 1053-1062.
+> #
+> 
+> suppressMessages(library(Matching))
+> 
+> # Replication of Dehejia and Wahba psid3 model.  
+> 
+> # Dehejia, Rajeev and Sadek Wahba. 1999.``Causal Effects in
+> # Non-Experimental Studies: Re-Evaluating the # Evaluation of Training
+> # Programs.''Journal of the American Statistical Association 94 (448):
+> # 1053-1062.  
+> 
+> set.seed(10391)
+> data(lalonde)
+> 
+> #
+> # Estimate the propensity model
+> #
+> glm1  <- glm(treat~age + I(age^2) + educ + I(educ^2) + black +
++              hisp + married + nodegr + re74  + I(re74^2) + re75 + I(re75^2) +
++              u74 + u75, family=binomial, data=lalonde)
+> 
+> #
+> #save data objects
+> #
+> X  <- glm1$fitted
+> Y  <- lalonde$re78
+> Tr  <- lalonde$treat
+> 
+> #
+> # one-to-one matching with replacement (the "M=1" option).
+> # Estimating the treatment effect on the treated (the "estimand" option which defaults ATT).
+> #
+> rr  <- Match(Y=Y,Tr=Tr,X=X,M=1);
+> summary(rr)
+
+Estimate...  2153.3 
+AI SE......  825.4 
+T-stat.....  2.6088 
+p.val......  0.0090858 
+
+Original number of observations..............  445 
+Original number of treated obs...............  185 
+Matched number of observations...............  185 
+Matched number of observations  (unweighted).  346 
+
+> 
+> #
+> # Let's check for balance
+> #
+> mb  <- MatchBalance(treat~age + I(age^2) + educ + I(educ^2) + black +
++                     hisp + married + nodegr + re74  + I(re74^2) + re75 + I(re75^2) +
++                     u74 + u75, data=lalonde, match.out=rr, nboots=0)
+
+***** (V1) age *****
+                       Before Matching 	 	 After Matching
+mean treatment........     25.816 	 	     25.816 
+mean control..........     25.054 	 	     25.006 
+std mean diff.........     10.655 	 	     11.317 
+
+mean raw eQQ diff.....    0.94054 	 	    0.41618 
+med  raw eQQ diff.....          1 	 	          0 
+max  raw eQQ diff.....          7 	 	          9 
+
+mean eCDF diff........   0.025364 	 	   0.010597 
+med  eCDF diff........   0.022193 	 	  0.0086705 
+max  eCDF diff........   0.065177 	 	   0.049133 
+
+var ratio (Tr/Co).....     1.0278 	 	     1.0662 
+T-test p-value........    0.26594 	 	    0.23472 
+KS Naive p-value......     0.7481 	 	    0.79781 
+KS Statistic..........   0.065177 	 	   0.049133 
+
+
+***** (V2) I(age^2) *****
+                       Before Matching 	 	 After Matching
+mean treatment........     717.39 	 	     717.39 
+mean control..........     677.32 	 	     673.08 
+std mean diff.........     9.2937 	 	     10.275 
+
+mean raw eQQ diff.....     56.076 	 	     28.948 
+med  raw eQQ diff.....         43 	 	          0 
+max  raw eQQ diff.....        721 	 	        909 
+
+mean eCDF diff........   0.025364 	 	   0.010597 
+med  eCDF diff........   0.022193 	 	  0.0086705 
+max  eCDF diff........   0.065177 	 	   0.049133 
+
+var ratio (Tr/Co).....     1.0115 	 	    0.91516 
+T-test p-value........    0.33337 	 	    0.31819 
+KS Naive p-value......     0.7481 	 	    0.79781 
+KS Statistic..........   0.065177 	 	   0.049133 
+
+
+***** (V3) educ *****
+                       Before Matching 	 	 After Matching
+mean treatment........     10.346 	 	     10.346 
+mean control..........     10.088 	 	      10.48 
+std mean diff.........     12.806 	 	    -6.6749 
+
+mean raw eQQ diff.....    0.40541 	 	    0.16185 
+med  raw eQQ diff.....          0 	 	          0 
+max  raw eQQ diff.....          2 	 	          2 
+
+mean eCDF diff........   0.028698 	 	   0.011561 
+med  eCDF diff........   0.012682 	 	  0.0086705 
+max  eCDF diff........    0.12651 	 	   0.052023 
+
+var ratio (Tr/Co).....     1.5513 	 	     1.1917 
+T-test p-value........    0.15017 	 	    0.45021 
+KS Naive p-value......   0.062873 	 	    0.73726 
+KS Statistic..........    0.12651 	 	   0.052023 
+
+
+***** (V4) I(educ^2) *****
+                       Before Matching 	 	 After Matching
+mean treatment........     111.06 	 	     111.06 
+mean control..........     104.37 	 	     113.21 
+std mean diff.........     17.012 	 	     -5.466 
+
+mean raw eQQ diff.....     8.7189 	 	     3.1098 
+med  raw eQQ diff.....          0 	 	          0 
+max  raw eQQ diff.....         60 	 	         60 
+
+mean eCDF diff........   0.028698 	 	   0.011561 
+med  eCDF diff........   0.012682 	 	  0.0086705 
+max  eCDF diff........    0.12651 	 	   0.052023 
+
+var ratio (Tr/Co).....     1.6625 	 	     1.2716 
+T-test p-value........   0.053676 	 	    0.51046 
+KS Naive p-value......   0.062873 	 	    0.73726 
+KS Statistic..........    0.12651 	 	   0.052023 
+
+
+***** (V5) black *****
+                       Before Matching 	 	 After Matching
+mean treatment........    0.84324 	 	    0.84324 
+mean control..........    0.82692 	 	    0.85946 
+std mean diff.........     4.4767 	 	    -4.4482 
+
+mean raw eQQ diff.....   0.016216 	 	  0.0086705 
+med  raw eQQ diff.....          0 	 	          0 
+max  raw eQQ diff.....          1 	 	          1 
+
+mean eCDF diff........  0.0081601 	 	  0.0043353 
+med  eCDF diff........  0.0081601 	 	  0.0043353 
+max  eCDF diff........    0.01632 	 	  0.0086705 
+
+var ratio (Tr/Co).....    0.92503 	 	     1.0943 
+T-test p-value........    0.64736 	 	    0.57783 
+
+
+***** (V6) hisp *****
+                       Before Matching 	 	 After Matching
+mean treatment........   0.059459 	 	   0.059459 
+mean control..........    0.10769 	 	   0.048649 
+std mean diff.........    -20.341 	 	     4.5591 
+
+mean raw eQQ diff.....   0.048649 	 	  0.0057803 
+med  raw eQQ diff.....          0 	 	          0 
+max  raw eQQ diff.....          1 	 	          1 
+
+mean eCDF diff........   0.024116 	 	  0.0028902 
+med  eCDF diff........   0.024116 	 	  0.0028902 
+max  eCDF diff........   0.048233 	 	  0.0057803 
+
+var ratio (Tr/Co).....    0.58288 	 	     1.2083 
+T-test p-value........   0.064043 	 	    0.41443 
+
+
+***** (V7) married *****
+                       Before Matching 	 	 After Matching
+mean treatment........    0.18919 	 	    0.18919 
+mean control..........    0.15385 	 	    0.16667 
+std mean diff.........     8.9995 	 	      5.735 
+
+mean raw eQQ diff.....   0.037838 	 	   0.017341 
+med  raw eQQ diff.....          0 	 	          0 
+max  raw eQQ diff.....          1 	 	          1 
+
+mean eCDF diff........   0.017672 	 	  0.0086705 
+med  eCDF diff........   0.017672 	 	  0.0086705 
+max  eCDF diff........   0.035343 	 	   0.017341 
+
+var ratio (Tr/Co).....     1.1802 	 	     1.1045 
+T-test p-value........    0.33425 	 	    0.46741 
+
+
+***** (V8) nodegr *****
+                       Before Matching 	 	 After Matching
+mean treatment........    0.70811 	 	    0.70811 
+mean control..........    0.83462 	 	    0.69189 
+std mean diff.........    -27.751 	 	     3.5572 
+
+mean raw eQQ diff.....    0.12432 	 	   0.014451 
+med  raw eQQ diff.....          0 	 	          0 
+max  raw eQQ diff.....          1 	 	          1 
+
+mean eCDF diff........   0.063254 	 	  0.0072254 
+med  eCDF diff........   0.063254 	 	  0.0072254 
+max  eCDF diff........    0.12651 	 	   0.014451 
+
+var ratio (Tr/Co).....     1.4998 	 	    0.96957 
+T-test p-value........  0.0020368 	 	    0.49161 
+
+
+***** (V9) re74 *****
+                       Before Matching 	 	 After Matching
+mean treatment........     2095.6 	 	     2095.6 
+mean control..........       2107 	 	     1624.3 
+std mean diff.........   -0.23437 	 	     9.6439 
+
+mean raw eQQ diff.....     487.98 	 	     467.33 
+med  raw eQQ diff.....          0 	 	          0 
+max  raw eQQ diff.....       8413 	 	      12410 
+
+mean eCDF diff........   0.019223 	 	   0.019782 
+med  eCDF diff........     0.0158 	 	   0.018786 
+max  eCDF diff........   0.047089 	 	   0.046243 
+
+var ratio (Tr/Co).....     0.7381 	 	     2.2663 
+T-test p-value........    0.98186 	 	    0.22745 
+KS Naive p-value......    0.97023 	 	     0.8532 
+KS Statistic..........   0.047089 	 	   0.046243 
+
+
+***** (V10) I(re74^2) *****
+                       Before Matching 	 	 After Matching
+mean treatment........   28141434 	 	   28141434 
+mean control..........   36667413 	 	   13117852 
+std mean diff.........    -7.4721 	 	     13.167 
+
+mean raw eQQ diff.....   13311731 	 	   10899373 
+med  raw eQQ diff.....          0 	 	          0 
+max  raw eQQ diff.....  365146387 	 	  616156569 
+
+mean eCDF diff........   0.019223 	 	   0.019782 
+med  eCDF diff........     0.0158 	 	   0.018786 
+max  eCDF diff........   0.047089 	 	   0.046243 
+
+var ratio (Tr/Co).....    0.50382 	 	     7.9006 
+T-test p-value........    0.51322 	 	    0.08604 
+KS Naive p-value......    0.97023 	 	     0.8532 
+KS Statistic..........   0.047089 	 	   0.046243 
+
+
+***** (V11) re75 *****
+                       Before Matching 	 	 After Matching
+mean treatment........     1532.1 	 	     1532.1 
+mean control..........     1266.9 	 	     1297.6 
+std mean diff.........     8.2363 	 	     7.2827 
+
+mean raw eQQ diff.....     367.61 	 	     211.42 
+med  raw eQQ diff.....          0 	 	          0 
+max  raw eQQ diff.....     2110.2 	 	     8195.6 
+
+mean eCDF diff........   0.050834 	 	   0.023047 
+med  eCDF diff........   0.061954 	 	   0.023121 
+max  eCDF diff........    0.10748 	 	   0.057803 
+
+var ratio (Tr/Co).....     1.0763 	 	     1.4291 
+T-test p-value........    0.38527 	 	    0.33324 
+KS Naive p-value......    0.16449 	 	    0.60988 
+KS Statistic..........    0.10748 	 	   0.057803 
+
+
+***** (V12) I(re75^2) *****
+                       Before Matching 	 	 After Matching
+mean treatment........   12654753 	 	   12654753 
+mean control..........   11196530 	 	    8896263 
+std mean diff.........     2.6024 	 	     6.7076 
+
+mean raw eQQ diff.....    2840830 	 	    2887443 
+med  raw eQQ diff.....          0 	 	          0 
+max  raw eQQ diff.....  101657197 	 	  344942969 
+
+mean eCDF diff........   0.050834 	 	   0.023047 
+med  eCDF diff........   0.061954 	 	   0.023121 
+max  eCDF diff........    0.10748 	 	   0.057803 
+
+var ratio (Tr/Co).....     1.4609 	 	      3.559 
+T-test p-value........    0.77178 	 	    0.37741 
+KS Naive p-value......    0.16449 	 	    0.60988 
+KS Statistic..........    0.10748 	 	   0.057803 
+
+
+***** (V13) u74 *****
+                       Before Matching 	 	 After Matching
+mean treatment........    0.70811 	 	    0.70811 
+mean control..........       0.75 	 	    0.68458 
+std mean diff.........    -9.1895 	 	     5.1608 
+
+mean raw eQQ diff.....   0.037838 	 	   0.017341 
+med  raw eQQ diff.....          0 	 	          0 
+max  raw eQQ diff.....          1 	 	          1 
+
+mean eCDF diff........   0.020946 	 	  0.0086705 
+med  eCDF diff........   0.020946 	 	  0.0086705 
+max  eCDF diff........   0.041892 	 	   0.017341 
+
+var ratio (Tr/Co).....     1.1041 	 	    0.95721 
+T-test p-value........    0.33033 	 	    0.52298 
+
+
+***** (V14) u75 *****
+                       Before Matching 	 	 After Matching
+mean treatment........        0.6 	 	        0.6 
+mean control..........    0.68462 	 	    0.62072 
+std mean diff.........    -17.225 	 	    -4.2182 
+
+mean raw eQQ diff.....   0.081081 	 	   0.031792 
+med  raw eQQ diff.....          0 	 	          0 
+max  raw eQQ diff.....          1 	 	          1 
+
+mean eCDF diff........   0.042308 	 	   0.015896 
+med  eCDF diff........   0.042308 	 	   0.015896 
+max  eCDF diff........   0.084615 	 	   0.031792 
+
+var ratio (Tr/Co).....     1.1133 	 	     1.0194 
+T-test p-value........   0.068031 	 	    0.46507 
+
+
+Before Matching Minimum p.value: 0.0020368 
+Variable Name(s): nodegr  Number(s): 8 
+
+After Matching Minimum p.value: 0.08604 
+Variable Name(s): I(re74^2)  Number(s): 10 
+
+> 
+> 
+> proc.time()
+   user  system elapsed 
+  0.417   0.033   0.442 
diff --git a/tests/GenMatch.R b/tests/GenMatch.R
new file mode 100644
index 0000000..c9a67a4
--- /dev/null
+++ b/tests/GenMatch.R
@@ -0,0 +1,46 @@
+suppressMessages(library(rgenoud))
+suppressMessages(library(Matching))
+
+set.seed(3101)
+data(lalonde)
+attach(lalonde)
+
+#The covariates we want to match on
+X = cbind(age, educ, black, hisp, married, nodegr, u74, u75, re75, re74)
+
+#The covariates we want to obtain balance on
+BalanceMat <- cbind(age, educ, black, hisp, married, nodegr, u74, u75, re75, re74,
+                    I(re74*re75))
+
+#
+#Let's call GenMatch() to find the optimal weight to give each
+#covariate in 'X' so as we have achieved balance on the covariates in
+#'BalanceMat'. This is only an example so we want GenMatch to be quick
+#so the population size has been set to be only 16 via the 'pop.size'
+#option. This is *WAY* too small for actual problems.
+#For details see http://sekhon.berkeley.edu/papers/MatchingJSS.pdf.
+#
+genout <- GenMatch(Tr=treat, X=X, BalanceMatrix=BalanceMat, estimand="ATE", M=1,
+                   pop.size=16, max.generations=10, wait.generations=1,
+                   unif.seed=3392, int.seed=8282, print.level=0)
+print(genout)
+
+#The outcome variable
+Y=re78/1000
+
+#
+# Now that GenMatch() has found the optimal weights, let's estimate
+# our causal effect of interest using those weights
+#
+mout <- Match(Y=Y, Tr=treat, X=X, estimand="ATE", Weight.matrix=genout)
+summary(mout)
+
+#                        
+#Let's determine if balance has actually been obtained on the variables of interest
+#                        
+mb <- MatchBalance(treat~age +educ+black+ hisp+ married+ nodegr+ u74+ u75+
+                   re75+ re74+ I(re74*re75),
+                   match.out=mout, nboots=500)
+
+# For more examples see: http://sekhon.berkeley.edu/matching/R.
+
diff --git a/tests/GenMatch.Rout.save b/tests/GenMatch.Rout.save
new file mode 100644
index 0000000..785c1bd
--- /dev/null
+++ b/tests/GenMatch.Rout.save
@@ -0,0 +1,945 @@
+
+R version 3.0.2 (2013-09-25) -- "Frisbee Sailing"
+Copyright (C) 2013 The R Foundation for Statistical Computing
+Platform: x86_64-apple-darwin10.8.0 (64-bit)
+
+R is free software and comes with ABSOLUTELY NO WARRANTY.
+You are welcome to redistribute it under certain conditions.
+Type 'license()' or 'licence()' for distribution details.
+
+R is a collaborative project with many contributors.
+Type 'contributors()' for more information and
+'citation()' on how to cite R or R packages in publications.
+
+Type 'demo()' for some demos, 'help()' for on-line help, or
+'help.start()' for an HTML browser interface to help.
+Type 'q()' to quit R.
+
+> suppressMessages(library(rgenoud))
+> suppressMessages(library(Matching))
+> 
+> set.seed(3101)
+> data(lalonde)
+> attach(lalonde)
+> 
+> #The covariates we want to match on
+> X = cbind(age, educ, black, hisp, married, nodegr, u74, u75, re75, re74)
+> 
+> #The covariates we want to obtain balance on
+> BalanceMat <- cbind(age, educ, black, hisp, married, nodegr, u74, u75, re75, re74,
++                     I(re74*re75))
+> 
+> #
+> #Let's call GenMatch() to find the optimal weight to give each
+> #covariate in 'X' so as we have achieved balance on the covariates in
+> #'BalanceMat'. This is only an example so we want GenMatch to be quick
+> #so the population size has been set to be only 16 via the 'pop.size'
+> #option. This is *WAY* too small for actual problems.
+> #For details see http://sekhon.berkeley.edu/papers/MatchingJSS.pdf.
+> #
+> genout <- GenMatch(Tr=treat, X=X, BalanceMatrix=BalanceMat, estimand="ATE", M=1,
++                    pop.size=16, max.generations=10, wait.generations=1,
++                    unif.seed=3392, int.seed=8282, print.level=0)
+> print(genout)
+$value
+ [1] 0.2998530 0.4365007 0.4653266 0.4653266 0.5272292 0.5272292 0.5547330
+ [8] 0.6548664 0.6548664 0.7136179 0.8956026 0.9464618 0.9516643 0.9707070
+[15] 0.9990218 0.9999971 1.0000000 1.0000000 1.0000000 1.0000000 1.0000000
+[22] 1.0000000
+
+$par
+ [1] 580.84914 356.15752 312.13349 343.83427 954.89910 591.73436 106.19145
+ [8]  56.99953 209.22764 735.57074
+
+$Weight.matrix
+          [,1]     [,2]     [,3]     [,4]     [,5]     [,6]     [,7]     [,8]
+ [1,] 580.8491   0.0000   0.0000   0.0000   0.0000   0.0000   0.0000  0.00000
+ [2,]   0.0000 356.1575   0.0000   0.0000   0.0000   0.0000   0.0000  0.00000
+ [3,]   0.0000   0.0000 312.1335   0.0000   0.0000   0.0000   0.0000  0.00000
+ [4,]   0.0000   0.0000   0.0000 343.8343   0.0000   0.0000   0.0000  0.00000
+ [5,]   0.0000   0.0000   0.0000   0.0000 954.8991   0.0000   0.0000  0.00000
+ [6,]   0.0000   0.0000   0.0000   0.0000   0.0000 591.7344   0.0000  0.00000
+ [7,]   0.0000   0.0000   0.0000   0.0000   0.0000   0.0000 106.1915  0.00000
+ [8,]   0.0000   0.0000   0.0000   0.0000   0.0000   0.0000   0.0000 56.99953
+ [9,]   0.0000   0.0000   0.0000   0.0000   0.0000   0.0000   0.0000  0.00000
+[10,]   0.0000   0.0000   0.0000   0.0000   0.0000   0.0000   0.0000  0.00000
+          [,9]    [,10]
+ [1,]   0.0000   0.0000
+ [2,]   0.0000   0.0000
+ [3,]   0.0000   0.0000
+ [4,]   0.0000   0.0000
+ [5,]   0.0000   0.0000
+ [6,]   0.0000   0.0000
+ [7,]   0.0000   0.0000
+ [8,]   0.0000   0.0000
+ [9,] 209.2276   0.0000
+[10,]   0.0000 735.5707
+
+$matches
+       [,1] [,2]      [,3]
+  [1,]    1  193 1.0000000
+  [2,]    2  231 1.0000000
+  [3,]    3  261 1.0000000
+  [4,]    4  254 1.0000000
+  [5,]    5  230 1.0000000
+  [6,]    6  188 0.5000000
+  [7,]    6  244 0.5000000
+  [8,]    7  256 0.5000000
+  [9,]    7  266 0.5000000
+ [10,]    8  279 1.0000000
+ [11,]    9  196 1.0000000
+ [12,]   10  277 1.0000000
+ [13,]   11  288 1.0000000
+ [14,]   12  196 1.0000000
+ [15,]   13  317 1.0000000
+ [16,]   14  274 0.3333333
+ [17,]   14  301 0.3333333
+ [18,]   14  315 0.3333333
+ [19,]   15  329 1.0000000
+ [20,]   16  323 0.5000000
+ [21,]   16  324 0.5000000
+ [22,]   17  280 1.0000000
+ [23,]   18  186 0.2500000
+ [24,]   18  232 0.2500000
+ [25,]   18  294 0.2500000
+ [26,]   18  312 0.2500000
+ [27,]   19  201 1.0000000
+ [28,]   20  311 1.0000000
+ [29,]   21  235 0.2500000
+ [30,]   21  240 0.2500000
+ [31,]   21  290 0.2500000
+ [32,]   21  305 0.2500000
+ [33,]   22  372 1.0000000
+ [34,]   23  298 1.0000000
+ [35,]   24  234 0.5000000
+ [36,]   24  243 0.5000000
+ [37,]   25  327 0.3333333
+ [38,]   25  337 0.3333333
+ [39,]   25  356 0.3333333
+ [40,]   26  293 0.5000000
+ [41,]   26  302 0.5000000
+ [42,]   27  204 0.3333333
+ [43,]   27  219 0.3333333
+ [44,]   27  283 0.3333333
+ [45,]   28  223 1.0000000
+ [46,]   29  328 0.2000000
+ [47,]   29  333 0.2000000
+ [48,]   29  334 0.2000000
+ [49,]   29  345 0.2000000
+ [50,]   29  354 0.2000000
+ [51,]   30  234 0.5000000
+ [52,]   30  243 0.5000000
+ [53,]   31  328 0.2000000
+ [54,]   31  333 0.2000000
+ [55,]   31  334 0.2000000
+ [56,]   31  345 0.2000000
+ [57,]   31  354 0.2000000
+ [58,]   32  263 1.0000000
+ [59,]   33  271 1.0000000
+ [60,]   34  218 1.0000000
+ [61,]   35  253 0.5000000
+ [62,]   35  284 0.5000000
+ [63,]   36  365 1.0000000
+ [64,]   37  250 1.0000000
+ [65,]   38  303 1.0000000
+ [66,]   39  211 1.0000000
+ [67,]   40  202 0.3333333
+ [68,]   40  249 0.3333333
+ [69,]   40  297 0.3333333
+ [70,]   41  218 0.5000000
+ [71,]   41  266 0.5000000
+ [72,]   42  341 1.0000000
+ [73,]   43  318 0.5000000
+ [74,]   43  339 0.5000000
+ [75,]   44  260 1.0000000
+ [76,]   45  237 0.2500000
+ [77,]   45  335 0.2500000
+ [78,]   45  347 0.2500000
+ [79,]   45  353 0.2500000
+ [80,]   46  271 1.0000000
+ [81,]   47  318 0.5000000
+ [82,]   47  339 0.5000000
+ [83,]   48  344 0.5000000
+ [84,]   48  346 0.5000000
+ [85,]   49  250 1.0000000
+ [86,]   50  256 0.5000000
+ [87,]   50  266 0.5000000
+ [88,]   51  208 0.5000000
+ [89,]   51  255 0.5000000
+ [90,]   52  293 0.5000000
+ [91,]   52  302 0.5000000
+ [92,]   53  321 0.3333333
+ [93,]   53  330 0.3333333
+ [94,]   53  351 0.3333333
+ [95,]   54  253 0.5000000
+ [96,]   54  284 0.5000000
+ [97,]   55  293 0.5000000
+ [98,]   55  302 0.5000000
+ [99,]   56  328 0.2000000
+[100,]   56  333 0.2000000
+[101,]   56  334 0.2000000
+[102,]   56  345 0.2000000
+[103,]   56  354 0.2000000
+[104,]   57  205 1.0000000
+[105,]   58  198 1.0000000
+[106,]   59  276 1.0000000
+[107,]   60  199 1.0000000
+[108,]   61  318 0.5000000
+[109,]   61  339 0.5000000
+[110,]   62  255 1.0000000
+[111,]   63  217 1.0000000
+[112,]   64  254 1.0000000
+[113,]   65  250 1.0000000
+[114,]   66  197 1.0000000
+[115,]   67  254 1.0000000
+[116,]   68  192 1.0000000
+[117,]   69  211 1.0000000
+[118,]   70  304 1.0000000
+[119,]   71  197 1.0000000
+[120,]   72  365 1.0000000
+[121,]   73  329 1.0000000
+[122,]   74  253 0.5000000
+[123,]   74  284 0.5000000
+[124,]   75  304 1.0000000
+[125,]   76  199 1.0000000
+[126,]   77  266 1.0000000
+[127,]   78  188 0.2500000
+[128,]   78  244 0.2500000
+[129,]   78  343 0.2500000
+[130,]   78  349 0.2500000
+[131,]   79  233 0.3333333
+[132,]   79  273 0.3333333
+[133,]   79  275 0.3333333
+[134,]   80  252 1.0000000
+[135,]   81  253 0.5000000
+[136,]   81  284 0.5000000
+[137,]   82  229 1.0000000
+[138,]   83  372 1.0000000
+[139,]   84  280 1.0000000
+[140,]   85  208 1.0000000
+[141,]   86  221 1.0000000
+[142,]   87  203 1.0000000
+[143,]   88  226 1.0000000
+[144,]   89  241 1.0000000
+[145,]   90  209 1.0000000
+[146,]   91  293 0.5000000
+[147,]   91  302 0.5000000
+[148,]   92  328 0.2000000
+[149,]   92  333 0.2000000
+[150,]   92  334 0.2000000
+[151,]   92  345 0.2000000
+[152,]   92  354 0.2000000
+[153,]   93  204 0.3333333
+[154,]   93  219 0.3333333
+[155,]   93  283 0.3333333
+[156,]   94  218 0.5000000
+[157,]   94  266 0.5000000
+[158,]   95  282 1.0000000
+[159,]   96  187 0.5000000
+[160,]   96  241 0.5000000
+[161,]   97  189 0.1250000
+[162,]   97  191 0.1250000
+[163,]   97  269 0.1250000
+[164,]   97  325 0.1250000
+[165,]   97  326 0.1250000
+[166,]   97  332 0.1250000
+[167,]   97  338 0.1250000
+[168,]   97  350 0.1250000
+[169,]   98  365 1.0000000
+[170,]   99  220 0.2500000
+[171,]   99  238 0.2500000
+[172,]   99  248 0.2500000
+[173,]   99  296 0.2500000
+[174,]  100  223 1.0000000
+[175,]  101  202 0.3333333
+[176,]  101  249 0.3333333
+[177,]  101  297 0.3333333
+[178,]  102  247 0.5000000
+[179,]  102  281 0.5000000
+[180,]  103  204 0.3333333
+[181,]  103  219 0.3333333
+[182,]  103  283 0.3333333
+[183,]  104  321 0.3333333
+[184,]  104  330 0.3333333
+[185,]  104  351 0.3333333
+[186,]  105  335 0.3333333
+[187,]  105  347 0.3333333
+[188,]  105  353 0.3333333
+[189,]  106  207 1.0000000
+[190,]  107  280 1.0000000
+[191,]  108  344 0.5000000
+[192,]  108  346 0.5000000
+[193,]  109  242 1.0000000
+[194,]  110  274 0.3333333
+[195,]  110  301 0.3333333
+[196,]  110  315 0.3333333
+[197,]  111  386 1.0000000
+[198,]  112  390 1.0000000
+[199,]  113  393 1.0000000
+[200,]  114  380 1.0000000
+[201,]  115  382 1.0000000
+[202,]  116  371 1.0000000
+[203,]  117  405 1.0000000
+[204,]  118  378 1.0000000
+[205,]  119  379 1.0000000
+[206,]  120  402 1.0000000
+[207,]  121  304 1.0000000
+[208,]  122  369 1.0000000
+[209,]  123  373 1.0000000
+[210,]  124  422 1.0000000
+[211,]  125  395 1.0000000
+[212,]  126  295 1.0000000
+[213,]  127  402 1.0000000
+[214,]  128  272 1.0000000
+[215,]  129  433 1.0000000
+[216,]  130  414 1.0000000
+[217,]  131  368 1.0000000
+[218,]  132  392 1.0000000
+[219,]  133  418 1.0000000
+[220,]  134  413 1.0000000
+[221,]  135  418 1.0000000
+[222,]  136  389 1.0000000
+[223,]  137  295 1.0000000
+[224,]  138  408 1.0000000
+[225,]  139  409 1.0000000
+[226,]  140  395 1.0000000
+[227,]  141  415 1.0000000
+[228,]  142  409 1.0000000
+[229,]  143  388 1.0000000
+[230,]  144  417 1.0000000
+[231,]  145  372 1.0000000
+[232,]  146  414 1.0000000
+[233,]  147  407 1.0000000
+[234,]  148  385 1.0000000
+[235,]  149  418 1.0000000
+[236,]  150  386 1.0000000
+[237,]  151  389 1.0000000
+[238,]  152  409 1.0000000
+[239,]  153  408 1.0000000
+[240,]  154  402 1.0000000
+[241,]  155  211 1.0000000
+[242,]  156  409 1.0000000
+[243,]  157  407 1.0000000
+[244,]  158  409 1.0000000
+[245,]  159  370 1.0000000
+[246,]  160  423 1.0000000
+[247,]  161  408 1.0000000
+[248,]  162  410 1.0000000
+[249,]  163  421 1.0000000
+[250,]  164  389 1.0000000
+[251,]  165  426 1.0000000
+[252,]  166  376 1.0000000
+[253,]  167  361 1.0000000
+[254,]  168  434 1.0000000
+[255,]  169  418 1.0000000
+[256,]  170  415 1.0000000
+[257,]  171  408 1.0000000
+[258,]  172  422 1.0000000
+[259,]  173  387 1.0000000
+[260,]  174  416 1.0000000
+[261,]  175  441 1.0000000
+[262,]  176  385 1.0000000
+[263,]  177  267 1.0000000
+[264,]  178  374 1.0000000
+[265,]  179  371 1.0000000
+[266,]  180  432 1.0000000
+[267,]  181  428 1.0000000
+[268,]  182  428 1.0000000
+[269,]  183  440 1.0000000
+[270,]  184  440 1.0000000
+[271,]  185  444 1.0000000
+[272,]   18  186 1.0000000
+[273,]   96  187 1.0000000
+[274,]    6  188 1.0000000
+[275,]   97  189 1.0000000
+[276,]   95  190 1.0000000
+[277,]   97  191 1.0000000
+[278,]   68  192 1.0000000
+[279,]    1  193 0.3333333
+[280,]   52  193 0.3333333
+[281,]   91  193 0.3333333
+[282,]   87  194 1.0000000
+[283,]   63  195 1.0000000
+[284,]   12  196 1.0000000
+[285,]   66  197 1.0000000
+[286,]  126  198 1.0000000
+[287,]   60  199 1.0000000
+[288,]   13  200 1.0000000
+[289,]    3  201 1.0000000
+[290,]   40  202 0.5000000
+[291,]  101  202 0.5000000
+[292,]   87  203 1.0000000
+[293,]   27  204 0.3333333
+[294,]   93  204 0.3333333
+[295,]  103  204 0.3333333
+[296,]   57  205 1.0000000
+[297,]  128  206 1.0000000
+[298,]  106  207 1.0000000
+[299,]   85  208 1.0000000
+[300,]   90  209 1.0000000
+[301,]    8  210 0.5000000
+[302,]  109  210 0.5000000
+[303,]    1  211 0.3333333
+[304,]   52  211 0.3333333
+[305,]   91  211 0.3333333
+[306,]   87  212 1.0000000
+[307,]    3  213 1.0000000
+[308,]    2  214 1.0000000
+[309,]   38  215 1.0000000
+[310,]    3  216 1.0000000
+[311,]   63  217 1.0000000
+[312,]   34  218 1.0000000
+[313,]   27  219 0.3333333
+[314,]   93  219 0.3333333
+[315,]  103  219 0.3333333
+[316,]   99  220 1.0000000
+[317,]    8  221 0.5000000
+[318,]   86  221 0.5000000
+[319,]   16  222 1.0000000
+[320,]    2  223 1.0000000
+[321,]  102  224 1.0000000
+[322,]    2  225 1.0000000
+[323,]   88  226 1.0000000
+[324,]   57  227 1.0000000
+[325,]   63  228 1.0000000
+[326,]   34  229 0.5000000
+[327,]   82  229 0.5000000
+[328,]    5  230 1.0000000
+[329,]    2  231 1.0000000
+[330,]   18  232 1.0000000
+[331,]   63  233 1.0000000
+[332,]   24  234 0.5000000
+[333,]   30  234 0.5000000
+[334,]   21  235 1.0000000
+[335,]   87  236 1.0000000
+[336,]   45  237 0.5000000
+[337,]   80  237 0.5000000
+[338,]   99  238 1.0000000
+[339,]   33  239 0.5000000
+[340,]   46  239 0.5000000
+[341,]   21  240 1.0000000
+[342,]   96  241 1.0000000
+[343,]  109  242 1.0000000
+[344,]   24  243 0.5000000
+[345,]   30  243 0.5000000
+[346,]    6  244 1.0000000
+[347,]    4  245 0.3333333
+[348,]   64  245 0.3333333
+[349,]   67  245 0.3333333
+[350,]    2  246 1.0000000
+[351,]  102  247 1.0000000
+[352,]   99  248 1.0000000
+[353,]   40  249 0.5000000
+[354,]  101  249 0.5000000
+[355,]   37  250 0.5000000
+[356,]   49  250 0.5000000
+[357,]   63  251 1.0000000
+[358,]   80  252 1.0000000
+[359,]   35  253 0.2500000
+[360,]   54  253 0.2500000
+[361,]   74  253 0.2500000
+[362,]   81  253 0.2500000
+[363,]    4  254 0.3333333
+[364,]   64  254 0.3333333
+[365,]   67  254 0.3333333
+[366,]   62  255 1.0000000
+[367,]    7  256 0.1666667
+[368,]   35  256 0.1666667
+[369,]   50  256 0.1666667
+[370,]   54  256 0.1666667
+[371,]   74  256 0.1666667
+[372,]   81  256 0.1666667
+[373,]   18  257 1.0000000
+[374,]   90  258 1.0000000
+[375,]    3  259 1.0000000
+[376,]   44  260 1.0000000
+[377,]    3  261 1.0000000
+[378,]   90  262 1.0000000
+[379,]   32  263 1.0000000
+[380,]   16  264 1.0000000
+[381,]    8  265 1.0000000
+[382,]   77  266 1.0000000
+[383,]  177  267 1.0000000
+[384,]    8  268 0.5000000
+[385,]  109  268 0.5000000
+[386,]   97  269 1.0000000
+[387,]  100  270 1.0000000
+[388,]   33  271 0.5000000
+[389,]   46  271 0.5000000
+[390,]   33  272 0.5000000
+[391,]   46  272 0.5000000
+[392,]   63  273 1.0000000
+[393,]   14  274 1.0000000
+[394,]  106  275 1.0000000
+[395,]   59  276 1.0000000
+[396,]   59  277 1.0000000
+[397,]   90  278 1.0000000
+[398,]    8  279 1.0000000
+[399,]   17  280 0.3333333
+[400,]   84  280 0.3333333
+[401,]  107  280 0.3333333
+[402,]  102  281 1.0000000
+[403,]   95  282 1.0000000
+[404,]   27  283 0.3333333
+[405,]   93  283 0.3333333
+[406,]  103  283 0.3333333
+[407,]   35  284 0.2500000
+[408,]   54  284 0.2500000
+[409,]   74  284 0.2500000
+[410,]   81  284 0.2500000
+[411,]   38  285 1.0000000
+[412,]   63  286 1.0000000
+[413,]   18  287 1.0000000
+[414,]   11  288 1.0000000
+[415,]   52  289 0.5000000
+[416,]   91  289 0.5000000
+[417,]   21  290 1.0000000
+[418,]    8  291 1.0000000
+[419,]  102  292 1.0000000
+[420,]   26  293 1.0000000
+[421,]   18  294 1.0000000
+[422,]   14  295 1.0000000
+[423,]   99  296 1.0000000
+[424,]   40  297 0.5000000
+[425,]  101  297 0.5000000
+[426,]   68  298 1.0000000
+[427,]   37  299 0.5000000
+[428,]   49  299 0.5000000
+[429,]   38  300 1.0000000
+[430,]   14  301 1.0000000
+[431,]   26  302 1.0000000
+[432,]   38  303 1.0000000
+[433,]   17  304 0.2500000
+[434,]   70  304 0.2500000
+[435,]   84  304 0.2500000
+[436,]  107  304 0.2500000
+[437,]   21  305 1.0000000
+[438,]   95  306 1.0000000
+[439,]  100  307 1.0000000
+[440,]   13  308 1.0000000
+[441,]  106  309 1.0000000
+[442,]    5  310 1.0000000
+[443,]   20  311 1.0000000
+[444,]   18  312 1.0000000
+[445,]   96  313 1.0000000
+[446,]   44  314 1.0000000
+[447,]   14  315 1.0000000
+[448,]   90  316 1.0000000
+[449,]   13  317 1.0000000
+[450,]   43  318 0.3333333
+[451,]   47  318 0.3333333
+[452,]   61  318 0.3333333
+[453,]    2  319 1.0000000
+[454,]   87  320 1.0000000
+[455,]   53  321 0.5000000
+[456,]  104  321 0.5000000
+[457,]   53  322 0.5000000
+[458,]  104  322 0.5000000
+[459,]   16  323 1.0000000
+[460,]   16  324 1.0000000
+[461,]   97  325 1.0000000
+[462,]   97  326 1.0000000
+[463,]   25  327 1.0000000
+[464,]   29  328 0.2500000
+[465,]   31  328 0.2500000
+[466,]   56  328 0.2500000
+[467,]   92  328 0.2500000
+[468,]   15  329 1.0000000
+[469,]   53  330 0.5000000
+[470,]  104  330 0.5000000
+[471,]    2  331 1.0000000
+[472,]   97  332 1.0000000
+[473,]   29  333 0.2500000
+[474,]   31  333 0.2500000
+[475,]   56  333 0.2500000
+[476,]   92  333 0.2500000
+[477,]   29  334 0.2500000
+[478,]   31  334 0.2500000
+[479,]   56  334 0.2500000
+[480,]   92  334 0.2500000
+[481,]  105  335 1.0000000
+[482,]   42  336 1.0000000
+[483,]   25  337 1.0000000
+[484,]   97  338 1.0000000
+[485,]   43  339 0.3333333
+[486,]   47  339 0.3333333
+[487,]   61  339 0.3333333
+[488,]   87  340 1.0000000
+[489,]   42  341 1.0000000
+[490,]   60  342 1.0000000
+[491,]   11  343 0.5000000
+[492,]   78  343 0.5000000
+[493,]   48  344 0.5000000
+[494,]  108  344 0.5000000
+[495,]   29  345 0.2500000
+[496,]   31  345 0.2500000
+[497,]   56  345 0.2500000
+[498,]   92  345 0.2500000
+[499,]   48  346 0.5000000
+[500,]  108  346 0.5000000
+[501,]  105  347 1.0000000
+[502,]  128  348 1.0000000
+[503,]   11  349 0.5000000
+[504,]   78  349 0.5000000
+[505,]   97  350 1.0000000
+[506,]   53  351 0.5000000
+[507,]  104  351 0.5000000
+[508,]    2  352 1.0000000
+[509,]  105  353 1.0000000
+[510,]   29  354 0.2500000
+[511,]   31  354 0.2500000
+[512,]   56  354 0.2500000
+[513,]   92  354 0.2500000
+[514,]    2  355 1.0000000
+[515,]   25  356 1.0000000
+[516,]  131  357 1.0000000
+[517,]  138  358 1.0000000
+[518,]  114  359 1.0000000
+[519,]  111  360 1.0000000
+[520,]  167  361 1.0000000
+[521,]  143  362 1.0000000
+[522,]  175  363 1.0000000
+[523,]   79  364 0.5000000
+[524,]   86  364 0.5000000
+[525,]   19  365 1.0000000
+[526,]  118  366 1.0000000
+[527,]  114  367 1.0000000
+[528,]  138  368 1.0000000
+[529,]  122  369 1.0000000
+[530,]  159  370 1.0000000
+[531,]  116  371 1.0000000
+[532,]  145  372 1.0000000
+[533,]  123  373 1.0000000
+[534,]  136  374 1.0000000
+[535,]  110  375 1.0000000
+[536,]   42  376 1.0000000
+[537,]  130  377 1.0000000
+[538,]  118  378 1.0000000
+[539,]  119  379 1.0000000
+[540,]  114  380 1.0000000
+[541,]  122  381 1.0000000
+[542,]   38  382 1.0000000
+[543,]  148  383 1.0000000
+[544,]  145  384 1.0000000
+[545,]  148  385 1.0000000
+[546,]  150  386 1.0000000
+[547,]  112  387 1.0000000
+[548,]  143  388 1.0000000
+[549,]  136  389 1.0000000
+[550,]  112  390 1.0000000
+[551,]  150  391 1.0000000
+[552,]  132  392 1.0000000
+[553,]  113  393 1.0000000
+[554,]  118  394 1.0000000
+[555,]  125  395 1.0000000
+[556,]  125  396 1.0000000
+[557,]  136  397 1.0000000
+[558,]  134  398 1.0000000
+[559,]  112  399 1.0000000
+[560,]  141  400 1.0000000
+[561,]  132  401 1.0000000
+[562,]  127  402 1.0000000
+[563,]  142  403 1.0000000
+[564,]  119  404 1.0000000
+[565,]  117  405 1.0000000
+[566,]  146  406 1.0000000
+[567,]  157  407 1.0000000
+[568,]  138  408 1.0000000
+[569,]  158  409 1.0000000
+[570,]  153  410 1.0000000
+[571,]  168  411 1.0000000
+[572,]  100  412 1.0000000
+[573,]  134  413 1.0000000
+[574,]  146  414 1.0000000
+[575,]  141  415 1.0000000
+[576,]  146  416 1.0000000
+[577,]  144  417 1.0000000
+[578,]  149  418 1.0000000
+[579,]  149  419 1.0000000
+[580,]  150  420 1.0000000
+[581,]  163  421 1.0000000
+[582,]  172  422 1.0000000
+[583,]  160  423 1.0000000
+[584,]    3  424 1.0000000
+[585,]  170  425 1.0000000
+[586,]  158  426 1.0000000
+[587,]  163  427 1.0000000
+[588,]  181  428 1.0000000
+[589,]  175  429 1.0000000
+[590,]  170  430 1.0000000
+[591,]  174  431 1.0000000
+[592,]  180  432 1.0000000
+[593,]  129  433 1.0000000
+[594,]  168  434 1.0000000
+[595,]  163  435 1.0000000
+[596,]  149  436 1.0000000
+[597,]  163  437 1.0000000
+[598,]  169  438 1.0000000
+[599,]  175  439 1.0000000
+[600,]  183  440 1.0000000
+[601,]  175  441 1.0000000
+[602,]  175  442 1.0000000
+[603,]  173  443 1.0000000
+[604,]  184  444 1.0000000
+[605,]  185  445 1.0000000
+
+$ecaliper
+NULL
+
+attr(,"class")
+[1] "GenMatch"
+> 
+> #The outcome variable
+> Y=re78/1000
+> 
+> #
+> # Now that GenMatch() has found the optimal weights, let's estimate
+> # our causal effect of interest using those weights
+> #
+> mout <- Match(Y=Y, Tr=treat, X=X, estimand="ATE", Weight.matrix=genout)
+> summary(mout)
+
+Estimate...  1.9382 
+AI SE......  0.77739 
+T-stat.....  2.4932 
+p.val......  0.012659 
+
+Original number of observations..............  445 
+Original number of treated obs...............  185 
+Matched number of observations...............  445 
+Matched number of observations  (unweighted).  605 
+
+> 
+> #                        
+> #Let's determine if balance has actually been obtained on the variables of interest
+> #                        
+> mb <- MatchBalance(treat~age +educ+black+ hisp+ married+ nodegr+ u74+ u75+
++                    re75+ re74+ I(re74*re75),
++                    match.out=mout, nboots=500)
+
+***** (V1) age *****
+                       Before Matching 	 	 After Matching
+mean treatment........     25.816 	 	     25.141 
+mean control..........     25.054 	 	      25.13 
+std mean diff.........     10.655 	 	    0.16669 
+
+mean raw eQQ diff.....    0.94054 	 	    0.34545 
+med  raw eQQ diff.....          1 	 	          0 
+max  raw eQQ diff.....          7 	 	          8 
+
+mean eCDF diff........   0.025364 	 	  0.0094312 
+med  eCDF diff........   0.022193 	 	  0.0066116 
+max  eCDF diff........   0.065177 	 	   0.033058 
+
+var ratio (Tr/Co).....     1.0278 	 	    0.96544 
+T-test p-value........    0.26594 	 	    0.94646 
+KS Bootstrap p-value..       0.58 	 	      0.732 
+KS Naive p-value......     0.7481 	 	     0.8956 
+KS Statistic..........   0.065177 	 	   0.033058 
+
+
+***** (V2) educ *****
+                       Before Matching 	 	 After Matching
+mean treatment........     10.346 	 	     10.196 
+mean control..........     10.088 	 	     10.225 
+std mean diff.........     12.806 	 	    -1.7112 
+
+mean raw eQQ diff.....    0.40541 	 	   0.076033 
+med  raw eQQ diff.....          0 	 	          0 
+max  raw eQQ diff.....          2 	 	          2 
+
+mean eCDF diff........   0.028698 	 	  0.0054309 
+med  eCDF diff........   0.012682 	 	  0.0033058 
+max  eCDF diff........    0.12651 	 	   0.028099 
+
+var ratio (Tr/Co).....     1.5513 	 	     1.0389 
+T-test p-value........    0.15017 	 	     0.4365 
+KS Bootstrap p-value..      0.012 	 	      0.626 
+KS Naive p-value......   0.062873 	 	    0.97071 
+KS Statistic..........    0.12651 	 	   0.028099 
+
+
+***** (V3) black *****
+                       Before Matching 	 	 After Matching
+mean treatment........    0.84324 	 	     0.8382 
+mean control..........    0.82692 	 	    0.84045 
+std mean diff.........     4.4767 	 	   -0.60952 
+
+mean raw eQQ diff.....   0.016216 	 	  0.0016529 
+med  raw eQQ diff.....          0 	 	          0 
+max  raw eQQ diff.....          1 	 	          1 
+
+mean eCDF diff........  0.0081601 	 	 0.00082645 
+med  eCDF diff........  0.0081601 	 	 0.00082645 
+max  eCDF diff........    0.01632 	 	  0.0016529 
+
+var ratio (Tr/Co).....    0.92503 	 	     1.0114 
+T-test p-value........    0.64736 	 	    0.65487 
+
+
+***** (V4) hisp *****
+                       Before Matching 	 	 After Matching
+mean treatment........   0.059459 	 	    0.08764 
+mean control..........    0.10769 	 	    0.08764 
+std mean diff.........    -20.341 	 	          0 
+
+mean raw eQQ diff.....   0.048649 	 	          0 
+med  raw eQQ diff.....          0 	 	          0 
+max  raw eQQ diff.....          1 	 	          0 
+
+mean eCDF diff........   0.024116 	 	          0 
+med  eCDF diff........   0.024116 	 	          0 
+max  eCDF diff........   0.048233 	 	          0 
+
+var ratio (Tr/Co).....    0.58288 	 	          1 
+T-test p-value........   0.064043 	 	          1 
+
+
+***** (V5) married *****
+                       Before Matching 	 	 After Matching
+mean treatment........    0.18919 	 	    0.16854 
+mean control..........    0.15385 	 	    0.16854 
+std mean diff.........     8.9995 	 	          0 
+
+mean raw eQQ diff.....   0.037838 	 	          0 
+med  raw eQQ diff.....          0 	 	          0 
+max  raw eQQ diff.....          1 	 	          0 
+
+mean eCDF diff........   0.017672 	 	          0 
+med  eCDF diff........   0.017672 	 	          0 
+max  eCDF diff........   0.035343 	 	          0 
+
+var ratio (Tr/Co).....     1.1802 	 	          1 
+T-test p-value........    0.33425 	 	          1 
+
+
+***** (V6) nodegr *****
+                       Before Matching 	 	 After Matching
+mean treatment........    0.70811 	 	    0.78202 
+mean control..........    0.83462 	 	    0.78202 
+std mean diff.........    -27.751 	 	          0 
+
+mean raw eQQ diff.....    0.12432 	 	          0 
+med  raw eQQ diff.....          0 	 	          0 
+max  raw eQQ diff.....          1 	 	          0 
+
+mean eCDF diff........   0.063254 	 	          0 
+med  eCDF diff........   0.063254 	 	          0 
+max  eCDF diff........    0.12651 	 	          0 
+
+var ratio (Tr/Co).....     1.4998 	 	          1 
+T-test p-value........  0.0020368 	 	          1 
+
+
+***** (V7) u74 *****
+                       Before Matching 	 	 After Matching
+mean treatment........    0.70811 	 	    0.73483 
+mean control..........       0.75 	 	    0.73933 
+std mean diff.........    -9.1895 	 	     -1.017 
+
+mean raw eQQ diff.....   0.037838 	 	  0.0066116 
+med  raw eQQ diff.....          0 	 	          0 
+max  raw eQQ diff.....          1 	 	          1 
+
+mean eCDF diff........   0.020946 	 	  0.0033058 
+med  eCDF diff........   0.020946 	 	  0.0033058 
+max  eCDF diff........   0.041892 	 	  0.0066116 
+
+var ratio (Tr/Co).....     1.1041 	 	     1.0111 
+T-test p-value........    0.33033 	 	    0.52723 
+
+
+***** (V8) u75 *****
+                       Before Matching 	 	 After Matching
+mean treatment........        0.6 	 	     0.6427 
+mean control..........    0.68462 	 	    0.65169 
+std mean diff.........    -17.225 	 	    -1.8737 
+
+mean raw eQQ diff.....   0.081081 	 	  0.0049587 
+med  raw eQQ diff.....          0 	 	          0 
+max  raw eQQ diff.....          1 	 	          1 
+
+mean eCDF diff........   0.042308 	 	  0.0024793 
+med  eCDF diff........   0.042308 	 	  0.0024793 
+max  eCDF diff........   0.084615 	 	  0.0049587 
+
+var ratio (Tr/Co).....     1.1133 	 	     1.0117 
+T-test p-value........   0.068031 	 	    0.46533 
+
+
+***** (V9) re75 *****
+                       Before Matching 	 	 After Matching
+mean treatment........     1532.1 	 	     1279.9 
+mean control..........     1266.9 	 	     1248.9 
+std mean diff.........     8.2363 	 	     1.0534 
+
+mean raw eQQ diff.....     367.61 	 	     129.83 
+med  raw eQQ diff.....          0 	 	          0 
+max  raw eQQ diff.....     2110.2 	 	     8195.6 
+
+mean eCDF diff........   0.050834 	 	   0.010604 
+med  eCDF diff........   0.061954 	 	  0.0082645 
+max  eCDF diff........    0.10748 	 	   0.029752 
+
+var ratio (Tr/Co).....     1.0763 	 	     1.0444 
+T-test p-value........    0.38527 	 	    0.71362 
+KS Bootstrap p-value..       0.05 	 	      0.512 
+KS Naive p-value......    0.16449 	 	    0.95166 
+KS Statistic..........    0.10748 	 	   0.029752 
+
+
+***** (V10) re74 *****
+                       Before Matching 	 	 After Matching
+mean treatment........     2095.6 	 	     1947.8 
+mean control..........       2107 	 	     1999.9 
+std mean diff.........   -0.23437 	 	     -1.076 
+
+mean raw eQQ diff.....     487.98 	 	     199.74 
+med  raw eQQ diff.....          0 	 	          0 
+max  raw eQQ diff.....       8413 	 	     7870.3 
+
+mean eCDF diff........   0.019223 	 	  0.0062459 
+med  eCDF diff........     0.0158 	 	  0.0049587 
+max  eCDF diff........   0.047089 	 	   0.021488 
+
+var ratio (Tr/Co).....     0.7381 	 	    0.86382 
+T-test p-value........    0.98186 	 	    0.55473 
+KS Bootstrap p-value..      0.574 	 	       0.72 
+KS Naive p-value......    0.97023 	 	    0.99902 
+KS Statistic..........   0.047089 	 	   0.021488 
+
+
+***** (V11) I(re74 * re75) *****
+                       Before Matching 	 	 After Matching
+mean treatment........   13118591 	 	   11751826 
+mean control..........   14530303 	 	   13196461 
+std mean diff.........    -2.7799 	 	    -3.1827 
+
+mean raw eQQ diff.....    3278733 	 	    2222436 
+med  raw eQQ diff.....          0 	 	          0 
+max  raw eQQ diff.....  188160151 	 	  188160151 
+
+mean eCDF diff........   0.022723 	 	  0.0046251 
+med  eCDF diff........   0.014449 	 	  0.0033058 
+max  eCDF diff........   0.061019 	 	   0.016529 
+
+var ratio (Tr/Co).....    0.69439 	 	    0.66813 
+T-test p-value........    0.79058 	 	    0.29985 
+KS Bootstrap p-value..       0.32 	 	      0.888 
+KS Naive p-value......    0.81575 	 	          1 
+KS Statistic..........   0.061019 	 	   0.016529 
+
+
+Before Matching Minimum p.value: 0.0020368 
+Variable Name(s): nodegr  Number(s): 6 
+
+After Matching Minimum p.value: 0.29985 
+Variable Name(s): I(re74 * re75)  Number(s): 11 
+
+> 
+> # For more examples see: http://sekhon.berkeley.edu/matching/R.
+> 
+> 
+> proc.time()
+   user  system elapsed 
+  5.159   0.051   5.196 
diff --git a/tests/Matchby.R b/tests/Matchby.R
new file mode 100644
index 0000000..3f552fd
--- /dev/null
+++ b/tests/Matchby.R
@@ -0,0 +1,18 @@
+suppressMessages(library(Matching))
+
+data(lalonde)
+
+X  <- cbind(lalonde$black, lalonde$age, lalonde$educ)
+Y  <- lalonde$re78
+Tr  <- lalonde$treat
+
+rr2  <- Matchby(Y=Y, Tr=Tr, X=X, M=1, exact=TRUE, by=X[,1],
+                ties=TRUE, replace=TRUE, AI=TRUE)
+summary(rr2)
+
+rr  <- Match(Y=Y, Tr=Tr, X=X, M=1, exact=TRUE)
+summary(rr, full=TRUE)
+
+rr$est-rr2$est
+rr$se-rr2$se
+rr$se.standard-rr2$se.standard
diff --git a/tests/Matchby.Rout.save b/tests/Matchby.Rout.save
new file mode 100644
index 0000000..dfbb536
--- /dev/null
+++ b/tests/Matchby.Rout.save
@@ -0,0 +1,80 @@
+
+R Under development (unstable) (2013-06-27 r63079) -- "Unsuffered Consequences"
+Copyright (C) 2013 The R Foundation for Statistical Computing
+Platform: x86_64-apple-darwin10.8.0 (64-bit)
+
+R is free software and comes with ABSOLUTELY NO WARRANTY.
+You are welcome to redistribute it under certain conditions.
+Type 'license()' or 'licence()' for distribution details.
+
+R is a collaborative project with many contributors.
+Type 'contributors()' for more information and
+'citation()' on how to cite R or R packages in publications.
+
+Type 'demo()' for some demos, 'help()' for on-line help, or
+'help.start()' for an HTML browser interface to help.
+Type 'q()' to quit R.
+
+> suppressMessages(library(Matching))
+> 
+> data(lalonde)
+> 
+> X  <- cbind(lalonde$black, lalonde$age, lalonde$educ)
+> Y  <- lalonde$re78
+> Tr  <- lalonde$treat
+> 
+> rr2  <- Matchby(Y=Y, Tr=Tr, X=X, M=1, exact=TRUE, by=X[,1],
++                 ties=TRUE, replace=TRUE, AI=TRUE)
+1 of 2 groups
+2 of 2 groups
+> summary(rr2)
+
+Estimate...  1907.3 
+AI SE......  598.06 
+AI T-stat..  3.1891 
+AI p.val...  0.0014269 
+
+SE.........  863.19 
+T-stat.....  2.2096 
+p.val......  0.027133 
+
+Original number of observations..............  445 
+Original number of treated obs...............  185 
+Matched number of observations...............  119 
+Matched number of observations  (unweighted).  355 
+
+Number of treated observations dropped.......  66 
+
+> 
+> rr  <- Match(Y=Y, Tr=Tr, X=X, M=1, exact=TRUE)
+> summary(rr, full=TRUE)
+
+Estimate...  1907.3 
+AI SE......  598.06 
+T-stat.....  3.1891 
+p.val......  0.0014269 
+
+Est noAdj..  1907.3 
+SE.........  863.19 
+T-stat.....  2.2096 
+p.val......  0.027133 
+
+Original number of observations..............  445 
+Original number of treated obs...............  185 
+Matched number of observations...............  119 
+Matched number of observations  (unweighted).  355 
+
+Number of obs dropped by 'exact' or 'caliper'  66 
+
+> 
+> rr$est-rr2$est
+             [,1]
+[1,] 2.273737e-13
+> rr$se-rr2$se
+[1] 1.136868e-13
+> rr$se.standard-rr2$se.standard
+[1] 0
+> 
+> proc.time()
+   user  system elapsed 
+  0.306   0.032   0.330 

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/debian-science/packages/r-cran-matching.git



More information about the debian-science-commits mailing list