function [dgw,dgh,bw,bh] = gap(br,lo,g,db)
% Undulator gap calculations using Walker and Hallbach formulas
% input: Br, period - lo, Gap - g, difference in field required - db
% output: Gap change required; Walker formula - dgw, Hallbach - dgh, 
% field by Walker - bw, by Hallbach - bh
PI = 3.141592653;
gl = g/lo;
fi = PI * gl;
dbb = db * br;
lo2 = lo * lo;
sh = sinh(fi);
sh3 = 3* sinh(3*fi);
ch = cosh(fi);
coeff = 4 * br/sqrt(2);
bw = coeff / PI * (1/sh - 1/sh3);
coeff1 = 3.33 * br / 0.9;
bh = coeff1 * exp(-gl*(5.47 - 1.8 * gl));
dgw = - sh * sh / ch / coeff * dbb * lo 
lo100 = 100 * lo2;
ex = exp((180*g*g - 547*lo*g)/lo100);
dgh = (360  * g - 547 * lo) * coeff1 * ex / lo100;
dgh = dbb / dgh
return;