function [targetpicmat]=matchbrightness(sourcefilename,sourcefilepath,targetfilename,targetfilepath)
%   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.                                                                      
sourcefile=[sourcefilepath,sourcefilename];
targetfile=[targetfilepath,targetfilename];

sourcepicmat=double(imread(sourcefile,'jpg'));
targetpicmat=double(imread(targetfile,'jpg'));
totbrightsourcemat=sum(sourcepicmat,3);
totbrighttargetmat=sum(targetpicmat,3);
faktormat=sourcepicmat./targetpicmat;
targetpicmat=targetpicmat.*((faktormat-1)*0.5+1);

imwrite(uint8(targetpicmat),'C:\outpic.jpg','jpg');
return

