function varargout = commblkrician1src2(block, varargin)
% COMMBLKRICIAN1SRC2 Mask dynamic dialog function for Rician source block

% Copyright 1996-2000 The MathWorks, Inc.
%   $Revision: 1.3 $  $Date: 2000/08/27 23:07:49 $


% --- Modes of operation
%		varargin{1} = action =	'init' - Indicates that the block initialization
%													function is calling the code.
%													The code should call the functions to update
%													visibilities/enables etc. and based on these
%													settings, make any changes to the
%													simulink block.
%
%					= CallbackName		-	Indicates that a dialog field callback
%													is executing.
%
%		varargin{2} = 0					- Dynamic dialog initiated callback
%					= 1					- Callback required to update fields only
%

% --- Field numbers

SpecMethod   = 1;
InPhase      = 2;
Quad         = 3;
KFactor      = 4;
Sigma	     = 5;
Seed	     = 6;
SampleTime   = 7;
FrameBased   = 8;
SampPerFrame = 9;
Orient       = 10;

nvarargin = nargin - 1;

switch nvarargin
	case 0
		action = '';
	case 1
		action = varargin{1};
		Args = '';
	otherwise
		action = varargin{1};
		Args = varargin{2:end};

      if(strcmp(action,'UpdateBlocks'))
         output_size = Args;
      end
      
      % --- Breakout the arguments if required
      if((nvarargin > 1) & (isa(Args,'cell')))
         Mask_iMean = Args{1};
         Mask_qMean = Args{2};
         Mask_K     = Args{3};
         Mask_s     = Args{4};
      end;
end;

% --- Field data

Vals  = get_param(block, 'maskvalues');
Vis   = get_param(block, 'maskvisibilities');
En    = get_param(block, 'maskenables');

% Build set of parameters according to different spec method

% "K-factor" method
if(strcmp(Vals{SpecMethod},'K-factor'))   
   idx_set = [KFactor Sigma Seed];
% "Quadrature compoment" method
else    
   idx_set = [InPhase Quad Sigma Seed];
end
   
vLen = [];
ii=1;
for idx=idx_set,
   % Get length of the set of parameters
   vLen=[vLen length(str2num(Vals{idx}))];
   
   % Get dimension of parameters
   vSize{ii}=size(str2num(Vals{idx}));
   ii=ii+1;
end

lenmax = max(vLen);            % Largest of all the parameter lengths
dimcomp = min(find(vLen~=1));  % Index of the first vector parameter
                               %    used for comparison with dimensions of other parameters

%*********************************************************************
% Function:			initialize
%
% Description:		Set the dialogs up based on the parameter values.
%						MaskEnables/MaskVisibles are not save in reference 
%						blocks.
%
% Inputs:			current block
%
% Return Values:	none
%
%********************************************************************

if(strcmp(action,'init'))

   % --- Exit code and error message definitions
   eStr.ecode = 0;
   eStr.emsg  = '';
      
   % Check for consistency among vector parameter lenghts
   if ~isequal(lenmax,1)   % there exist vector parameters
      
      % Check if vector lengths (if any) agree
      if any(find(vLen(find(vLen~=1))~=lenmax)),
         eStr.ecode = 1;
         eStr.emsg  = 'Parameters must be either all scalars, or if more than one of them is a vector, their vector sizes should agree.';
         
      % If dimensions are to be preserved, check if they agree
      elseif strcmp(Vals{Orient},'off') & strcmp(Vals{FrameBased},'off')  
         for idx=[find(vLen~=1)]
            if ~isequal(vSize{idx},vSize{dimcomp})
               eStr.ecode = 1;
               eStr.emsg  = ['Dimensions of parameter values in ', block, ' are inconsistent.'];
            end
         end         
      end
   end

   feval(mfilename,block,'UpdateFields');
   [varargout{1:2}, outputSize] = feval(mfilename,block,'UpdateWs',Args);
   cbFrameBased(block);
   cbOrient(block);
   feval(mfilename,block,'UpdateBlocks',outputSize);
   
   varargout{3}=eStr;
end;

if(strcmp(action,'cbFrameBased'))
    cbFrameBased(block);
end

if(strcmp(action,'cbOrient'))
    cbOrient(block);
end

%----------------------------------------------------------------------
%
%	Block specific update functions
%
%----------------------------------------------------------------------

%*********************************************************************
% Function:			UpDateBlocks
%
% Description:		Set the simulink blocks as required
%
% Inputs:			current block
%
% Return Values:	none
%
%********************************************************************


if(strcmp(action,'UpdateBlocks'))
   
   % Sample-based case
   if(strcmp(Vals{FrameBased},'off'))
      set_param([block, '/Frame Status Conversion'],'outframe','Sample-based');   
      set_param([block, '/Buffer'],'N','1');   % Do not buffer up
      set_param([block, '/Buffer'],'ic','0');
      
      % Interpret as 1-D; OR scalar output
      if(strcmp(Vals{Orient},'on')) | ~any(vLen-1)
         % Interpret as 1-D; OR scalar output
         set_param([block, '/Reshape'],'OutputDimensionality','1-D array');
       
      % 2-D vector output    
       else
          vec = vSize{dimcomp};
          
          % Column vector
          if vec(1) > vec(2)
             set_param([block, '/Reshape'],'OutputDimensionality','Column vector');
          % Row vector   
          else  
             set_param([block, '/Reshape'],'OutputDimensionality','Row vector');
          end            
       end
       
   % Frame-based case
   else
       set_param([block, '/Frame Status Conversion'],'outframe','Frame-based');   
       set_param([block, '/Buffer'],'N','sampPerFrame');   % Buffer up
       set_param([block, '/Reshape'],'OutputDimensionality','Customize');
       
       set_param([block, '/Reshape'],'OutputDimensions',['[sampPerFrame, ',num2str(output_size), ']']);
       
       if str2num(Vals{SampPerFrame}) > 1
          set_param([block, '/Buffer'],'ic','buffic');
       else
          set_param([block, '/Buffer'],'ic','0'); 
       end
       
    end;
 end;
 
%*********************************************************************
% Function:			UpdateWs
%
% Description:		Set the simulink blocks as required
%
% Inputs:			current block
%
% Return Values:	values to be set in the workspace
%
%********************************************************************

if(strcmp(action,'UpdateWs'))

   if(strcmp(Vals{SpecMethod},'Quadrature components'))
      varargout{1} = Mask_iMean;
      varargout{2} = Mask_qMean;
      
   else
      K = Mask_K;
      s = Mask_s;
      m1 = sqrt(2*K(:)).*s(:);
      m2 = 0;
      varargout{1} = m1;
      varargout{2} = m2;
      
   end;
   varargout{3} = lenmax;   % size of desired output
end;


%*********************************************************************
% Function:			UpdateFields
%
% Description:		Update the dialog fields.
%						Indicate that block updates are not required
%
% Inputs:			current block
%
% Return Values:	none
%
%********************************************************************

if(strcmp(action,'UpdateFields'))
	feval(mfilename,block,'SpecMethod',1);
end;

if(strcmp(action,'UpdateIc'))

   sampnum = str2num(Vals{SampPerFrame});
   seed = str2num(Vals{Seed});
   s = Mask_s.*ones(1,lenmax);

   if(strcmp(Vals{SpecMethod},'Quadrature components'))
      m1 = Mask_iMean.*ones(1,lenmax);
      m2 = Mask_qMean.*ones(1,lenmax);
      
   else
      K = Mask_K.*ones(1,lenmax);
      m1 = sqrt(2*K).*s;
      m2 = zeros(1,lenmax);
      
   end;
      varargout{1} = abs(complex( wgn(sampnum,lenmax,1,1,seed(1)).*(ones(sampnum,1)*sqrt(s))+ones(sampnum,1)*m1, ...
                     wgn(sampnum,lenmax,1,1,seed(1)+max(seed)).*(ones(sampnum,1)*sqrt(s))+ones(sampnum,1)*m2 ));

end;

%----------------------------------------------------------------------
%
%	Dynamic dialog specific field functions
%
%----------------------------------------------------------------------
%*********************************************************************
% Function Name:	'SpecMethod'
%
% Description:		Deal with the different specification methods
%
% Inputs:			current block
%						Update mode: Args = 0, block update required
%										 Args = 1, no block update required
%
% Return Values:	none
%
%********************************************************************

if(strcmp(action,'SpecMethod'))

   if(strcmp(Vals{SpecMethod},'Quadrature components'))
		if(strcmp(Vis{KFactor},'on'))
			Vis{KFactor} = 'off';
			En{KFactor}  = 'off';

			Vis{InPhase} = 'on';
			Vis{Quad}    = 'on';
			En{InPhase}  = 'on';
			En{Quad}     = 'on';

			set_param(block,'MaskVisibilities',Vis,'MaskEnables',En);
			if(~Args)
            % --- If update of the block is required when the dynamic dialog
            %     changes, the uncomment the following
				%feval(mfilename,block,'UpdateBlocks');
			end;
		end;
	elseif(strcmp(Vis{KFactor},'off'))
		Vis{KFactor} = 'on';
		En{KFactor}  = 'on';

   	Vis{InPhase} = 'off';
		Vis{Quad}    = 'off';
   	En{InPhase}  = 'off';
		En{Quad}     = 'off';

      set_param(block,'MaskVisibilities',Vis,'MaskEnables',En);
		if(~Args)
         % --- If update of the block is required when the dynamic dialog
         %     changes, the uncomment the following
			%feval(mfilename,block,'UpdateBlocks');
		end;
	end

end;

%----------------------------------------------------------------------
%
%	Setup/Utility functions
%
%----------------------------------------------------------------------



%*********************************************************************
% Function Name:	'default'
%
% Description:		Set the block defaults (development use only)
%
% Inputs:			current block
%
% Return Values:	none
%
%********************************************************************

if(strcmp(action,'default'))

	Cb{SpecMethod}   = [mfilename '(gcb,''SpecMethod'');'];
	Cb{InPhase}      = '';
	Cb{Quad}         = '';
	Cb{KFactor}      = '';
	Cb{Sigma}        = '';
	Cb{Seed}         = '';
	Cb{SampleTime}   = '';
	Cb{FrameBased}    = 'commblkriciansrc2(gcb,''cbFrameBased'');';
	Cb{SampPerFrame}  = '';
	Cb{Orient}        = 'commblkriciansrc2(gcb,''cbOrient'');';

	En{SpecMethod}   = 'on';
	En{InPhase}      = 'off';
	En{Quad}         = 'off';
	En{KFactor}      = 'on';
	En{Sigma}        = 'on';
	En{Seed}         = 'on';
	En{SampleTime}   = 'on';
    En{FrameBased}    = 'on';
    En{SampPerFrame}  = 'off';
    En{Orient}        = 'on';
    
    Vis{SpecMethod}  = 'on';
    Vis{InPhase}     = 'off';
    Vis{Quad}        = 'off';
    Vis{KFactor}     = 'on';
    Vis{Sigma}       = 'on';
    Vis{Seed}        = 'on';
    Vis{SampleTime}  = 'on';
    Vis{FrameBased}   = 'on';
    Vis{SampPerFrame} = 'on';
    Vis{Orient}       = 'on';
    
    % --- Set Callbacks, enable status and visibilities
    set_param(block,'MaskCallbacks',Cb,'MaskEnables',En,'MaskVisibilities',Vis);
    
	% --- Set the start up values.  '' Indicates that the default saved will be used

	Vals{SpecMethod}   = 'K-factor';
	Vals{InPhase}      = 'sqrt(2)';
	Vals{Quad}         = 'sqrt(2)';
	Vals{KFactor}      = '2';
	Vals{Sigma}        = '1';
	Vals{Seed}         = '12345';
    Vals{FrameBased}   = 'off';
    Vals{SampPerFrame} = '1';
	Vals{Orient}       = 'off';
	Vals{SampleTime}   = '1';

	MN = get_param(gcb,'MaskNames');
	for n=1:length(Vals)
		if(~isempty(Vals{n}))
			set_param(block,MN{n},Vals{n});
		end;
	end;

	% --- Update the Vals field with the actual values

	Vals	= get_param(block, 'maskvalues');

   % --- Set the copy function
	set_param(block,'CopyFcn','');

	% --- Set the Mask Modifiable flag as required
	set_param(block,'MaskSelfModifiable','off');

end;


%*********************************************************************
% Function Name:	show all
%
% Description:		Show all of the widgets
%
% Inputs:			current block
%
% Return Values:	none
%
% Notes:				This function is for development use only and allows
%						All fields to be displayed
%
%********************************************************************

if(strcmp(action,'showall'))

	Vis	= get_param(block, 'maskvisibilities');
	En  	= get_param(block, 'maskenables');

	Cb = {};
	for n=1:length(Vis)
		Vis{n} = 'on';
		En{n} = 'on';
		Cb{n} = '';
	end;

   set_param(block,'MaskVisibilities',Vis,'MaskEnables',En,'MaskCallbacks',Cb);

end;



%----------------------------------------------------------------------
%
%	Subfunctions
%
%----------------------------------------------------------------------


%*********************************************************************
% Function Name:	'cbFrameBased'
%
%  - Callback function for 'frameBased' parameter
%
%********************************************************************

function cbFrameBased(block)

Vals  = get_param(block, 'maskvalues');
En    = get_param(block, 'maskenables');
oldEnSamp   = En{9};
oldEnOrient = En{10};

if(strcmp(Vals{8},'off'))
    En{9}  = 'off';
    En{10}  = 'on';
else % 'Frame-based'
    En{9}  = 'on';
    En{10}  = 'off';
end;

if strcmp(oldEnSamp, En{9}) == 0 | strcmp(oldEnOrient, En{10}) == 0
    set_param(block,'MaskEnables',En);
end

%*********************************************************************
% Function Name:	'cbOrient'
%
%  - Callback function for 'orient' parameter
%
%********************************************************************

function cbOrient(block)

Vals  = get_param(block, 'maskvalues');
En    = get_param(block, 'maskenables');
oldEnFrame = En{8};

if(strcmp(Vals{10},'on'))  % Interpret as 1-D
    En{8}  = 'off';
else
    En{8}  = 'on';
end;

if strcmp(oldEnFrame, En{8}) == 0
    set_param(block,'MaskEnables',En);
end

