function coadpc2(iarg,rmp,rcp)
% COADPC2, Does Dynamic Principal Component Analysis for 2 Populations
%      Corneal Topography Analysis System
%   Creates a menu window for choosing movie, and creates
%   4 other windows, each with a kde and a movie
%   for doing Principal Component Analysis
%      Intended to be called by coa2pm.m
%      Reads list of files from LISTFILESTR1 and LISTFILESTR2
% Inputs:
%     iarg - Type of Analysis
%             1 - standard PCA 
%                    (eigen analysis of usual covariance matrix)
%             2 - Intra Class Spread normalized PCA
%                    (eigen analysis of cov matrix, modulo intra class spread)
%     rmp - Robust Mean Parameter:
%             0 - (or not specified) use the ordinary sample mean
%             1 - Use the Spherical L1 location estimate
%             2 - Use the Elliptical (rescaled by MADs) L1 location estimate
%     rcp - Robust Covariance Parameter:
%             0 - (or not specified) use the ordinary covariance matrix
%             1 - Use the Spherical covariance matrix
%             2 - Use the Elliptical (rescaled by MADs) covariance matrix
% Outputs:
%     Only graphics, in current Figure

%    Copyright (c) J. S. Marron 1998
%    Department of Statistics, University of North Carolina


%  Set parameters and defaults according to number of input arguments
%
if nargin == 1 ;    %  1 argument input, use default
  irmp = 0 ;      %  default mean robustness parameter
else ;              %  was specified, use that
  irmp = rmp ;
end ;

if nargin <= 2 ;    %  at most 2 argument input, use default
  ircp = 0 ;      %  default covarince robustness parameter
else ;              %  was specified, use that
  ircp = rcp ;
end ;




%  Set local parameters
%
ngrid = 64 ;     %  Construct surfaces as ngrid x ngrid array
nframe = 21 ;
          %  number of movie frames
    


%  Set up global variables
%
%  First some general globals
global R0 NMAX IBASIS IRECENT COMAP NRPT NRIF ;
%  R0 - radius of analysis
          %    this gets reloaded when a feature vec is reloaded from file
%  NMAX - maximum number of Zernike columns
          %    this gets reloaded when a feature vec is reloaded from file
%  IBASIS - 1 for full (triangle), 2 for radial (3 row)
%  IRECENT - To recenter (or not) decompositions
%  COMAP - Color Map
%  NRPT - Number of times to Repeat Movie
%  NRIF - Number of times to Repeat Individual Movie Frames
          %    (controls speed of .mpeg version)

global SCREENWD SCREENHT MENUWD ;
        % overall sizes of display area, generic menu width
global VERTGAP HORIZGAP TITLHT BUTTONHT
        %  generic sizes of objects on menus
global DPCAHANDPOS DPCAM1POS DPCAM2POS DPCAM3POS DPCAM4POS ;
        %  window positioning vectors
global DPCAM1HAND DPCAM2HAND DPCAM3HAND DPCAM4HAND ;
        %  Handles for movie windows in Dynamic PC Analysis
global DPCAM1 DPCAM2 DPCAM3 DPCAM4 ;
        %  Movie matrices in Dynamic PC Analysis
global FEATMPATH SUBDIRSTR LISTR ;
        %  path for storing Zernike feature matrices
        %  SUBDIRSTR - current subdirectory (of both indata and outputs)
        %  string for inputting list file
global LISTFILESTR1 LISTFILESTR2 SETLIST1PATH SETLIST2PATH ;
        %  list file strings
        %  strings to set paths to lists
global PC2STR PC2LOAD1 PC2LOAD2 ;
        %  PC2STR - String with title info for 2 population analyses
        %  PC2LOAD1 - 1st Population Loadings for 2 population analyses
        %  PC2LOAD2 - 2nd Population Loadings for 2 population analyses




%  Read in matrix of Zernike feature coefficients, Population 1
%
disp('      Reading Files for Population 1') ;
eval(SETLIST1PATH) ;
          %  sets LISTR to Full Path List, for Population 1
mfv1 = coaflr ;
d1 = size(mfv1,1) ;
n1 = size(mfv1,2) ;



%  Read in matrix of Zernike feature coefficients, Population 2
%
disp('      Reading Files for Population 2') ;
eval(SETLIST2PATH) ;
          %  sets LISTR to Full Path List, for Population 2
mfv2 = coaflr ;
d2 = size(mfv2,1) ;
n2 = size(mfv2,2) ;



%  Combine into one big data set
if d1 == d2 ;
  d = d1 ;
else ;
  disp('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!') ;
  disp('!!!   Error from coaspc2.m:          !!!') ;
  disp('!!!   Different Number of Zernikes   !!!') ;
  disp('!!!      for these 2 lists           !!!') ;
  disp('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!') ;
end ;
mfv = [mfv1, mfv2] ;
n = n1 + n2 ;



%  Calculate grid quantities
%
xgrid = linspace(-R0, R0, ngrid) ;
ygrid = xgrid ;	        %  Vectors of image coordinate values 
[mxgrid, mygrid] = meshgrid(xgrid,ygrid) ;
              		%  Matrices of image coordinate values 


%  Create vector of frame orders
%
  imean = round((nframe + 1) / 2) ;
vmorder = imean:nframe ;
vmorder = [vmorder, ((nframe-1):-1:1)] ;
vmorder = [vmorder, (2:imean)] ;
          %  vector of frame orders to start and stop at mean
vmorder = vec2mat(vmorder,NRIF) ;
vmorder = reshape(vmorder,1,size(vmorder,2)*NRIF) ;
          %  replicate frame number, NRIF times



%  Main Principal Component Block (combined data set)
%
sst = sum(sum(mfv.^2)) ;

%  Get mean feature vector
%
if irmp == 0 ;        %  then do original non-robust sample mean
  vmean = mean(mfv')' ;
  meanstr = 'mean' ;
elseif irmp == 1 ;    %  then do spherical robust sample mean
  vmean = rmean(mfv')' ;
  meanstr = 'S. L1' ;
elseif irmp == 2 ;    %  then do elliptical robust sample mean
  vmad = gpmad(mfv',0)' ;
          %  column vector of MADs of each row
  smfv = mfv .* vec2mat(1 ./ vmad, n) ;
          %  make each coordinate have MAD 1
  vmean = rmean(smfv')' ;
  vmean = vmean .* vmad ;
  meanstr = 'E. L1' ;
end ;

%  Get residuals from mean
%
vsd = std(mfv')' ;
ssm = n * sum(vmean.^2) ;
ssmr = sst - ssm ;
mresid = mfv - vec2mat(vmean,n) ;

%  Get covariance matrix
%
if ircp == 0 ;        %  then do original non-robust covariance matrix
  mcov = cov(mresid') ;
          %  Get covariance matrix, transpose, since want "coordinates
          %                      as variables"
  covstr = '' ;
elseif ircp == 1 ;    %  then do spherical robust sample mean
  vrad = sqrt(sum(mresid .^2)) ;
          %  Transpose, since want "coordinates as variables"
          %  vector of radii of each curve
  sphereresid = mresid' ./ vec2mat(vrad',d) ;
          %  make each curve have "length" one
  mcov = cov(sphereresid) ;
          %  Get covariance matrix of "sphered" data
  covstr = 'E' ;
elseif ircp == 2 ;    %  then do elliptical robust sample mean
  vmad = gpmad(mresid',0)' ;
          %  column vector of MADs of each row
  smresid = mresid .* vec2mat(1 ./ vmad, n) ;
          %  make each coordinate have MAD 1
  vrad = sqrt(sum(smresid .^2)) ;
  sphereresid = smresid' ./ vec2mat(vrad',d) ;
          %  Transpose, since want "coordinates as variables"
          %  vector of radii of each curve
          %  make each curve have "length" one
  ellipsresid = sphereresid .* vec2mat(vmad', n) ;
          %  return each coordinate to original scale
  mcov = cov(ellipsresid) ;
          %  Get covariance matrix of "ellipsed" data
  covstr = 'E' ;
end ;


if iarg == 1 ;
  PC2STR = [covstr 'PCA'] ;
elseif iarg == 2 ;    % then normalize by "within class cov"
  PC2STR = [covstr 'ICS'] ;

  %  Get individual sample means
  %
  if irmp == 0 ;        %  then do original non-robust sample mean
    vmean1 = mean(mfv1')' ;
    vmean2 = mean(mfv2')' ;
  elseif irmp == 1 ;    %  then do spherical robust sample mean
    vmean1 = rmean(mfv1')' ;
    vmean2 = rmean(mfv2')' ;
  elseif irmp == 2 ;    %  then do elliptical robust sample mean
    vmad1 = gpmad(mfv1',0)' ;
    vmad2 = gpmad(mfv2',0)' ;
          %  column vector of MADs of each row
    smfv1 = mfv1 .* vec2mat(1 ./ vmad1, n1) ;
    smfv2 = mfv2 .* vec2mat(1 ./ vmad2, n2) ;
          %  make each coordinate have MAD 1
    vmean1 = rmean(smfv1')' ;
    vmean2 = rmean(smfv2')' ;
    vmean1 = vmean1 .* vmad1 ;
    vmean2 = vmean2 .* vmad2 ;
  end ;

  mresid1 = mfv1 - vec2mat(vmean1,n1) ;
  mresid2 = mfv2 - vec2mat(vmean2,n2) ;

  %  Get individual covariance matrices
  %
  if ircp == 0 ;        %  then do original non-robust covariance matrix
    mcov1 = cov(mresid1') ;
    mcov2 = cov(mresid2') ;
          %  Get covariance matrix, transpose, since want "coordinates
          %                      as variables"
  elseif ircp == 1 ;    %  then do spherical robust sample mean
    vrad1 = sqrt(sum(mresid1 .^2)) ;
    vrad2 = sqrt(sum(mresid2 .^2)) ;
          %  Transpose, since want "coordinates as variables"
          %  vector of radii of each curve
    sphereresid1 = mresid1' ./ vec2mat(vrad1',d) ;
    sphereresid2 = mresid2' ./ vec2mat(vrad2',d) ;
          %  make each curve have "length" one
    mcov1 = cov(sphereresid1) ;
    mcov2 = cov(sphereresid2) ;
          %  Get covariance matrix of "sphered" data
  elseif ircp == 2 ;    %  then do elliptical robust sample mean
    vmad1 = gpmad(mresid1',0)' ;
    vmad2 = gpmad(mresid2',0)' ;
          %  column vector of MADs of each row
    smresid1 = mresid1 .* vec2mat(1 ./ vmad1, n1) ;
    smresid2 = mresid2 .* vec2mat(1 ./ vmad2, n2) ;
          %  make each coordinate have MAD 1
    vrad1 = sqrt(sum(smresid1 .^2)) ;
    vrad2 = sqrt(sum(smresid2 .^2)) ;
    sphereresid1 = smresid1' ./ vec2mat(vrad1',d) ;
    sphereresid2 = smresid2' ./ vec2mat(vrad2',d) ;
          %  Transpose, since want "coordinates as variables"
          %  vector of radii of each curve
          %  make each curve have "length" one
    ellipsresid1 = sphereresid1 .* vec2mat(vmad1', n1) ;
    ellipsresid2 = sphereresid2 .* vec2mat(vmad2', n2) ;
          %  return each coordinate to original scale
    mcov1 = cov(ellipsresid1) ;
    mcov2 = cov(ellipsresid2) ;
          %  Get covariance matrix of "ellipsed" data
  end ;

  
  mcovw = (n1 / n) * mcov1 + (n2 / n) * mcov2 ;
            %  Average of "within class covariances"

wfact = max(max(mcovw)) / n ;
mcovw = mcovw + wfact * eye(size(mcovw)) ;
          %  kludge to avoid numerical problems

  mcovw = sqrtm(mcovw) ;

  mcov = (mcovw \ mcov) / mcovw ;
          %  Multiply by inverse square root on each side
          %  to preserve nonegative definiteness for eigenvalues

          %  Caution: this will usually produce warning messages which 
          %  "should" be no problem
%  disp('        (hopefully above warning messages can be ignored)') ;



elseif iarg == 3 ;    % then get principle discriminant "cov matrix"
  PC2STR = [covstr 'PDA'] ;

  %  Get individual sample means
  %
  if irmp == 0 ;        %  then do original non-robust sample mean
    vmean1 = mean(mfv1')' ;
    vmean2 = mean(mfv2')' ;
  elseif irmp == 1 ;    %  then do spherical robust sample mean
    vmean1 = rmean(mfv1')' ;
    vmean2 = rmean(mfv2')' ;
  elseif irmp == 2 ;    %  then do elliptical robust sample mean
    vmad1 = gpmad(mfv1',0)' ;
    vmad2 = gpmad(mfv2',0)' ;
          %  column vector of MADs of each row
    smfv1 = mfv1 .* vec2mat(1 ./ vmad1, n1) ;
    smfv2 = mfv2 .* vec2mat(1 ./ vmad2, n2) ;
          %  make each coordinate have MAD 1
    vmean1 = rmean(smfv1')' ;
    vmean2 = rmean(smfv2')' ;
    vmean1 = vmean1 .* vmad1 ;
    vmean2 = vmean2 .* vmad2 ;
  end ;

  mresid1 = mfv1 - vec2mat(vmean1,n1) ;
  mresid2 = mfv2 - vec2mat(vmean2,n2) ;

  %  Get individual covariance matrices
  %
  if ircp == 0 ;        %  then do original non-robust covariance matrix
    mcov1 = cov(mresid1') ;
    mcov2 = cov(mresid2') ;
          %  Get covariance matrix, transpose, since want "coordinates
          %                      as variables"
  elseif ircp == 1 ;    %  then do spherical robust sample mean
    vrad1 = sqrt(sum(mresid1 .^2)) ;
    vrad2 = sqrt(sum(mresid2 .^2)) ;
          %  Transpose, since want "coordinates as variables"
          %  vector of radii of each curve
    sphereresid1 = mresid1' ./ vec2mat(vrad1',d) ;
    sphereresid2 = mresid2' ./ vec2mat(vrad2',d) ;
          %  make each curve have "length" one
    mcov1 = cov(sphereresid1) ;
    mcov2 = cov(sphereresid2) ;
          %  Get covariance matrix of "sphered" data
  elseif ircp == 2 ;    %  then do elliptical robust sample mean
    vmad1 = gpmad(mresid1',0)' ;
    vmad2 = gpmad(mresid2',0)' ;
          %  column vector of MADs of each row
    smresid1 = mresid1 .* vec2mat(1 ./ vmad1, n1) ;
    smresid2 = mresid2 .* vec2mat(1 ./ vmad2, n2) ;
          %  make each coordinate have MAD 1
    vrad1 = sqrt(sum(smresid1 .^2)) ;
    vrad2 = sqrt(sum(smresid2 .^2)) ;
    sphereresid1 = smresid1' ./ vec2mat(vrad1',d) ;
    sphereresid2 = smresid2' ./ vec2mat(vrad2',d) ;
          %  Transpose, since want "coordinates as variables"
          %  vector of radii of each curve
          %  make each curve have "length" one
    ellipsresid1 = sphereresid1 .* vec2mat(vmad1', n1) ;
    ellipsresid2 = sphereresid2 .* vec2mat(vmad2', n2) ;
          %  return each coordinate to original scale
    mcov1 = cov(ellipsresid1) ;
    mcov2 = cov(ellipsresid2) ;
          %  Get covariance matrix of "ellipsed" data
  end ;


  mcovb = vmean1 - vmean2 ;
  mcovb = mcovb * mcovb' ;

  mcovw = (n1 / n) * mcov1 + (n2 / n) * mcov2 ;
            %  Average of "within class covariances"

  mcov = pinv(mcovw) ;
  mcov = (mcov + mcov') / 2 ;
            %  symmetrize, since psuedo inv is not quite symmetric
%max(max(abs(mcov - mcov')))
%max(max(abs(mcovb - mcovb')))

  mcov = pinv(mcovw) * mcovb ;
          %  original line, appears to be numerically unstable,
          %  in particular result is not symmetric
  mcov = (mcov + mcov') / 2 ;
            %  symmetrize, since not quite symmetric



end ;




% Do eigen analysis
%
[meigvec,meigval] = eig(mcov) ;
veigval = (diag(meigval)) ;
          %  Get eigenvalues and eigenvectors

[veigval,vind] = sort(veigval) ;
meigvec = meigvec(:,vind) ;
          %  Sort to avoid possible ordering problems
  
ev1 = meigvec(:,d) ;
          %  eigenvector with largest eigenvalue
pc1 = mresid' * ev1 ;
          %  vector of projections of data onto ev1
pc1rep = max(abs(pc1 - mean(pc1))) ;
          %  "most representative pc", defined as MAD
mpc1 = ev1 * pc1rep ;
          %  "average vector" for display
mresid1 = (mresid - ev1 * pc1') ;
ss1r = sum(sum(mresid1.^2)) ;
ss1 = ssmr - ss1r ;

ev2 = meigvec(:,d-1) ;
          %  eigenvector with largest eigenvalue
pc2 = mresid1' * ev2 ;
          %  vector of projections of data onto ev2
pc2rep = max(abs(pc2 - mean(pc2))) ;
          %  "most representative pc", defined as MAD
mpc2 = ev2 * pc2rep ;
          %  "average vector" for display
mresid2 = (mresid1 - ev2 * pc2') ;
ss2r = sum(sum(mresid2.^2)) ;
ss2 = ss1r - ss2r ;

ev3 = meigvec(:,d-2) ;
          %  eigenvector with largest eigenvalue
pc3 = mresid2' * ev3 ;
          %  vector of projections of data onto ev3
pc3rep = max(abs(pc3 - mean(pc3))) ;
          %  "most representative pc", defined as MAD
mpc3 = ev3 * pc3rep ;
          %  "average vector" for display
mresid3 = (mresid2 - ev3 * pc3') ;
ss3r = sum(sum(mresid3.^2)) ;
ss3 = ss2r - ss3r ;

ev4 = meigvec(:,d-3) ;
          %  eigenvector with largest eigenvalue
pc4 = mresid3' * ev4 ;
          %  vector of projections of data onto ev4
pc4rep = max(abs(pc4 - mean(pc4))) ;
          %  "most representative pc", defined as MAD
mpc4 = ev4 * pc4rep ;
          %  "average vector" for display
mresid4 = (mresid3 - ev4 * pc4') ;
ss4r = sum(sum(mresid4.^2)) ;
ss4 = ss3r - ss4r ;


%  Form mean +- representative eigenvectors
mpc1p = vmean + mpc1 ;
mpc1m = vmean - mpc1 ;
mpc2p = vmean + mpc2 ;
mpc2m = vmean - mpc2 ;
mpc3p = vmean + mpc3 ;
mpc3m = vmean - mpc3 ;
mpc4p = vmean + mpc4 ;
mpc4m = vmean - mpc4 ;





%  Create PC1 movie
%
DPCAM1HAND = figure ;
          %  create a new window
set(DPCAM1HAND, 'NumberTitle', 'off');
set(DPCAM1HAND,'Position', DPCAM1POS) ;
set(DPCAM1HAND,'Name','PC1') ;

subplot(2,1,2) ;
  pccur = pc1 ;
          %  Matrix of current PC loadings
  pccur1 = pccur(1:n1) ;
          %  Current PC Loadings, for Population 1
  pccur2 = pccur(n1+1:n) ;
          %  Current PC Loadings, for Population 2
  [kde1, xgrid1] = gpkde(pccur1) ;
  [kde2, xgrid2] = gpkde(pccur2) ;
  plot(xgrid1,kde1,'r',xgrid2,kde2,'c') ;
    title([PC2STR ' Dir. 1']) ;
    vlim = axis ;
          %  Get axis values for drawing vertical lines
    left = -pc1rep ;
    right = pc1rep ;
    range = right - left ;
    left = left - .05 * range ;
    right = right + .05 * range ;
    bottom = vlim(3) ;
    top = vlim(4) ;
    axis([left right bottom top]) ;
    hold on ;
      plot([pccur2 pccur2],[bottom (top + bottom)/2], 'c') ;
      plot([pccur1 pccur1],[(top + bottom)/2 top], 'r') ;
          %  Show locations of projections 
          %  (pop'n 2 first, since likely more spread)
      plot(xgrid1,kde1,'r',xgrid2,kde2,'c') ;
          %  Do a replot to ensure seeing kde
      plot([pc1rep pc1rep], [bottom top], 'y') ;
          %  Show location of current projection
        tx = left + .1 * (right - left) ;
        ty = bottom + .9 * (top - bottom) ;
        ssstr = num2str(100 * ss1 / ssmr) ;
        tstr = [ssstr '% of MR'] ;
      text(tx,ty,tstr) ;
    hold off ;

mmov1 = [] ;
for iframe = 1:nframe ;
  w = (iframe - 1) / (nframe - 1) ;
  vfeat = (1 - w) * mpc1p + w * mpc1m ;
  linex = (1 - w) * pc1rep + w * (-pc1rep) ;
  mout = coazr(vfeat) ;

  subplot(2,1,1) ;
  pcolor(mxgrid,mygrid,mout) ;
    shading flat ;
    axis('square') ;
      caxis([0 1]) ;
    colormap(COMAP) ;
    hold on ;   % add centering type and bar showing time gone
      if IRECENT == 0 ;  %  then everything is centered at apex normals
        plot(0,0,'+k');
      elseif IRECENT == 1 ;  %  then everything is recentered
        plot(0,0,'ok');
      end ;

      barl = 0.4 * R0 ;
      bary = 0.95 * R0 ;
      barc = bary - barl / 2 ;
        if w < .5 ;
          plot([barc+(w-1/2)*barl, 1.05*barc],[bary,bary],'r') ;
        elseif w == .5 ;
          plot([barc, 1.05*barc],[bary,bary],'m') ;
        else ;
          plot([barc, 1.05*barc+(w-1/2)*barl],[bary,bary],'b') ;
        end ;
        vhand = get(gca,'Children') ;
        set(vhand(1),'LineWidth',5) ;
    hold off ;

    subplot(2,1,2) ;
      vchand = get(gca,'Children') ;
      set(vchand(2),'XData',[linex linex]) ;
          %  Move yellow line over to show location of current projection

   DPCAM1(:,iframe) = getframe(DPCAM1HAND) ;
end ;

DPCAM1 = DPCAM1(:,vmorder') ;
          %  reorder frames, to start and stop at mean

movie(DPCAM1HAND,DPCAM1,NRPT) ;








%  Create PC2 movie
%
DPCAM2HAND = figure ;
          %  create a new window
set(DPCAM2HAND, 'NumberTitle', 'off');
set(DPCAM2HAND,'Position', DPCAM2POS) ;
set(DPCAM2HAND,'Name','PC2') ;

subplot(2,1,2) ;
  pccur = pc2 ;
          %  Matrix of current PC loadings
  pccur1 = pccur(1:n1) ;
          %  Current PC Loadings, for Population 1
  pccur2 = pccur(n1+1:n) ;
          %  Current PC Loadings, for Population 2
  [kde1, xgrid1] = gpkde(pccur1) ;
  [kde2, xgrid2] = gpkde(pccur2) ;
  plot(xgrid1,kde1,'r',xgrid2,kde2,'c') ;
    title([PC2STR ' Dir. 2']) ;
    vlim = axis ;
          %  Get axis values for drawing vertical lines
    left = -pc2rep ;
    right = pc2rep ;
    range = right - left ;
    left = left - .05 * range ;
    right = right + .05 * range ;
    bottom = vlim(3) ;
    top = vlim(4) ;
    axis([left right bottom top]) ;
    hold on ;
      plot([pccur2 pccur2],[bottom (top + bottom)/2], 'c') ;
      plot([pccur1 pccur1],[(top + bottom)/2 top], 'r') ;
          %  Show locations of projections 
          %  (pop'n 2 first, since likely more spread)
      plot(xgrid1,kde1,'r',xgrid2,kde2,'c') ;
          %  Do a replot to ensure seeing kde
      plot([pc2rep pc2rep], [bottom top], 'y') ;
          %  Show location of current projection
        tx = left + .1 * (right - left) ;
        ty = bottom + .9 * (top - bottom) ;
        ssstr = num2str(100 * ss2 / ssmr) ;
        tstr = [ssstr '% of MR'] ;
      text(tx,ty,tstr) ;
    hold off ;

mmov2 = [] ;
for iframe = 1:nframe ;
  w = (iframe - 1) / (nframe - 1) ;
  vfeat = (1 - w) * mpc2p + w * mpc2m ;
  linex = (1 - w) * pc2rep + w * (-pc2rep) ;
  mout = coazr(vfeat) ;

  subplot(2,1,1) ;
  colormap(COMAP) ;
  pcolor(mxgrid,mygrid,mout) ;
    shading flat ;
    axis('square') ;
      caxis([0 1]) ;
    colormap(COMAP) ;
    hold on ;   % add bar showing time gone
      barl = 0.4 * R0 ;
      bary = 0.95 * R0 ;
      barc = bary - barl / 2 ;
        if w < .5 ;
          plot([barc+(w-1/2)*barl, 1.05*barc],[bary,bary],'r') ;
        elseif w == .5 ;
          plot([barc, 1.05*barc],[bary,bary],'m') ;
        else ;
          plot([barc, 1.05*barc+(w-1/2)*barl],[bary,bary],'b') ;
        end ;
        vhand = get(gca,'Children') ;
        set(vhand(1),'LineWidth',5) ;
    hold off ;

    subplot(2,1,2) ;
      vchand = get(gca,'Children') ;
      set(vchand(2),'XData',[linex linex]) ;
          %  Move yellow line over to show location of current projection

   DPCAM2(:,iframe) = getframe(DPCAM2HAND) ;
end ;

DPCAM2 = DPCAM2(:,vmorder') ;
          %  reorder frames, to start and stop at mean

movie(DPCAM2HAND,DPCAM2,NRPT) ;




%  Create PC3 movie
%
DPCAM3HAND = figure ;
          %  create a new window
set(DPCAM3HAND, 'NumberTitle', 'off');
set(DPCAM3HAND,'Position', DPCAM3POS) ;
set(DPCAM3HAND,'Name','PC3') ;

subplot(2,1,2) ;
  pccur = pc3 ;
          %  Matrix of current PC loadings
  pccur1 = pccur(1:n1) ;
          %  Current PC Loadings, for Population 1
  pccur2 = pccur(n1+1:n) ;
          %  Current PC Loadings, for Population 2
  [kde1, xgrid1] = gpkde(pccur1) ;
  [kde2, xgrid2] = gpkde(pccur2) ;
  plot(xgrid1,kde1,'r',xgrid2,kde2,'c') ;
    title([PC2STR ' Dir. 3']) ;
    vlim = axis ;
          %  Get axis values for drawing vertical lines
    left = -pc3rep ;
    right = pc3rep ;
    range = right - left ;
    left = left - .05 * range ;
    right = right + .05 * range ;
    bottom = vlim(3) ;
    top = vlim(4) ;
    axis([left right bottom top]) ;
    hold on ;
      plot([pccur2 pccur2],[bottom (top + bottom)/2], 'c') ;
      plot([pccur1 pccur1],[(top + bottom)/2 top], 'r') ;
          %  Show locations of projections 
          %  (pop'n 2 first, since likely more spread)
      plot(xgrid1,kde1,'r',xgrid2,kde2,'c') ;
          %  Do a replot to ensure seeing kde
      plot([pc3rep pc3rep], [bottom top], 'y') ;
          %  Show location of current projection
        tx = left + .1 * (right - left) ;
        ty = bottom + .9 * (top - bottom) ;
        ssstr = num2str(100 * ss3 / ssmr) ;
        tstr = [ssstr '% of MR'] ;
      text(tx,ty,tstr) ;
    hold off ;

mmov3 = [] ;
for iframe = 1:nframe ;
  w = (iframe - 1) / (nframe - 1) ;
  vfeat = (1 - w) * mpc3p + w * mpc3m ;
  linex = (1 - w) * pc3rep + w * (-pc3rep) ;
  mout = coazr(vfeat) ;

  subplot(2,1,1) ;
  pcolor(mxgrid,mygrid,mout) ;
    shading flat ;
    axis('square') ;
      caxis([0 1]) ;
    colormap(COMAP) ;
    hold on ;   % add bar showing time gone
      barl = 0.4 * R0 ;
      bary = 0.95 * R0 ;
      barc = bary - barl / 2 ;
        if w < .5 ;
          plot([barc+(w-1/2)*barl, 1.05*barc],[bary,bary],'r') ;
        elseif w == .5 ;
          plot([barc, 1.05*barc],[bary,bary],'m') ;
        else ;
          plot([barc, 1.05*barc+(w-1/2)*barl],[bary,bary],'b') ;
        end ;
        vhand = get(gca,'Children') ;
        set(vhand(1),'LineWidth',5) ;
    hold off ;

    subplot(2,1,2) ;
      vchand = get(gca,'Children') ;
        set(vchand(2),'XData',[linex linex]) ;
          %  Move yellow line over to show location of current projection

   DPCAM3(:,iframe) = getframe(DPCAM3HAND) ;
end ;

DPCAM3 = DPCAM3(:,vmorder') ;
          %  reorder frames, to start and stop at mean

movie(DPCAM3HAND,DPCAM3,NRPT) ;




%  Create PC4 movie
%
DPCAM4HAND = figure ;
          %  create a new window
set(DPCAM4HAND, 'NumberTitle', 'off');
set(DPCAM4HAND,'Position', DPCAM4POS) ;
set(DPCAM4HAND,'Name','PC4') ;

subplot(2,1,2) ;
  pccur = pc4 ;
          %  Matrix of current PC loadings
  pccur1 = pccur(1:n1) ;
          %  Current PC Loadings, for Population 1
  pccur2 = pccur(n1+1:n) ;
          %  Current PC Loadings, for Population 2
  [kde1, xgrid1] = gpkde(pccur1) ;
  [kde2, xgrid2] = gpkde(pccur2) ;
  plot(xgrid1,kde1,'r',xgrid2,kde2,'c') ;
    title([PC2STR ' Dir. 4']) ;
    vlim = axis ;
          %  Get axis values for drawing vertical lines
    left = -pc4rep ;
    right = pc4rep ;
    range = right - left ;
    left = left - .05 * range ;
    right = right + .05 * range ;
    bottom = vlim(3) ;
    top = vlim(4) ;
    axis([left right bottom top]) ;
    hold on ;
      plot([pccur2 pccur2],[bottom (top + bottom)/2], 'c') ;
      plot([pccur1 pccur1],[(top + bottom)/2 top], 'r') ;
          %  Show locations of projections 
          %  (pop'n 2 first, since likely more spread)
      plot(xgrid1,kde1,'r',xgrid2,kde2,'c') ;
          %  Do a replot to ensure seeing kde
      plot([pc4rep pc4rep], [bottom top], 'y') ;
          %  Show location of current projection
        tx = left + .1 * (right - left) ;
        ty = bottom + .9 * (top - bottom) ;
        ssstr = num2str(100 * ss4 / ssmr) ;
        tstr = [ssstr '% of MR'] ;
      text(tx,ty,tstr) ;
    hold off ;

mmov4 = [] ;
for iframe = 1:nframe ;
  w = (iframe - 1) / (nframe - 1) ;
  vfeat = (1 - w) * mpc4p + w * mpc4m ;
  linex = (1 - w) * pc4rep + w * (-pc4rep) ;
  mout = coazr(vfeat) ;

  subplot(2,1,1) ;
  pcolor(mxgrid,mygrid,mout) ;
    shading flat ;
    axis('square') ;
      caxis([0 1]) ;
    colormap(COMAP) ;

    hold on ;   % add bar showing time gone
      barl = 0.4 * R0 ;
      bary = 0.95 * R0 ;
      barc = bary - barl / 2 ;
        if w < .5 ;
          plot([barc+(w-1/2)*barl, 1.05*barc],[bary,bary],'r') ;
        elseif w == .5 ;
          plot([barc, 1.05*barc],[bary,bary],'m') ;
        else ;
          plot([barc, 1.05*barc+(w-1/2)*barl],[bary,bary],'b') ;
        end ;
        vhand = get(gca,'Children') ;
        set(vhand(1),'LineWidth',5) ;
    hold off ;

    subplot(2,1,2) ;
      vchand = get(gca,'Children') ;
      set(vchand(2),'XData',[linex linex]) ;
          %  Move yellow line over to show location of current projection

   DPCAM4(:,iframe) = getframe(DPCAM4HAND) ;
end ;

DPCAM4 = DPCAM4(:,vmorder') ;
          %  reorder frames, to start and stop at mean

movie(DPCAM4HAND,DPCAM4,NRPT) ;





%  Create Control window  (in new window)
%
dpcachand = figure ;
set(dpcachand, 'Position', DPCAHANDPOS);
set(dpcachand, 'NumberTitle', 'off');
set(dpcachand, 'Name', 'Push to Run Movie');



%  Create push button for PC 1 movie
%
buttony = VERTGAP ;
buttonwd = (MENUWD - 5 * HORIZGAP) / 4 ;
cbs1 = ['  figure(DPCAM1HAND) ;' ...
        '  colormap(COMAP) ;' ...
        '  movie(DPCAM1HAND,DPCAM1,NRPT) ;'] ;
          %  CallBack String 1: Runs movie for PC1
dpcam1hand = uicontrol(dpcachand,'Style','push',...
              'Position',[HORIZGAP buttony buttonwd BUTTONHT],...
              'String','PC1',...
              'CallBack',cbs1) ;



%  Create push button for PC 2 movie
%
buttony = VERTGAP ;
buttonwd = (MENUWD - 5 * HORIZGAP) / 4 ;
buttonx = buttonwd + 2 * HORIZGAP ;
cbs2 = ['  figure(DPCAM2HAND) ;' ...
        '  colormap(COMAP) ;' ...
        '  movie(DPCAM2HAND,DPCAM2,NRPT) ;'] ;
          %  CallBack String 2: Runs movie for PC2
dpcam2hand = uicontrol(dpcachand,'Style','push',...
              'Position',[buttonx buttony buttonwd BUTTONHT],...
              'String','PC2',...
              'CallBack',cbs2) ;



%  Create push button for PC 3 movie
%
buttony = VERTGAP ;
buttonwd = (MENUWD - 5 * HORIZGAP) / 4 ;
buttonx = 2 * buttonwd + 3 * HORIZGAP ;
cbs3 = ['  figure(DPCAM3HAND) ;' ...
        '  colormap(COMAP) ;' ...
        '  movie(DPCAM3HAND,DPCAM3,NRPT) ;'] ;
          %  CallBack String 3: Runs movie for PC3
dpcam3hand = uicontrol(dpcachand,'Style','push',...
              'Position',[buttonx buttony buttonwd BUTTONHT],...
              'String','PC3',...
              'CallBack',cbs3) ;



%  Create push button for PC 4 movie
%
buttony = VERTGAP ;
buttonwd = (MENUWD - 5 * HORIZGAP) / 4 ;
buttonx = 3 * buttonwd + 4 * HORIZGAP ;
cbs4 = ['  figure(DPCAM4HAND) ;' ...
        '  colormap(COMAP) ;' ...
        '  movie(DPCAM4HAND,DPCAM4,NRPT) ;'] ;
          %  CallBack String 4: Runs movie for PC4
dpcam4hand = uicontrol(dpcachand,'Style','push',...
              'Position',[buttonx buttony buttonwd BUTTONHT],...
              'String','PC4',...
              'CallBack',cbs4) ;



%  Save 2 population analysis Loadings
%
mload = [pc1 pc2 pc3 pc4] ;
PC2LOAD1 = mload(1:n1,:) ;
PC2LOAD2 = mload(n1+1:n,:) ;
