function s=smaze(x,M,start,final,direc)
% calculate the score

% if go "1" then follow maze that way
% if go "3" then follow maze that way

[m,n]=size(M);
dn=length(x);

MM=ones(m+2,n+2);
MM(2:m+1,2:n+1)=M;

start=start+[1,1];
final=final+[1,1];

pos=start;

s=0;

ind=1;

cc=1;

while ind>0,

if cc>(length(x)+1),
s=s+100000;
return;
end

  if MM(pos(1),pos(2))==0,

	if (pos(1)==final(1))&&(pos(2)==final(2))
	  return;
end

	s=s+1;
else
s=s+5000;
return;
end

if (min(pos)<2)||(pos(1)>(m+1))||(pos(2)>(n+1)),
s=s+50000;
return;
end

			   if ((MM(pos(1)+1,pos(2))==0)&&(MM(pos(1),pos(2)+1)==0)&&(MM(pos(1),pos(2)-1)==0)&&(MM(pos(1)-1,pos(2))==0))||((MM(pos(1),pos(2)-1)==0)&&(MM(pos(1)-1,pos(2))==0)&&(MM(pos(1)+1,pos(2))==0))||((MM(pos(1)-1,pos(2))==0)&&(MM(pos(1)+1,pos(2))==0)&&(MM(pos(1),pos(2)+1)==0))||((MM(pos(1),pos(2)-1)==0)&&(MM(pos(1)+1,pos(2))==0)&&(MM(pos(1),pos(2)+1)==0))||((MM(pos(1),pos(2)-1)==0)&&(MM(pos(1)-1,pos(2))==0)&&(MM(pos(1),pos(2)+1)==0)),

if (cc>length(x)),s=s+100000;return;end

if x(cc)==1,pos=pos+[-1,0];direc=1;
elseif x(cc)==2,pos=pos+[0,1];direc=2;
elseif x(cc)==3,pos=pos+[1,0];direc=3;
else pos=pos+[0,-1];direc=4;
end
cc=cc+1;

else % we arent at a descision point

if direc==3,

if MM(pos(1)+1,pos(2))==0,pos=pos+[1,0];direc=3;
elseif MM(pos(1),pos(2)+1)==0,pos=pos+[0,1];direc=2;
elseif MM(pos(1),pos(2)-1)==0,pos=pos+[0,-1];direc=4;
else % dead end
if (pos==start),
s=s+10000;
return;
elseif (pos==final),
s=s-500;
return;
else
s=s+500;
return;
end
end

elseif direc==1

if MM(pos(1)-1,pos(2))==0,pos=pos+[-1,0];direc=1;
elseif MM(pos(1),pos(2)+1)==0,pos=pos+[0,1];direc=2;
elseif MM(pos(1),pos(2)-1)==0,pos=pos+[0,-1];direc=4;
else % dead end
if (pos==start),
s=s+10000;
return;
elseif(pos==final),
s=s-500;
return;
else
s=s+500;
return;
end
end

elseif direc==2,

if MM(pos(1),pos(2)+1)==0,pos=pos+[0,1];direc=2;
elseif MM(pos(1)+1,pos(2))==0,pos=pos+[1,0];direc=3;
elseif MM(pos(1)-1,pos(2))==0,pos=pos+[-1,0];direc=1;
else % dead end
if (pos==start),
s=s+10000;
return;
elseif(pos==final),
s=s-500;
return;
else
s=s+500;
return;
end
end

elseif direc==4

if MM(pos(1),pos(2)-1)==0,pos=pos+[0,-1];direc=4;
elseif MM(pos(1)+1,pos(2))==0,pos=pos+[1,0];direc=3;
elseif MM(pos(1)-1,pos(2))==0,pos=pos+[-1,0];direc=1;
else % dead end
if (pos==start),
s=s+10000;
return;
elseif(pos==final),
s=s-500;
return;
else
s=s+500;
return;
end
end
end
end
end


