function temp = mainfig1(camainpar,caestpar) 
% MAINFIG, Controls Main Figure Window for NonParametric regression MOVies
%     Makes 3 windows with simultaneous movies, and 2 windows
%     with local fits and MSE boxes
% Inputs:
%    camainpar - Cell Array of MAIN movie PARameters,
%                   including (in this order):
%       nf - number of frames,  scalar
%           (note: this is also number of "evaluation points of smooth")
%       nrep - number of replays of movie
%       fps - frames per second, controls speed of movie
%       nrif - number of times to Repeat Individual Movie Frames for mpeg
%       colormat - Color matrix
%       movopt - Movie options
%    caestpar - Cell Array of ESTimation setting PARameters
%                   including (in this order):
%       h - bandwidth,   scalar or 3-vector (col)
%       hf - bandwidth factor for local fit snakes (col)
%       lfmag - scalar, horizontal magnification factor for local fit snakes
%       p - local polynomial degree,   scalar or 3-vector (col)
%       n - sample size,  scalar or 3-vector (col)
%       sig - average value of noise level sigma,  scalar or 3-vector
%       xstr - string with name of function for generating x's
%       tarstr - string or 3-string matrix,
%                with name of function for generating target curve m
%       sigstr - string or 3-string matrix,
%                with name of function for generating sigma's
%       kerstr - string or 3-string matrix,
%                with name of function for generating kernel
%       mtitstr - string matrix of titles
%       movoutstr - string with directory and filename 
%                for storing movies as .mpg files
%
% Output:
%     none and draws a graph of the result (in the current figure)
%
%
% A modification of original mainfig, which allows nicer
%    cell arrays of arguments, and works with the menu for
%    saving as mpeg files

%    Copyright (c) J. S. Marron, E. Smith 1999



%  Set global variables
%
global M1 ;
          %  M1 - Main Figure Movie Matrix




%  Set Parameters
%
nxgrid = 50 ;
left = -2 ;
right = 2 ;
bottom = 0 ;
top = 2.5 ;



%  Unpack parameters from cell arrays
%
nf = camainpar{1} ;
nrep = camainpar{2} ;
fps = camainpar{3} ;
nrif = camainpar{4} ;
colormat = camainpar{5} ;
movopt = camainpar{6} ;

h = caestpar{1} ;
hf = caestpar{2} ;
lfmag = caestpar{3} ;
p = caestpar{4} ;
n = caestpar{5} ;
sig = caestpar{6} ;
xstr = caestpar{7} ;
tarstr = caestpar{8} ;
sigstr = caestpar{9} ;
kerstr = caestpar{10} ;
mtitstr = caestpar{11} ;
movoutstr = caestpar{12} ;





%  Adjust inputs to vectors and string matrices
%
if length(h) == 1 ;
  vh = [h; h; h] ;
else;
  vh = h ;
end ;

if length(hf) == 1 ;
  vhf = [hf; hf; hf] ;
else;
  vhf = hf ;
end ;

if length(p) == 1 ;
  vp = [p; p; p] ;
else;
  vp = p ;
end ;

if length(n) == 1 ;
  vn = [n; n; n] ;
else;
  vn = n ;
end ;

if length(sig) == 1 ;
  vsig = [sig; sig; sig] ;
else;
  vsig = sig ;
end ;

if size(xstr,1) == 1 ;
  xstr = str2mat(xstr,xstr,xstr) ;
end ;

if size(tarstr,1) == 1 ;
  tarstr = str2mat(tarstr,tarstr,tarstr) ;
  tar1flag = 1 ;
  %  1 shows all targets are same
else
  tar1flag = 0 ;
end ;

if size(sigstr,1) == 1 ;
  sigstr = str2mat(sigstr,sigstr,sigstr) ;
end ;

if size(kerstr,1) == 1 ;
  kerstr = str2mat(kerstr,kerstr,kerstr) ;
end ;





%  Construct data, global plotting stuff etc.
%
xgrid = linspace(left, right, nxgrid)' ;
           %  plotting grid
xestgrid = linspace(left, right, nf)' ;
           %  grid where curve is estimated
mmgrid = [] ;
mestmgrid = [] ;
maxn = max(vn) ;
mxdat = zeros(maxn,3) ;
           %  x's part of data
mmdat = zeros(maxn,3) ;
           %  target curve m, evaluated at x's part of data
mydat = zeros(maxn,3) ;
           %  y's part of data
mvsig = zeros(maxn,3) ;
           %  sigma factors, for heteroscedasticity
for ipic = 1:3 ;

  eval(['mmgrid = [mmgrid, ' tarstr(ipic,:) '(xgrid)] ;']) ;
           %  evaluate input function to generate m's
  eval(['mestmgrid = [mestmgrid, ' tarstr(ipic,:) '(xestgrid)] ;']) ;
           %  evaluate input function to generate m's

  eval(['xdat = ' xstr(ipic,:) '(vn(ipic),left,right) ;']) ;
           %  evaluate input function to generate x's
  mxdat(1:vn(ipic),ipic) = xdat ;

  eval(['mdat = ' tarstr(ipic,:) '(xdat) ;']) ;
           %  evaluate input function to generate m's
  mmdat(1:vn(ipic),ipic) = mdat ;

  eval(['vsigma = ' sigstr(ipic,:) '(xdat,vsig(ipic)) ;']) ;
           %  evaluate local sigma function
  mvsig(1:vn(ipic),ipic) = vsigma ;

    randn('seed', 39287409) ;
    ydat = mdat + vsigma .* randn(vn(ipic),1) ;
  eval(['mydat(1:vn(ipic),ipic) = ydat ;']) ;
end ;




%  Get Kernel Height Factor
%
vkmax = [] ;
for ipic = 1:3 ;
  eval(['kmax = ' kerstr(ipic,:) '(0,vh(ipic)) ;']) ;
           %  evaluate input kernel function at 0 (which gives max)
  vkmax = [vkmax; kmax] ;  
end ;    %  of ipic loop

kmax = max(vkmax) ;

if kmax > top ;    %  then need to adjust kernel heights
  khtfactor = top / kmax ;
else ;   %  leave kernels heights the same
  khtfactor = 1 ;
end ;



%  Do construction of movie
%
figh = gcf ;    %  get current figure handle

M1 = moviein(nf, figh);

mhatgrid = zeros(nxgrid,3) ;
emhatgrid = zeros(nxgrid,3) ;
for j=1:nf ;
    
  clf;			
  colordef(figh,'none') ; 
          %  this gives good black background, and sets other colors
  set(figh,'Colormap',colormat) ;
  set(figh,'Color',[0 0 0]) ;

  %  Loop through 3 main windows
  %
  mxsnake = zeros(nxgrid,3) ;
  mysnake = zeros(nxgrid,3) ;
  vns = [] ;
  vbias = [] ;
  vsd = [] ;
  for ipic = 1:3 ;
    
    dmdata = desmat(mxdat(1:vn(ipic),ipic),xestgrid(j),vp(ipic)) ;
    dmgrid = desmat(xgrid,xestgrid(j),vp(ipic)) ;
          %  set design matrices

    eval(['kdata = ' kerstr(ipic,:) ...
                      '(mxdat(1:vn(ipic),ipic)-xestgrid(j),vh(ipic)) ;']) ;
    eval(['kgrid = ' kerstr(ipic,:) '(xgrid-xestgrid(j),vh(ipic)) ;']) ;
           %  evaluate input kernel function
    kgrid = khtfactor * kgrid ;

    %  do weighted least squares
    wxdata = dmdata .* vec2mat(kdata,vp(ipic)+1) ;
           %  weighted version of design matrix
    y2beta = inv(wxdata' * dmdata) * wxdata' ;
           %  multiply this times Y to get betahat
           %  multiply X times this to get hat matrix
    hatgrid = dmgrid * y2beta ;
           %  like hat matrix, but gives fit at xgrid
    y2mhat = y2beta(1,:) ;
           %  multiply this times Y to get mhat at current grid point
    mhatgrid(j,ipic) = y2mhat * mydat(1:vn(ipic),ipic) ;
    emhatgrid(j,ipic) = y2mhat * mmdat(1:vn(ipic),ipic) ;
    mvargrid = y2mhat.^2 * mvsig(1:vn(ipic),ipic) .^2 ;
           %  Linear combo of local sig2, with squares of usual weights



    %  get snakes
      flag = abs(xgrid - xestgrid(j)) < vhf(ipic) * vh(ipic) ;

    xsnake = xgrid(flag) ;
    ysnake = hatgrid * mydat(1:vn(ipic),ipic) ;
    ysnake = ysnake(flag) ;
    ns = sum(flag) ;
    mxsnake(1:ns,ipic) = xsnake ;
    mysnake(1:ns,ipic) = ysnake ;
    vns = [vns; ns] ;
          %  number of elements in this snake


    %  get box stuff
    vbias = [vbias; (emhatgrid(j,ipic) - mestmgrid(j,ipic))] ;
    vsd = [vsd; sqrt(mvargrid)] ;


    %  make plot
    subplot(2,3,ipic);
      plot(xgrid,mmgrid(:,ipic),':', ...
                 mxdat(1:vn(ipic),ipic),mydat(1:vn(ipic),ipic),'+', ...
	         [xestgrid(j),xestgrid(j)],[bottom, top],'-', ...
                 xgrid,kgrid,'-', ...
                 xestgrid(1:j),mhatgrid(1:j,ipic),'-', ...
                 xsnake,ysnake,'-') ;
        vhcur = get(gca,'Children')  ;
          %  vector of handles to children of current axes
        set(vhcur(6),'LineWidth',2.5) ;
        set(vhcur(6),'Color',colormat(2,:)) ;
          %  adjust underlying curve
        set(vhcur(5),'MarkerSize',4) ;
        set(vhcur(5),'Color',colormat(3,:)) ;
          %  adjust data scatterplot
        set(vhcur(4),'LineWidth',1) ;
        set(vhcur(4),'Color',colormat(4,:)) ;
          %  adjust location of estimation
        set(vhcur(3),'LineWidth',1.5) ;
        set(vhcur(3),'Color',colormat(5,:)) ;
          %  adjust kernel
        set(vhcur(2),'LineWidth',2) ;
        set(vhcur(2),'Color',colormat(6,:)) ;
          %  adjust running estimate
        set(vhcur(1),'LineWidth',1.5) ;
        set(vhcur(1),'Color',colormat(6+ipic,:)) ;
          %  adjust snake

        htit = get(gca,'Title') ;
        set(htit,'Color',colormat(6+ipic,:)) ;
%	hplot2 = get(gcf,'Children') ;
%	set(hplot2(1),'Color',[.2 .2 .2]) ;
        title(mtitstr(ipic,:));	
        axis([left, right, bottom, top]) ;


  end ;



  %  Do snake window
  %
  subplot(2,3,4) ;
    cla;
    for ipic = 3:-1:1 ;
      hold on ;
        plot(mxsnake(1:vns(ipic),ipic) - xestgrid(j), ...
                  mysnake(1:vns(ipic),ipic)) ;
          vch = get(gca,'Children') ;
          set(vch(1),'LineWidth',1.5) ;
          set(vch(1),'Color',colormat(6+ipic,:)) ;
      hold off ;
      axis([left/lfmag, right/lfmag, bottom, top]) ;
      axis('off') ;
    end ;

    lh = line([0,0], [bottom, top]);
      set(lh, 'Color', colormat(4,:));
      mm = mmgrid(j,:) ;
      if tar1flag == 1 ;
        hold on ;
          plot(0,mean(mm),'o') ;
            vch = get(gca,'Children') ;
            set(vch(1),'Color',colormat(1,:)) ;
        hold off ;
      end ;  
      text(-.2 * (right - left),bottom - .1 * (top - bottom),'local fits') ;
         %  fix this later





  %  Do MSE Box Windows
  %
  if j == 1 ;
    rmsemax = max(sqrt(vbias.^2 + vsd.^2)) ;
  end ;

  %  absolute RMSE boxes
  subplot(2,3,5) ;
    cla ;
    axis('equal') ;
    axis([0, 1, -1, 1]) ;
    axis('off') ;
          %  careful about aspect ratio, so sum of squares is MSE

    xaxis = line ([0, 1], [0, 0]);
    yaxis = line ([0, 0], [-1, 1]);
    set(xaxis, 'color', colormat(2,:));
    set(yaxis, 'color', colormat(2,:));
          %  put down gray axes

    %  draw boxes and circles
    theta = linspace(-pi/2,pi/2,50) ;
    for ipic = 1:3 ;
      sd = vsd(ipic) / rmsemax ;
      bias = vbias(ipic) / rmsemax ;

      rmse = sqrt(bias^2 + sd^2) ;
      s = rmse*sin(theta) ;
      c = rmse*cos(theta) ;
      hold on ;
        lhn = line ([0, sd], [bias, bias]);
        lhb = line ([sd, sd], [0, bias]);
        lhd = line ([0, sd], [0, bias]);
	
        set(lhn, 'color', colormat(6+ipic,:));
        set(lhn, 'LineWidth',1.5) ;
        set(lhb, 'color', colormat(6+ipic,:));
        set(lhb, 'LineWidth',1.5) ;
        set(lhd, 'color', colormat(6+ipic,:));
        set(lhd, 'LineWidth',1.5) ;

        ph = plot(c,s) ;
          set(ph,'Color',colormat(6+ipic,:)) ;
      hold off ;

    end ;



          %  Color matrix, with rows:
          %    1 - bright white,  for text, etc.
          %    2 - gray, for underlying target curve
          %    3 - bright, light blue, for data
          %    4 - dim blue for location of estimation
          %    5 - magenta for kernel
          %    6 - yellow for snake 1
          %    7 - green for snake 2
          %    8 - red for snake 3



      txb = -.4 ;
      tyb = .9 ;
    text(txb,tyb,'bias') ;
      txs = 1 ;
      tys = 0 ;
    text(txs,tys,'std dev') ;
      txn = -.2 ;
      tyn = -1.2 ;
    text(txn,tyn,'Absolute RMSE') ;


  %  relative RMSE boxes
  subplot(2,3,6) ;
    cla ;
    axis('equal') ;
    axis([0, 1, -1, 1]) ;
    axis('off') ;
          %  careful about aspect ratio, so sum of squares is MSE

    xaxis = line ([0, 1], [0, 0]);
    yaxis = line ([0, 0], [-1, 1]);
    set(xaxis, 'color', colormat(2,:));
    set(yaxis, 'color', colormat(2,:));
          %  put down gray axes

    %  draw boxes and circles
    theta = linspace(-pi/2,pi/2,50) ;
    rmsemaxtf = max(sqrt(vbias.^2 + vsd.^2)) ;
          %  root MSE max, this frame
    for ipic = 1:3 ;
      sd = vsd(ipic) /rmsemaxtf ;
      bias = vbias(ipic) / rmsemaxtf ;

      rmse = sqrt(bias^2 + sd^2) ;
      s = rmse*sin(theta) ;
      c = rmse*cos(theta) ;
      hold on ;
        lhn = line ([0, sd], [bias, bias]);
        lhb = line ([sd, sd], [0, bias]);
        lhd = line ([0, sd], [0, bias]);
	
        set(lhn, 'color', colormat(6+ipic,:));
        set(lhn, 'LineWidth',1.5) ;
        set(lhb, 'color', colormat(6+ipic,:));
        set(lhb, 'LineWidth',1.5) ;
        set(lhd, 'color', colormat(6+ipic,:));
        set(lhd, 'LineWidth',1.5) ;

        ph = plot(c,s) ;
          set(ph,'Color',colormat(6+ipic,:)) ;
      hold off ;

    end ;

    text(txb,tyb,'bias') ;
    text(txs,tys,'std dev') ;
    text(txn,tyn,'Relative RMSE') ;


  M1(:,j) = getframe(figh);



end ;






%  Set up movie control menu
%

movmenuh = uimenu (figh,'Label','Movie Controls') ;
          %  Put main menu on menu bar

  replaycbs = ['h = axes(''Visible'', ''off'');' ...
               'h = axes(''Position'', [0 0 1 1]);' ...
               'movie(M1, nrep, fps);'
                                            ] ;
          %  Call Back String for Replay Menu
  replaymenuh = uimenu(movmenuh,'Label','Replay Movie', ...
                      'CallBack',replaycbs) ;
          %  create Replay Movie Menu

  savecbs = ['M1save = M1(:,vmorder'') ;' ...
             'mpgwrite(M1save,colormat,''' movoutstr ''',movopt) ;' ...
             'disp(''  '') ;' ...
             'disp([''    Finished creating ' movoutstr ' '']) ;' ...
                                         ] ;
          %  Call Back String for MPEG Save Menu
  savemenuh = uimenu(movmenuh,'Label','MPEG Save of Movie', ...
                      'CallBack',savecbs, ...
                      'Separator','On') ;
          %  create MPEG Save Menu



%  Do Matlab Play of movie
%
h = axes('Visible', 'off');
h = axes('Position', [0 0 1 1]);
movie(M1, nrep, fps);



