diff --git a/.gitattributes b/.gitattributes
index 8d994babbdcd8a363ba4122a40f1257f3c134d96..790b2e8455c6a37140af146e006266fb3a23944d 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -312,6 +312,13 @@ MAC/APL/DEPENDENCIES -text svneol=native#application/octet-stream
 MAC/APL/PAC/BeamServer/test/weights.dat -text svneol=unset#unset
 MAC/APL/PAC/CalServer/src/CS010C_HALF_positions.dat -text
 MAC/APL/PAC/CalServer/src/CS010C_positions.dat -text
+MAC/APL/PAC/MatlabCal/bootstrap -text
+MAC/APL/PAC/MatlabCal/test/20080118_083229_acc_512x96x96.dat -text
+MAC/APL/PAC/MatlabCal/test/antpos.dat -text
+MAC/APL/PAC/MatlabCal/test/calresult.dat -text
+MAC/APL/PAC/MatlabCal/test/flags.dat -text
+MAC/APL/PAC/MatlabCal/test/frequencies.dat -text
+MAC/APL/PAC/MatlabCal/test/srcpos.dat -text
 MAC/APL/PIC/MIS/Makefile.am -text svneol=native#application/octet-stream
 MAC/APL/PIC/MIS/bootstrap -text svneol=native#application/octet-stream
 MAC/APL/PIC/MIS/configure.in -text svneol=native#application/octet-stream
diff --git a/MAC/APL/PAC/MatlabCal/Makefile.am b/MAC/APL/PAC/MatlabCal/Makefile.am
new file mode 100644
index 0000000000000000000000000000000000000000..201861e1755984e9435c1fcc3cc1109f3b1680d5
--- /dev/null
+++ b/MAC/APL/PAC/MatlabCal/Makefile.am
@@ -0,0 +1,18 @@
+SUBDIRS=src test 
+
+ACLOCAL_AMFLAGS = -I $(top_srcdir)/autoconf_share
+
+pkgextdir     = $(prefix)/config/$(PACKAGE)
+pkgext_DATA   = pkgext pkgextcppflags pkgextcxxflags pkgextldflags
+
+DISTCHECK_CONFIGURE_FLAGS=\
+	--with-common=$(prefix) \
+	--with-gcftm=$(prefix) \
+	--with-rtccommon=$(prefix)
+
+EXTRA_DIST = \
+      Makefile.common \
+      MatLabCal.spec \
+      autoconf_share/compiletool
+
+include $(top_srcdir)/Makefile.common
diff --git a/MAC/APL/PAC/MatlabCal/MatlabCal.spec.in b/MAC/APL/PAC/MatlabCal/MatlabCal.spec.in
new file mode 100644
index 0000000000000000000000000000000000000000..0380618a26ef522803e5086d8e0e19cb8830197a
--- /dev/null
+++ b/MAC/APL/PAC/MatlabCal/MatlabCal.spec.in
@@ -0,0 +1,161 @@
+# -*- Mode:rpm-spec -*-
+# MatlabCal.spec.in
+#
+
+##############################################################################
+#
+# Preamble
+#
+##############################################################################
+
+Summary: The MatlabCal library creates a C-library from matlab code.
+
+%define release @RPM_RELEASE@
+%define version @VERSION@
+%define pkgname @PACKAGE@
+%define pkgdir %{pkgname}-%{version}-%{release}
+%define prefix /opt/lofar
+%define configure_args @RPM_CONFIGURE_ARGS@
+##define build_kernel_version @BUILD_KERNEL_VERSION@
+
+Name: %{pkgname}
+Version: %{version}
+Release: %{release}
+Copyright: LGPL
+Group: Application/System
+Source: %{pkgname}-%{version}.tar.gz
+BuildRoot: %{_tmppath}/%{pkgdir}-root
+URL: http://www.astron.nl
+Prefix: %{prefix}
+BuildArchitectures: i386 # Target platforms, i.e., i586
+##Requires: Common = 1.2   ## define dependent packages here
+Packager: %{packager}
+Distribution: The LOFAR project
+Vendor: ASTRON
+
+AutoReqProv: no
+
+%description
+
+The MatlabCal library implements LBA station calibration by compiling Matlab
+code with the MatLab compiler into a C-lib that can be used by the CalServer.
+
+##############################################################################
+#
+# prep
+#
+##############################################################################
+%prep
+echo $prefix
+
+# create the build directory, untar the source
+%setup
+
+##############################################################################
+#
+# build
+#
+##############################################################################
+%build
+./configure %{configure_args} --prefix=%{prefix} && make
+
+##############################################################################
+#
+# install
+#
+##############################################################################
+%install
+# To make things work with BUILDROOT
+if [ "$RPM_BUILD_ROOT" != "%{_tmppath}/%{pkgdir}-root" ]
+then
+  echo
+  echo @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
+  echo @                                                                    @
+  echo @  RPM_BUILD_ROOT is not what I expected.  Please clean it yourself. @
+  echo @                                                                    @
+  echo @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
+  echo
+else
+  echo Cleaning RPM_BUILD_ROOT: "$RPM_BUILD_ROOT"
+  rm -rf "$RPM_BUILD_ROOT"
+fi
+mkdir -p $RPM_BUILD_ROOT%{prefix}
+make DESTDIR="$RPM_BUILD_ROOT" install
+
+#uninstall
+
+##############################################################################
+#
+# verify
+#
+##############################################################################
+#verify
+
+##############################################################################
+#
+# clean
+#
+##############################################################################
+%clean
+# Call me paranoid, but I do not want to be responsible for nuking
+# someone's harddrive!
+if [ "$RPM_BUILD_ROOT" != "%{_tmppath}/%{pkgdir}-root" ]
+then
+  echo
+  echo @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
+  echo @                                                                    @
+  echo @  RPM_BUILD_ROOT is not what I expected.  Please clean it yourself. @
+  echo @                                                                    @
+  echo @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
+  echo
+else
+  echo Cleaning RPM_BUILD_ROOT: "$RPM_BUILD_ROOT"
+  rm -rf "$RPM_BUILD_ROOT"
+fi
+
+##############################################################################
+#
+# files
+#
+##############################################################################
+
+# empty 'files' means all distributed files
+%files
+%defattr(-, root, root)
+%{prefix}
+
+# Your application file list goes here
+# %{prefix}/lib/lib*.so*
+
+# Documentation
+# doc COPYING ChangeLog README AUTHORS NEWS
+# doc doc/*
+
+# link the module to the correct path
+%post 
+
+# before uninstall
+%preun
+
+# after uninstall
+%postun
+
+##############################################################################
+#
+# package devel
+#
+##############################################################################
+
+#package devel
+#Summary: Development files for %{pkgname}
+#Group: Applications/System
+#description devel
+#Development files for %{pkgname}.
+
+#files devel
+
+# Your development files go here
+# Programmers documentation goes here
+#doc doc
+
+# end of file
diff --git a/MAC/APL/PAC/MatlabCal/bootstrap b/MAC/APL/PAC/MatlabCal/bootstrap
new file mode 100755
index 0000000000000000000000000000000000000000..7f674c416802db5e7c438f093a99e63f63c784aa
--- /dev/null
+++ b/MAC/APL/PAC/MatlabCal/bootstrap
@@ -0,0 +1,3 @@
+#!/bin/sh
+
+../../../../autoconf_share/bootstrap ../../../../autoconf_share
diff --git a/MAC/APL/PAC/MatlabCal/configure.in b/MAC/APL/PAC/MatlabCal/configure.in
new file mode 100644
index 0000000000000000000000000000000000000000..a12c132b2f98c3f44ab2be62eabe9d33dde1bf9f
--- /dev/null
+++ b/MAC/APL/PAC/MatlabCal/configure.in
@@ -0,0 +1,65 @@
+dnl
+dnl Process this file with autoconf to produce a configure script.
+dnl
+AC_INIT
+dnl AC_CONFIG_AUX_DIR(config)
+dnl AM_CONFIG_HEADER(config/config.h)
+AM_CONFIG_HEADER(config.h)
+AM_INIT_AUTOMAKE(MatlabCal, 1.0, no-define)
+
+dnl Initialize for LOFAR (may set compilers)
+lofar_INIT
+
+dnl Checks for programs.
+AC_PROG_AWK
+AC_PROG_YACC
+AC_PROG_CC
+AC_PROG_CXX
+AM_PROG_LEX
+AC_PROG_INSTALL
+AC_PROG_LN_S
+AC_DISABLE_SHARED
+AC_PROG_LIBTOOL
+
+dnl Checks for libraries.
+
+dnl dnl Replace `main' with a function in -lfl:
+dnl AC_CHECK_LIB(fl, main)
+dnl dnl Replace `main' with a function in -lcosev_r:
+dnl AC_CHECK_LIB(cosev_r, main)
+dnl dnl Replace `main' with a function in -lcosnm_r:
+dnl AC_CHECK_LIB(cosnm_r, main)
+dnl dnl Replace `main' with a function in -lorb_r:
+dnl AC_CHECK_LIB(orb_r, main)
+dnl dnl Replace `main' with a function in -lpthread:
+dnl AC_CHECK_LIB(pthread, main)
+dnl dnl Replace `main' with a function in -lvport_r:
+dnl AC_CHECK_LIB(vport_r, main)
+
+dnl Checks for header files.
+AC_HEADER_STDC
+AC_CHECK_HEADERS(unistd.h)
+
+dnl Checks for typedefs, structures, and compiler characteristics.
+AC_C_CONST
+AC_TYPE_SIZE_T
+
+dnl Checks for library functions.
+AC_FUNC_VPRINTF
+
+dnl
+dnl Check for LOFAR specific things
+dnl
+lofar_GENERAL
+lofar_INTERNAL(LCS/Common, Common, , 1, Common/LofarTypes.h,,)
+lofar_EXTERNAL(BLITZ, 1, blitz/blitz.h,,,,'gnu3:-Wno-unused gnu3:-ftemplate-depth-30',, -lm)
+
+dnl
+dnl Output Makefiles
+dnl
+AC_OUTPUT(
+src/Makefile
+test/Makefile
+Makefile
+MatlabCal.spec
+)
diff --git a/MAC/APL/PAC/MatlabCal/package.dox b/MAC/APL/PAC/MatlabCal/package.dox
new file mode 100644
index 0000000000000000000000000000000000000000..a44bb3fa0e5714ce8631ec9e86803d0367533b04
--- /dev/null
+++ b/MAC/APL/PAC/MatlabCal/package.dox
@@ -0,0 +1,2 @@
+// \ingroup PAC
+// \defgroup MatlabCal Compilation of Matlab calibration routines.
diff --git a/MAC/APL/PAC/MatlabCal/src/calibrate.m b/MAC/APL/PAC/MatlabCal/src/calibrate.m
new file mode 100644
index 0000000000000000000000000000000000000000..f2f6edbc47569e290a17cec4f3e788fffbe97b64
--- /dev/null
+++ b/MAC/APL/PAC/MatlabCal/src/calibrate.m
@@ -0,0 +1,295 @@
+function [cal, flags] = calibrate(acc, antpos, srcpos, freq)
+% [cal, flags] = calibrate(acc, srcpos, antpos, freq)
+%
+% Function performing the station calibration routine on the array
+% covariance cube (ACC) provided returning calibration factors and flags
+% per antenna per subband indicating bad antennas and RFI. This is a
+% monolithic variant of the station calibration implemented earlier for
+% compilation to a C++ shared library used by the LCU.
+%
+% Arguments
+% acc    : Nrcu x Nrcu x Nsb array covariance cube containing an array
+%          covariance matrix for each subband
+% antpos : Nelem x 3 matrix with (x, y, z)-positions of the antennas in
+%          Cartesian peak UR coordinates in meters
+% srcpos : Nsrc x 3 matrix with (l, m, n)-coordinates of the calibrator
+%          sources to be used in Cartesian peak UR coordinates
+% freq   : Nsb x 1 vector containing the center frequencies of the subbands
+%          in Hertz. If a frequency is set to zero, it is assumed to be in
+%          a stopband or aliased band and the corresponding subband will be
+%          skipped.
+%
+% Return values
+% cal    : Nsb x Nrcu matrix containing complex calibration factors per
+%          subband per receiver path. These values can be applied to the
+%          beam former coefficient to get a nominal beam.
+% flags  : Nsb x Nrcu matrix containing flags per subband per receive path
+%          indicating the result from RFI and bad antenna detection.
+%
+% Stefan Wijnholds, 19 November 2008
+
+    % parameters
+    c = 2.99792e8;           % speed of light in m/s
+    uvlimlambda = 4;         % baseline restriction in wavelength
+    uvlimmeter = 20;         % baseline restriction in meters
+    Nelem = size(antpos, 1); % number of elements in the array
+    Nsb = length(freq);      % number of subband
+    Ns = freq(2)-freq(1);    % number of samples after 1 s integration
+    sbidx = 1:Nsb;           % index for subbands
+    diffstop = 1e-3;         % stop criterion for calibration routine
+    maxiter = 10;            % maximum number of iterations in calibration loop
+
+    % tresholds for RFI detection and bad antenna detection
+    tresholdRFI = 10 * sqrt(2 * Nelem / Ns);  % 10 sigma
+    tresholdRCU = 5;                          % 5 sigma
+
+    % ignore subbands in stopband or aliased bands
+    sbsel = freq > 0;
+
+    % RFI detection
+    [cleansbx, cleansby] = RFIdetection(acc, tresholdRFI);
+    sbselx = sbsel & cleansbx;
+    sbsely = sbsel & cleansby;
+
+    % check for bad antennas
+    [selx, sely] = detectBadElem(acc, sbselx, sbsely, tresholdRCU);
+
+    % determine baseline lengths
+    u = meshgrid(antpos(:, 1)) - meshgrid(antpos(:, 1)).';
+    v = meshgrid(antpos(:, 2)) - meshgrid(antpos(:, 2)).';
+    w = meshgrid(antpos(:, 3)) - meshgrid(antpos(:, 3)).';
+    uvwdist = sqrt(u.^2 + v.^2 + w.^2);
+
+    % calibrate array of x-elements
+    tic
+    calx = zeros(Nsb, sum(selx));
+    sbidxx = sbidx(sbselx);
+    for idx = sbidxx;
+        disp(['Working on subband ' num2str(find(sbidxx == idx)) ' of ' num2str(sum(sbselx))]);
+        % initialization
+        A = exp(-(2 * pi * i * freq(idx) / c) * antpos(selx, :) * srcpos.');
+        Rhat = squeeze(acc(1:2:end, 1:2:end, sbidx(idx)));
+        Rhat = Rhat(selx, selx);
+        mask = uvwdist < min([uvlimlambda * (c / freq(idx)), uvlimmeter]);
+        mask = mask(selx, selx);
+        flux = real(inv(abs(A' * A).^2) * khatrirao(conj(A), A)' * (Rhat(:) .* (1 - mask(:))));
+        flux = flux / flux(1);
+        flux(flux < 0) = 0;
+        % calibrate using WALS method
+        calx(idx, :) = cal_ext(Rhat, A, flux, mask, diffstop, maxiter);
+    end
+    calx0 = checkCal(calx, selx, Nsb, Nelem);
+    toc
+    
+    % calibrate array of y-elements
+    tic
+   caly = zeros(Nsb, sum(sely));
+    sbidxy = sbidx(sbsely);
+    for idx = sbidxy;
+        disp(['Working on subband ' num2str(find(sbidxy == idx)) ' of ' num2str(sum(sbsely))]);
+        % initialization
+        A = exp(-(2 * pi * i * freq(idx) / c) * antpos(sely, :) * srcpos.');
+        Rhat = squeeze(acc(2:2:end, 2:2:end, sbidx(idx)));
+        Rhat = Rhat(sely, sely);
+        mask = uvwdist < min([uvlimlambda * (c / freq(idx)), uvlimmeter]);
+        mask = mask(sely, sely);
+        flux = real(inv(abs(A' * A).^2) * khatrirao(conj(A), A)' * (Rhat(:) .* (1 - mask(:))));
+        flux = flux / flux(1);
+        flux(flux < 0) = 0;
+        % calibrate using WALS method
+        caly(idx, :) = cal_ext(Rhat, A, flux, mask, diffstop, maxiter);
+    end
+    caly0 = checkCal(caly, sely, Nsb, Nelem);
+    toc
+
+    cal = zeros(Nsb, 2 * Nelem);
+    cal(:, 1:2:end) = calx0;
+    cal(:, 1:2:end) = caly0;
+    flags = (cal == 0);
+    % interpolation (currently not implemented)
+    cal(cal == 0) = 1;
+
+end % end function calibrate
+
+% Helper functions:
+%   RFIdetection: detects RFI occupied subbands unsuitable for calibration
+%   detectBadElem: detect failing elements
+%   checkCal: post-calibration check on calibration results
+%   cal_ext: implements WALS calibration method
+%   computeAlphaW: helper function for cal_ext
+%   khatrirao: computes Khatri-Rao product of two matrices
+
+function [cleansbx, cleansby] = RFIdetection(acc, treshold)
+    Nsb = size(acc, 3);
+    teststatx = zeros(Nsb, 1);
+    teststaty = zeros(Nsb, 1);
+    for sb = 1:Nsb
+        Rhat = squeeze(acc(:, :, sb));
+        Rwhite = Rhat ./ sqrt(diag(Rhat) * diag(Rhat).');
+        teststatx(sb) = norm(Rwhite(1:2:end, 1:2:end), 'fro').^2;
+        teststaty(sb) = norm(Rwhite(2:2:end, 2:2:end), 'fro').^2;
+    end
+    cleansbx = max(abs(teststatx - [teststatx(2:end); 0]), abs(teststatx - [0; teststatx(1:end-1)])) < treshold;
+    cleansby = max(abs(teststaty - [teststaty(2:end); 0]), abs(teststaty - [0; teststaty(1:end-1)])) < treshold;
+end % end function RFIdetection
+
+function [selx, sely] = detectBadElem(acc, sbselx, sbsely, tresholdRCU)
+    Nelem = size(acc, 1) / 2;
+    ac = zeros(2 * Nelem, size(acc, 3));
+    for idx = 1:2 * Nelem
+        ac(idx, :) = squeeze(acc(idx, idx, :));
+    end
+    acx = ac(1:2:end, sbselx);
+    acy = ac(2:2:end, sbsely);
+    teststatx = abs(acx - repmat(median(acx), Nelem, 1));
+    treshold = tresholdRCU * repmat(std(acx), Nelem, 1);
+    selx = sum((teststatx < treshold).') == sum(sbselx);
+    teststaty = abs(acy - repmat(median(acy), Nelem, 1));
+    treshold = tresholdRCU * repmat(std(acy), Nelem, 1);
+    sely = sum((teststaty < treshold).') == sum(sbsely);
+end % end function detectBadElem
+
+function cal = checkCal(cal, sel, Nch, nelem)
+    cal = cal ./ repmat(median(abs(cal), 2), [1 size(cal, 2)]);
+    cal(isnan(cal)) = 0;
+    delta = max(abs(cal - [cal(2:end, :); zeros(1, size(cal, 2))]), abs(cal - [zeros(1, size(cal, 2)); cal(1:end-1, :)]));
+    selcalf = sum(delta < 0.3, 2) > 0.5 * nelem;
+    selcalant = sum(abs(cal(selcalf, :)) < 3) == max(sum(abs(cal(selcalf, :)) < 3));
+    cal(~selcalf, :) = 0;
+    cal(:, ~selcalant) = 0;
+    caltemp = zeros(Nch, nelem);
+    caltemp(:, sel) = cal;
+    cal = caltemp;
+end % end function checkCal
+
+function cal = cal_ext(Rhat, A, sigmas, mask, diffstop, maxiter)
+    % parameters
+    [Nelem, Nsrc] = size(A);
+
+    % selection matrix for non-diagonal noise matrix
+    % selection matrix main diagonal
+    Isdiag = khatrirao(eye(Nelem), eye(Nelem));
+    % selection matrix real parts off-diagonal elements
+    seltriu = triu(mask, 1);
+    seltriu = diag(seltriu(:));
+    seltriu = seltriu(:, diag(seltriu) == 1);
+    seltril = tril(mask, -1);
+    seltril = diag(seltril(:));
+    seltril = seltril(:, diag(seltril) == 1);
+    Isre = seltriu + seltril;
+    % selection matrix imaginary parts off-diagonal elements
+    Isim = seltriu - seltril;
+    % complete selection matrix
+    Isel = [Isdiag, Isre, Isim];
+
+    % initialization
+    ghat = zeros(Nelem, maxiter+1);
+    sigmahat = zeros(Nsrc, maxiter+1);
+    sigmahat(:, 1) = sigmas;
+    sigmanhat = zeros(sum(mask(:)), maxiter+1);
+    sigmanhat(1:Nelem, 1) = 1;
+    Sigma_n = zeros(Nelem);
+
+    % implementation using WALS
+    for iter = 2:maxiter+1
+        % estimate g using baseline restriction
+        alpha = computeAlphaW(Rhat .* (1 - mask), A * diag(sigmahat(:, iter-1)) * A' .* (1 - mask));
+        [v, d] = eig(alpha);
+        [dummy, idx] = max(diag(d));
+        ghat(:, iter) = conj(v(:, idx));
+        GA = diag(ghat(:, iter)) * A;
+        Rest = GA * diag(sigmahat(:, iter-1)) * GA';
+        compidx = (1 - eye(Nelem)) ~= 0;
+        normg = abs(sqrt(pinv(Rest(compidx)) * Rhat(compidx)));
+        ghat(:, iter) = normg * ghat(:, iter) / (ghat(1, iter) / abs(ghat(1, iter)));
+
+        % estimate sigmanhat using sigmahat from previous iteration and ghat
+        R0 = normg^2 * Rest;
+        Sigma_n(:) = Isel * sigmanhat(:, iter-1);
+        R = R0 + Sigma_n;
+        pinvIsel = [Isdiag, 0.5 * Isre, 0.5 * Isim].';
+        sigmanhat(:, iter) = pinvIsel * (Rhat(:) - R0(:));
+    
+        % estimate sigmahat using sigmanhat and ghat
+        Sigma_n(:) = Isel * sigmanhat(:, iter);
+        invR = inv(R);
+        sigmahat(:, iter) = real(inv(abs(conj(GA' * invR * GA)).^2) * diag(GA' * invR * (Rhat - Sigma_n) * invR * GA));
+        if sum(isfinite(sigmahat(:, iter))) ~= 0
+            sigmahat(:, iter) = sigmahat(:, iter-1);
+        end
+        sigmahat(:, iter) = max(sigmahat(:, iter) / sigmahat(1, iter), 0); % no negative values!
+        
+        % test for convergence
+        theta_prev = [ghat(:, iter-1); sigmahat(:, iter-1); sigmanhat(:, iter-1)];
+        theta = [ghat(:, iter); sigmahat(:, iter); sigmanhat(:, iter)];
+        if (abs(pinv(theta_prev) * theta - 1) < diffstop)
+            break
+        end
+    end
+    cal = conj(1 ./ ghat(:, iter));
+end % end function cal_ext
+
+function alphamat = computeAlphaW(Rhat, R0)
+% alphamat = computeAlphaW(Rhat, R0)
+%
+% Support function for cal_ext which computes a matrix
+% alphamat = g * (1./g).' which corresponds to the matrix M in [1], where g
+% are the complex gains of the elements producing the input signals for
+% which Rhat is the measured array covariance matrix (ACM) and R0 is the
+% model ACM. If specific entries in these matrices are set to zero, these
+% entries are not used for estimating alpha. This feature can be exploited
+% when a baseline restriction is applied.
+%
+% Parameters
+% Rhat     : p.p measured ACM
+% R0       : p.p expected (model) ACM
+%
+% Return value
+% alphamat : p.p matrix representing the best estimate for g * (1./g).'
+%
+% References
+% [1] Stefan J. Wijnholds and Albert-Jan Boonstra, "A Multisource
+% Calibration Method for Phased Array Radio Telescopes", IEEE Workshop on
+% Sensor Array and Multichannel Processing (SAM), Waltham (MA), USA,
+% July2006
+%
+% Stefan J. Wijnholds, 2006
+
+    [nelem, nelem] = size(Rhat);
+    Rhat_red = Rhat - diag(diag(Rhat));
+    R0_red = R0 - diag(diag(R0));
+    alphamat = zeros(nelem);
+    
+    for i = 1:nelem
+        for j = 1:nelem
+            nonzero = (Rhat_red(i, :) ~= 0) & (Rhat_red(j, :) ~= 0 & (R0_red(i, :) ~= 0) & (R0_red(j, :) ~= 0));
+            rhati = Rhat(i, nonzero)';
+            rhatj = Rhat(j, nonzero)';
+            r0i = R0(i, nonzero)';
+            r0j = R0(j, nonzero)';
+            w = abs(r0i .* rhatj).^2;
+            alphamat(i, j) =  sum(w .* (rhati .* r0j) ./ (rhatj .* r0i)) / sum(w);
+        end
+    end
+end % end function computeAlphaW
+
+function C = khatrirao(A, B)
+% C = khatrirao(A, B)
+%
+% Computes the Khatri-Rao (column wise Kronecker) product of A and B.
+%
+% Parameters
+% A, B : 2-D matrices with equal second dimension. This is not checked by
+%        the function, so entering matrices with insuitable dimensions may
+%        produce unexpected results.
+%
+% Return value
+% C    : column wise Kronecker product of A and B
+%
+% Stefan J. Wijnholds, 2006
+
+    C = zeros(size(B, 1) * size(A, 1), size(A, 2));
+    for n = 1:size(A, 2)
+        C(:, n) = kron(A(:, n), B(:, n));
+    end
+end % end function khatrirao
\ No newline at end of file
diff --git a/MAC/APL/PAC/MatlabCal/src/readme.txt b/MAC/APL/PAC/MatlabCal/src/readme.txt
new file mode 100644
index 0000000000000000000000000000000000000000..ea04f6cbb7e55594ee57b9c726ec311be24c2ddb
--- /dev/null
+++ b/MAC/APL/PAC/MatlabCal/src/readme.txt
@@ -0,0 +1,232 @@
+MATLAB Deployment Checklist
+===========================
+
+Use this checklist to successfully deploy your application, component, 
+or library.
+
+You can distribute a MATLAB Compiler-generated standalone application, 
+component, or library to any target machine with the same operating 
+system as the machine on which the application was compiled 
+(the "source" development machine).
+
+For more information, see the documentation for the MATLAB Compiler at:
+http://www.mathworks.com/access/helpdesk/help/toolbox/compiler/
+
+NOTE: Replace the items enclosed in angle brackets ( < > ) with your own 
+values.
+
+1. Ensure that the MATLAB Compiler Runtime (MCR) is installed on target 
+   machines, and ensure you have installed the correct version. To verify 
+   this, do the following: 
+
+    A. Attempt to verify the MCR exists on your system.
+
+    The MCR usually resides in these locations on these platforms:
+
+    Operating System        Path to MCR
+    ================        ===========
+    Windows              C:\Program Files\MATLAB\MATLAB Compiler Runtime\v78
+    Mac                  Applications/MATLAB/MATLAB_Compiler_Runtime/v78 
+    Linux/Solaris        *** No predetermined installation location ***
+                         Contact your system administrator.  
+
+        NOTE: For information about the installation process and the MCR, 
+              type "help MCR" or "help mcrinstaller" at the MATLAB 
+              command prompt. 
+
+    B. MATLAB 2008a uses MCR version 7.8. To verify
+       the version number of the installed MCR, type the following 
+       command:
+       [mcrmajor,mcrminor]=mcrversion
+       at the MATLAB command prompt.
+
+
+2. Add the MCR directory to the path specified by the target system's 
+   environment variable. 
+
+    A. Locate the name of the environment variable to set, using the table 
+       below:
+
+    Operating System        Environment Variable
+    ================        ====================
+    Windows                PATH
+    Linux                  LD_LIBRARY_PATH
+    Solaris                LD_LIBRARY_PATH
+    Mac                    DYLD_LIBRARY_PATH
+
+    B. Set the path by doing one of the following:
+
+        On Windows systems:
+
+        * Add the MCR directory to the environment variable by opening a 
+        command prompt and issuing the DOS command, specifying either 
+        win32 or win64:
+
+            set PATH=C:\Program Files\MATLAB\MATLAB Compiler Runtime\v78\runtime\{win32|win64};%PATH% 
+
+        Alternately, for Windows, add the following pathname:
+            C:\Program Files\MATLAB\MATLAB Compiler Runtime\v78\runtime\{win32|win64}
+        to the PATH environment variable, specifying either win32 or win64, 
+        by doing the following:
+            1. Select the My Computer icon on your desktop.
+            2. Right-click the icon and select Properties from the menu.
+            3. Select the Advanced tab.
+            4. Click Environment Variables.  
+
+        On UNIX systems:
+
+        * Add the MCR directory to the environment variable by issuing 
+            the following commands:
+
+        Linux
+            setenv LD_LIBRARY_PATH
+                <mcr_root>/v78/runtime/glnx86:
+                <mcr_root>/v78/sys/os/glnx86:
+                <mcr_root>/v78/sys/java/jre/glnx86/jre1.6.0/lib/i386/native_threads:
+                <mcr_root>/v78/sys/java/jre/glnx86/jre1.6.0/lib/i386/server:
+                <mcr_root>/v78/sys/java/jre/glnx86/jre1.6.0/lib/i386
+            setenv XAPPLRESDIR <mcr_root>/v78/X11/app-defaults
+
+        Solaris64
+            setenv LD_LIBRARY_PATH /usr/lib/lwp:
+                <mcr_root>/v78/runtime/sol64:
+                <mcr_root>/v78/sys/os/sol64:
+                <mcr_root>/v78/sys/java/jre/sol64/jre1.6.0/lib/sparcv9/native_threads:
+                <mcr_root>/v78/sys/java/jre/sol64/jre1.6.0/lib/sparcv9/server:
+                <mcr_root>/v78/sys/java/jre/sol64/jre1.6.0/lib/sparcv9
+            setenv XAPPLRESDIR <mcr_root>/v78/X11/app-defaults
+
+        Linux x86-64
+            setenv LD_LIBRARY_PATH
+                <mcr_root>/v78/runtime/glnxa64:
+                <mcr_root>/v78/sys/os/glnxa64:
+                <mcr_root>/v78/sys/java/jre/glnxa64/jre1.6.0/lib/amd64/native_threads:
+                <mcr_root>/v78/sys/java/jre/glnxa64/jre1.6.0/lib/amd64/server:
+                <mcr_root>/v78/sys/java/jre/glnxa64/jre1.6.0/lib/amd64 
+            setenv XAPPLRESDIR <mcr_root>/v78/X11/app-defaults
+
+        Mac
+            setenv DYLD_LIBRARY_PATH
+                <mcr_root>/version/runtime/maci:
+                <mcr_root>/version/sys/os/maci:
+                <mcr_root>/version/bin/maci:
+                /System/Library/Frameworks/JavaVM.framework/JavaVM:
+                /System/Library/Frameworks/JavaVM.framework/Libraries
+            setenv XAPPLRESDIR <mcr_root>/version/X11/app-defaults
+
+
+        NOTE: To make theses changes persistent after logout on UNIX or 
+              Mac machines, modify the .cshrc file to include this setenv 
+              command.
+        NOTE: On Windows, the Environment Variable syntax utilizes 
+              backslashes (\), delimited by semi-colons (;). On UNIX,
+              the EV syntax utilizes forward slashes (/), delimited by 
+              colons (:). 
+        NOTE: When deploying C and C++ standalone applications, it is 
+              possible to run the shell script file run_libstatcal1_0.sh 
+              on UNIX and Mac instead of setting environment variables. 
+              See "Requirements for Standalone Applications," below.    
+
+
+3. Collect the following files, based on what you are deploying: 
+
+    Requirements for Standalone Applications:
+    ============================================================
+
+    All Platforms:
+        * libstatcal1_0.ctf (If present)(Component Technology File archive,
+          platform-dependent on target machine)
+
+    Windows:
+        * MCRInstaller.exe (self-extracting MATLAB Compiler Runtime
+          installer)
+        * libstatcal1_0.exe (application created by MATLAB Compiler)
+
+    UNIX:
+        * MCRInstaller.bin (MATLAB Compiler Runtime installer)
+        * libstatcal1_0 (application created by MATLAB Compiler)
+        * run_libstatcal1_0.sh (shell script that can be run to 
+          temporarily set environment paths and execute the application)
+
+    Mac:
+        * MCRInstaller.dmg (MATLAB Compiler Runtime installer)
+        * libstatcal1_0 (application created by MATLAB Compiler)
+        * run_libstatcal1_0.sh (shell script that can be run to 
+          temporarily set environment paths and execute the application)
+
+
+    Requirements for C and C++ shared libraries:
+    ============================================================
+
+    All Platforms:
+        * libstatcal1_0.so (shared library, file extension varies by 
+          platform)
+        * libstatcal1_0.h (library header file)
+        * libstatcal1_0.ctf (If present)(Component Technology File archive,
+          platform-dependent on target machine, contains compiled M-code)
+
+    Windows:
+        * MCRInstaller.exe (self-extracting MATLAB Compiler Runtime
+          installer)  
+
+    UNIX:
+        * MCRInstaller.bin (MATLAB Compiler Runtime installer)
+
+    Mac:
+        * MCRInstaller.dmg (MATLAB Compiler Runtime installer)
+
+
+    Requirements for .NET Components:
+    ============================================================
+
+    Windows:
+        * libstatcal1_0.ctf (Component Technology File archive, contains 
+          compiled M-code)    
+        * libstatcal1_0.xml (documentation files)
+        * libstatcal1_0.pdb (program database file - if DEBUG option 
+          selected)
+        * libstatcal1_0.dll (component assembly file)
+        * MCRInstaller.exe (self-extracting MATLAB Compiler Runtime
+          archive)
+
+
+    Requirements for COM Components:
+    ============================================================
+
+    Windows:
+        * libstatcal1_0.ctf (Component Technology File archive, contains 
+          compiled M-code)
+        * libstatcal1_0_1_0.dll (COM component)
+        * MCRInstaller.exe (self-extracting MATLAB Compiler Runtime
+          archive)      
+
+
+    Requirements for Java Components: 
+    ============================================================
+
+    All Platforms: 
+        * libstatcal1_0.jar (Java class files and compiled M-code)
+
+    Windows:
+        * MCRInstaller.exe (self-extracting MATLAB Compiler Runtime
+          installer)  
+
+    UNIX:
+        * MCRInstaller.bin (MATLAB Compiler Runtime installer)
+
+    Mac:
+        * MCRInstaller.dmg (MATLAB Compiler Runtime installer)
+
+
+    Requirements for COM Components for Use with Microsoft Excel:
+    ============================================================
+
+    Windows:
+        * libstatcal1_0_1_0.dll (COM component)
+        * libstatcal1_0.ctf (Component Technology File archive, contains 
+          compiled M-code)
+        * libstatcal1_0.xla (Optionally created and placed in
+           directory by the user)  
+        * MCRInstaller.exe (self-extracting MATLAB Compiler Runtime
+          archive)
+
diff --git a/MAC/APL/PAC/MatlabCal/test/20080118_083229_acc_512x96x96.dat b/MAC/APL/PAC/MatlabCal/test/20080118_083229_acc_512x96x96.dat
new file mode 100644
index 0000000000000000000000000000000000000000..29ef75de32398aa2e29a4ca1001856e543bd0303
Binary files /dev/null and b/MAC/APL/PAC/MatlabCal/test/20080118_083229_acc_512x96x96.dat differ
diff --git a/MAC/APL/PAC/MatlabCal/test/antpos.dat b/MAC/APL/PAC/MatlabCal/test/antpos.dat
new file mode 100644
index 0000000000000000000000000000000000000000..bb3c1dd5ed7d8c52f84042dd5a9a8c03d51c9993
Binary files /dev/null and b/MAC/APL/PAC/MatlabCal/test/antpos.dat differ
diff --git a/MAC/APL/PAC/MatlabCal/test/calresult.dat b/MAC/APL/PAC/MatlabCal/test/calresult.dat
new file mode 100644
index 0000000000000000000000000000000000000000..a188d8e6222cada7d08bc574964a43690190e317
Binary files /dev/null and b/MAC/APL/PAC/MatlabCal/test/calresult.dat differ
diff --git a/MAC/APL/PAC/MatlabCal/test/flags.dat b/MAC/APL/PAC/MatlabCal/test/flags.dat
new file mode 100644
index 0000000000000000000000000000000000000000..f83fd9b2846f7331d1f51277c9ca52cb812ba258
Binary files /dev/null and b/MAC/APL/PAC/MatlabCal/test/flags.dat differ
diff --git a/MAC/APL/PAC/MatlabCal/test/frequencies.dat b/MAC/APL/PAC/MatlabCal/test/frequencies.dat
new file mode 100644
index 0000000000000000000000000000000000000000..c9d7659244488a32d33831a01181b2ebfadd095b
Binary files /dev/null and b/MAC/APL/PAC/MatlabCal/test/frequencies.dat differ
diff --git a/MAC/APL/PAC/MatlabCal/test/srcpos.dat b/MAC/APL/PAC/MatlabCal/test/srcpos.dat
new file mode 100644
index 0000000000000000000000000000000000000000..7754e134d77fa0a094ee698e74b3522aadf59893
Binary files /dev/null and b/MAC/APL/PAC/MatlabCal/test/srcpos.dat differ
diff --git a/MAC/APL/PAC/MatlabCal/test/testdriver.cc b/MAC/APL/PAC/MatlabCal/test/testdriver.cc
new file mode 100644
index 0000000000000000000000000000000000000000..25ebcb93471875ddd2ebae511a0e22cb6a2ee1f6
--- /dev/null
+++ b/MAC/APL/PAC/MatlabCal/test/testdriver.cc
@@ -0,0 +1,115 @@
+#include "libstatcal1_0.h"
+#include <iostream>
+#include <fstream>
+#include <iterator>
+
+
+using namespace std;
+
+int driver(int argc, char **argv)
+{
+    if (!mclInitializeApplication(NULL, 0))
+    {
+	cerr << "Failed to initialize the MCR" << endl;
+	return -1;
+    }
+    if (!libstatcal1_0Initialize())
+    {
+	cerr << "Failed to initialize libstatcal1_0.s0" << endl;
+	return -2;
+    }
+    cout << "MCR and libstatcal1_0.so successfully initialized" << endl;
+
+
+    try
+    {
+	// get array covariance cube
+	ifstream caldata("20080118_083229_acc_512x96x96.dat");
+	double *data = new double[2 * 512 * 96 * 96];
+	caldata.read(reinterpret_cast<char *>(data), 2 * 512 * 96 * 96 * sizeof(double));
+	const mwSize dim[3] = {96, 96, 512};
+	mwArray acc(3, dim, mxDOUBLE_CLASS, mxCOMPLEX);
+	int dataidx = 0;
+	for (int sb = 1; sb <= 512; sb++)
+	{
+	    for (int idx2 = 1; idx2 <= 96; idx2++)
+	    {
+		for (int idx1 = 1; idx1 <= 96; idx1++)
+		{
+		    acc(idx1, idx2, sb).Real() = data[dataidx];
+		    acc(idx1, idx2, sb).Imag() = data[dataidx + 1];
+		    dataidx += 2;
+		}
+	    }
+	}
+	delete[] data;
+
+	// get antenna positions
+	ifstream antfile("antpos.dat");
+	double *antdata = new double[3 * 48];
+	antfile.read(reinterpret_cast<char *>(antdata), 3 * 48 * sizeof(double));
+	mwArray antpos(48, 3, mxDOUBLE_CLASS);
+	antpos.SetData(antdata, 3 * 48);
+	delete[] antdata;
+
+	// get source positions for test data
+	ifstream srcfile("srcpos.dat");
+	double *srcposdata = new double[3 * 3];
+	srcfile.read(reinterpret_cast<char *>(srcposdata), 3 * 3 * sizeof(double));
+	mwArray srcpos(3, 3, mxDOUBLE_CLASS);
+	srcpos.SetData(srcposdata, 3 * 3);
+	delete[] srcposdata;
+
+	// get center frequencies of subband
+	ifstream freqfile("frequencies.dat");
+	double *freqdata = new double[512];
+	freqfile.read(reinterpret_cast<char *>(freqdata), 512 * sizeof(double));
+	mwArray freq(512, 1, mxDOUBLE_CLASS);
+	freq.SetData(freqdata, 512);
+	delete[] freqdata;
+
+	// up to this point, the code has been verified
+
+	// call calibrate-function
+	mwArray calresult;
+	mwArray mflags;
+	calibrate(2, calresult, mflags, acc, antpos, srcpos, freq);
+
+	// retrieve data
+	double *cal_real = new double[512 * 96];
+	double *cal_imag = new double[512 * 96];
+	double *flags = new double[512 * 96];
+	calresult.Real().GetData(cal_real, 512 * 96);
+	calresult.Imag().GetData(cal_imag, 512 * 96);
+	mflags.GetData(flags, 512 * 96);
+	ofstream calfile("calresult.dat");
+	calfile.write(reinterpret_cast<char *>(cal_real), 512 * 96 * sizeof(double));
+	calfile.write(reinterpret_cast<char *>(cal_imag), 512 * 96 * sizeof(double));
+	ofstream flagfile("flags.dat");
+	flagfile.write(reinterpret_cast<char *>(flags), 512 * 96 * sizeof(double));
+	delete[] flags;
+	delete[] cal_imag;
+	delete[] cal_real;
+    }
+    catch(const mwException& e)
+    {
+	cerr << e.what() << endl;
+	return -3;
+    }
+    catch(...)
+    {
+	cerr << "Unexpected error" << endl;
+	return -4;
+    }
+
+    libstatcal1_0Terminate();
+    mclTerminateApplication();
+    cout << "All garbage has been successfully collected" << endl;
+    return 0;
+}
+
+int main()
+{
+    mclmcrInitialize();
+    return mclRunMain((mclMainFcnType)driver, 0, NULL);
+}