use strict;
return sub
{
	my $dbh = shift;


	my $fix_embem = sub
	{
		my ($default_template, $db_table, $db_field) = @_;
	
		my ($headers_d, $body_d) = split /\r?\n\r?\n/, $default_template, 2;
		my %headers_d = map { split /\:\s*/, $_, 2 } split /\r?\n/, $headers_d;

		my $subject_d = $headers_d{Subject};
		s/[\s\r\n]//g for $subject_d, $body_d;
		
		my $sth = $dbh->prepare("select id, $db_field from $db_table where $db_field!=''");
		$sth->execute;
	
		while (my $row = $sth->fetchrow_hashref)
		{
			my ($headers, $body) = split /\r?\n\r?\n/, $row->{$db_field}, 2;
			my %headers = map { split /\:\s*/, $_, 2 } split /\r?\n/, $headers;

			my $subject = $headers{Subject};
			s/[\s\r\n]//g for $subject, $body;
	
			if ($subject_d eq $subject && $body_d eq $body && ! $headers{'X-Disabled'})
			{
				$dbh->do("update $db_table set $db_field='' where id=?", undef, $row->{id});
			}
		}
	};
	
	&$fix_embem('Subject: Welcome to "#{Affprog.title}"!

Hi #{User.name}!

You are now a member of #{Affprog.title}!', 'jin_affprog', 'email_welcome');
	
	&$fix_embem('Subject: Welcome!

Welcome and thank you for ordering "#{Package.title}"!
', 'jin_package', 'email_welcome');
	
	&$fix_embem('Subject: Welcome, new customer!

Welcome, #{User.name}!', 'jin_user_settings', 'email_ma2cust');
	
	&$fix_embem('Subject: Welcome!

Welcome, #{User.name}!
', 'jin_user_settings', 'email_me2refered');
	

	&$fix_embem('Subject: Access to #{MembershipURL} disabled

Product:  #{SaleDescription}
URL:      #{MembershipURL}
Username: #{Customer.email}', 'jin_cmsmem', 'email_delete');

	&$fix_embem('Subject: Access to #{MembershipURL} disabled

Product:  #{SaleDescription}
URL:      #{MembershipURL}
Username: #{Customer.email}', 'jin_lmem', 'email_delete');

	&$fix_embem('Subject: Access to #{MembershipURL} disabled

Product:  #{SaleDescription}
URL:      #{MembershipURL}
Username: #{Customer.email}', 'jin_rmem', 'email_delete');

	
	my $sth = $dbh->prepare("select id, user_register from jin_embedded_email where user_register!=''");
	$sth->execute;
	
	while (my $row = $sth->fetchrow_hashref)
	{
		my $templ = $row->{user_register};
		$templ =~ s/\#\{SYS\.URI\}/#{LoginURI}/g;
	
		if ($templ ne $row->{user_register})
		{
			$dbh->do("update jin_embedded_email set user_register=? where id=?", undef, $templ, $row->{id});
		}
	}

	return;
};