%%My attempt to do FDTD with a staggered grid

I=200;
IPLM=220;
i=[1:I];            iplm=[I+1:IPLM];        it=[i,iplm];
ih=[2:IPLM];
il=[1:IPLM-1];

%Velocity Field                      Pressure Field
u=zeros(1,IPLM);                     p=zeros(1,IPLM);       %Field for Gaussian Wave
u1=zeros(1,IPLM);                    p1=zeros(1,IPLM);      %Field Blackman window
%Constants and Values
c=1500;                             %Speed                   c=1500m/s
pho=1;                              %Density                 pho=1 gm/cm^3
k=1/(c^2*pho);                      %compressibility         k=4.44*10^-6 N^-1 cm^2
fmax=1e6;                           %Max frequency           fmax=1 Mhz
lambda_min=c/fmax;                  %Minimum wavelength      lambda=
delta=lambda_min/10;                %Grid spacing            m
h=delta/(c);                       %Time step               t
alpha_max=-(c*k/(delta))*log(.99);   

%Perfectly absorbing boundary condition
alpha=alpha_max*((iplm-I)./(IPLM-I)).^2;
gamma=alpha/k;


%Coefficients for artificial attenuation
e1=ones(1,IPLM);                     e1(iplm)=exp(-alpha.*h./k);
e2=(h/(delta*k)).*ones(1,IPLM);      e2(iplm)=(1-exp(-alpha.*h./k))./(delta.*alpha);
e3=ones(1,IPLM);                     e3(iplm)=exp(-gamma.*h);
e4=(h/(delta*pho)).*ones(1,IPLM);    e4(iplm)=(1-exp(-gamma.*h))./(delta.*pho.*gamma);


nsteps=1000;
set(gcf,'doublebuffer','on');
blackmanlength=50;
blackmanwin=blackman(blackmanlength)
p1source=zeros(nsteps,1);
p1source(1:blackmanlength)=20*blackmanwin;

for t=1:nsteps 
   
    p(ih)=e1(ih).*p(ih)-e2(ih).*(u(ih)-u(il));
    p1(ih)=e1(ih).*p1(ih)-e2(ih).*(u1(ih)-u1(il));
    u(il)=e3(il).*u(il)-e4(il).*(p(ih)-p(il));
    u1(il)=e3(il).*u1(il)-e4(il).*(p1(ih)-p1(il));
    %p1(1)=10*exp(-(t-30.)*(t-30)/100);
    tau=t*fmax;
    %p1(1)=(fmax/(pi*tau))*cos(tau/pi)*sin(tau/pi)*(.84-4*tau^2/(4*tau^2-1)+...
    %                                               .16*tau^2/(tau^2-1));
    p1(1)=p1source(t);
    p1(IPLM)=0;
    %plot(it,p,it,u,it,p1);
    plot(it,p1);
    set(gca,'ylim',[-20,20]);
    pause(.005);
    
end