function interpolateFieldmapVarZnR(mapfn,range_z, range_r, cavity_info, N)
% writes the field map in t7 format containing the longitudinal and radial 
% electrical field as well as the transverse magnetic field
%
% Author: Christof Kraus christof.kraus@psi.ch
%
% mapfn        is the filename of the on-axis longitudinal electrical field
% range_z      is the range in longitudinal direction over which the field
%              should be interpolated
% range_r      is the range in transverse direction over which the field 
%              should be interpolated
% cavity_info  an array containing the length and the frequency (in this
%              order!)
% N            the number of fourier coefficients to be used

map = load(mapfn);
% make the fieldmap periodic; 
% if it allready is periodic comment out the second line
map2(1:size(map,1)) = map(:,2);
map2(2*size(map,1):-1:size(map,1)+1) = map(:,2);

if N > size(map,1)
    N = size(map,1)
end

fft_map = fft(map2)/size(map,1);

if size(range_r,2) > size(range_r,1)
    range_r = range_r';
end
if size(range_z,2) > size(range_z,1)
    range_z = range_z';
end
size_z = size(range_z,1);
size_r = size(range_r,1);

E = []; Ez = []; Er = []; Bt = [];

for j = 1:size_r
    for i=1:size_z
        [Ezp Erp Btp] = interpolateFieldmap(fft_map(1:N),range_r(j,1),range_z(i,1),cavity_info);
        Ez(j,i) = Ezp;
        Er(j,i) = Erp;
        Bt(j,i) = Btp;
    end
end

for j = 1:size_r
    E((j-1)*size_z+1:j*size_z,1) = Ez(j,:);
    E((j-1)*size_z+1:j*size_z,2) = Er(j,:);
    E((j-1)*size_z+1:j*size_z,4) = Bt(j,:);
end    
E(:,4) = zeros(size_r*size_z,1);

header = [sprintf('%1.8f %1.8f %d\n',range_z(1)*100, range_z(size_z)*100, size_z-1) ...
          sprintf('%1.8f\n', cavity_info(2)) ...
          sprintf('%1.8f %1.8f %d',range_r(1)*100, range_r(size_r)*100, size_r-1)];
dotposition = strfind(mapfn,'.');
if size(dotposition,2) == 0
    lastdotposition = size(mapfn,2);
else
    lastdotposition = dotposition(size(dotposition,2)) - 1;
end
t7filename = strcat(mapfn(1:lastdotposition),'.T7temp');
headerfilename = strcat(mapfn(1:lastdotposition),'.head');
command = ['save  ',t7filename,' E -ASCII'];
eval(command);

systemcall = ['echo ''' header '''>' headerfilename];
system(systemcall);

systemcall = ['cat ' headerfilename ' ' t7filename '>' t7filename(1:size(t7filename,2)-4)];
system(systemcall);

systemcall = ['rm ' headerfilename ' ' t7filename];
system(systemcall);
