function matchcon(filename,filepath)

%   matchcon

%   This software is protected by german copyright and international treaties.             
%   Copyright 2004 Markus Junghöfer & Peter Peyk. All Rights Reserved.                     
%                                                                                          
%   THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE        
%   NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO,    
%   WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE    
%   OF THE SOFTWARE OR DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS,
%   TRADEMARKS OR OTHER RIGHTS. COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT,       
%   INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE      
%   OR DOCUMENTATION.                                                                      

if nargin < 2
    filepath = [];
end

if nargin < 1
    [filename,filepath]= uigetfile('*.CON','Please select con-file:');
end

file = [filepath, filename];

fid = fopen(file,'rt');
header = fgets(fid);
convec = fgets(fid);

trigger = str2num(convec);

einer = find(trigger==1);
zweier = find(trigger ==2);
dreier = find(trigger ==3);

kgn = min([length(einer),length(zweier),length(dreier)]);

diffeiner = length(einer)-kgn;
diffzweier = length(zweier)-kgn;
diffdreier = length(dreier)-kgn;

einerkill = randperm(length(einer));
einerkill(1+diffeiner:end)=[];

zweierkill = randperm(length(zweier));
zweierkill(1+diffzweier:end)=[];

dreierkill = randperm(length(dreier));
dreierkill(1+diffdreier:end)=[];

trigger(einer(einerkill))=9;
trigger(zweier(zweierkill))=9;
trigger(dreier(dreierkill))=9;

fclose(fid);

newfile = strrep(file,'.con','_eq.con');
fid  = fopen(newfile,'wt');
fprintf(fid,header);
fprintf(fid,num2str(trigger));
fclose(fid);

return

