function [ xrnew, yrnew, CM, movd, tflag ] = movrob( xr,yr, CM, movd, targ )
%move robot one step and check for proximity to target
% Detailed explanation goes here
%current robot center is at xr, yr
nxtmv=[0 1; 1 0; 0 -1; -1 0]; %table of dx, dy for up, right, down, left

tflag=0; %target found flag not set
flag2=0; %set to one if free neighbor found

if (movd==1); %look one step ahead in current direction of travel
xt=xr; yt=yr+1; %check next neighbor in up direction
elseif (movd==2)
xt=xr+1; yt=yr; %check right direction
elseif (movd==3)
xt=xr; yt=yr-1; %check down direction
elseif (movd==4)
xt=xr-1; yt=yr; %check left direction
end

%now have coords of next neighbor in current travel direction
if (CM(xt, yt)==0); %proposed neighbor is free and unexplored and not target
xrnew=xt; yrnew=yt; %move there
CM(xrnew,yrnew)=0.5; %explored use 0.5 for communication, 0 for none
%don't change travel direction movd

else; %look for free neighbor in another direction (if none, go to prev. explored neighbor)
%check all neighbors in CW succession for first free one.
%if none is free, take random previously explored cell
%there must be at least one of these, or else robot is trapped
%but it can't be since at worst it could backtrack the way it came
%here.

nb1=1+floor(rand*3.99); %pick a random direction 1 - 4 for first check, then perform subsequent checks in CW sequence
for nbs=1:4; %check all 4 neighbors
nb=1+mod(nb1+nbs, 4); %cycle through all 4 starting at random
xt=xr+nxtmv(nb,1); yt=yr+nxtmv(nb,2); %first neighbor to check

if (CM(xt, yt)==0); %proposed neighbor is free
movd=nb; %change travel direction to current
xrnew=xt; yrnew=yt; %move there
CM(xrnew,yrnew)=0.5; %mark explored use 0.5 for communication, 0 for none
flag2=1; break; %free neighbor found - stop checking
end
end

%If flag2=0, there is no free neighbor. Need to revisit a previously explored neighbor to get out
nb1=1+floor(rand*3.99); %pick a random direction 1 - 4 for first check, then perform subsequent checks in CW sequence
for nbs=1:4; %check all 4 neighbors
nb=1+mod(nb1+nbs, 4); %cycle through all 4 starting at random
xt=xr+nxtmv(nb,1); yt=yr+nxtmv(nb,2); %first neighbor to check

if ((CM(xt, yt)==.5)); %proposed neighbor is prev. explored or occupied by another robot

movd=nb; %change travel direction to current
xrnew=xt; yrnew=yt; %move there
CM(xrnew,yrnew)=CM(xt, yt); %don't change value of cell
flag2=1; break; %suitable neighbor found - stop checking
end
end

%at this point, flag2 should be set

if (flag2 ==0)
disp('error: flag2 never set')
end
end
%Now we have a new location and possibly a new direction defined

%check here for proximity to target after move
targx=targ(1); targy=targ(2);
t1=abs(targx-xrnew); t2=abs(targy-yrnew);
ts=t1+t2;
if(ts<3)
tflag=1; %set target found flag
end

end