function viewfields;

global A y

fid = fopen('dcinj.in', 'rt');

y = 1;
while feof(fid) == 0;
    tline = fgetl(fid);
    a = strfind(tline,'!');
    if(~isempty(a))
        tline = tline(1:a-1);
    end
    A{y} = tline;
    y=y+1;
end
fclose(fid); 

E1 = namval('maxe\(1\)');
E2 = namval('maxe\(2\)');
E3 = namval('maxe\(3\)');
E4 = namval('maxe\(4\)');
E5 = namval('maxe\(5\)');
E6 = namval('maxe\(6\)');
E7 = namval('maxe\(7\)');

C1 = namval('c_pos\(1\)');
C2 = namval('c_pos\(2\)');
C3 = namval('c_pos\(3\)');
C4 = namval('c_pos\(4\)');
C5 = namval('c_pos\(5\)');
C6 = namval('c_pos\(6\)');
C7 = namval('c_pos\(7\)');

B1 = namval('maxb\(1\)');
B2 = namval('maxb\(2\)');

S1 = namval('s_pos\(1\)');
S2 = namval('s_pos\(2\)');

Z = namval('zstop');

g = load('fields/dcgun.dat');
b = load('fields/buncher.dat');
c = load('fields/srf2cell.dat');
c_r = load('fields/srf2cell_r.dat');
s = load('fields/solenoid.dat');

g(:,2) = g(:,2) / max(abs(g(:,2)));
b(:,2) = b(:,2) / max(abs(b(:,2)));
c(:,2) = c(:,2) / max(abs(c(:,2)));
c_r(:,2) = c_r(:,2) / max(abs(c_r(:,2)));
s(:,2) = s(:,2) / max(abs(s(:,2)));

if (isempty(findobj('Tag','Fields')))
   scrsz = get(0,'ScreenSize');
   figure('Position',[12 1 scrsz(3)/1.2 scrsz(4)/1.2], 'Tag', 'Fields', 'Name', 'viewfields');
else
    figure(findobj('Tag', 'Fields'));
end

subplot(2,1,1);
plot(g(:,1)+C1,g(:,2)*E1, 'r-', ...
     b(:,1)+C2,b(:,2)*E2, 'r-', ...
     c(:,1)+C3,c(:,2)*E3, 'r-', ...
     c_r(:,1)+C4,c_r(:,2)*E4, 'r-', ...
     c(:,1)+C5,c(:,2)*E5, 'r-', ...
     c_r(:,1)+C6,c_r(:,2)*E6, 'r-', ...
     c(:,1)+C7,c(:,2)*E7, 'r-')
 axis([0 Z -Inf Inf]);
 xlabel('position (m)');
 ylabel('electric field (MV/m)');

subplot(2,1,2);
plot(b(:,1)+S1,b(:,2)*B1, 'b-', ...
     b(:,1)+S2,b(:,2)*B2, 'b-')
 axis([0 Z -Inf Inf]);
 xlabel('position (m)');
 ylabel('magnetic field (T)');


function v = namval(s);

global A y

s1 = '(?<=';
s2 = '\s*=\s*)\-?\w*\.?\w*';

found = 0;
for ii = 1:y-1
[mat idx] = regexpi(A{ii}, [s1 s s2], 'match', 'start');
if(~isempty(mat))
    found = 1;
    mat;
    break
end
end

if(~found)
    error('cannot find name in Astra input file')
end

v = str2num(mat{1});
