function [Ctime,Cmag,Catalog,Mc]=FiltSpace(Ctime,Cmag,Catalog,s1)

clc
id_time=findfield(Catalog,'Occurrence_Time');
id_X=findfield(Catalog,'X');id_Y=findfield(Catalog,'Y');
id_Lat=findfield(Catalog,'Lat');id_Long=findfield(Catalog,'Long');
% SELECT COORDINATES SYSTEM
if id_X==0;
            disp('Only Geopraphical Coordinates are Available')
            XCO=Catalog(id_Long).val;YCO=Catalog(id_Lat).val;
elseif id_Lat==0
            disp('Only Cartesian Coordinates are Available')
            XCO=Catalog(id_X).val;YCO=Catalog(id_Y).val;
else
opts.Interpreter='tex';opts.Default='Geographical';
quest='Please Select Coordinate System:';
answer=questdlg(quest,'Coordinate System','Geographical','Cartesian',opts);

        if strcmp(answer,'Geographical')
        XCO=Catalog(id_Long).val;YCO=Catalog(id_Lat).val;
        else    
        XCO=Catalog(id_X).val;YCO=Catalog(id_Y).val;
        end

end


% AREA SELECTION MODE
opts.Interpreter='tex';opts.Default='Polygon';
quest='Please Choose an Area Selection Mode:';
answer1=questdlg(quest,'Data Selection','Polygon','Circular',opts);
plot(XCO,YCO,'o')
switch answer1
    case 'Polygon'
        h=drawpolygon;clc
        display('Use mouse to define the area, then press any key to continue')
        pause
in=inpolygon(XCO,YCO,h.Position(:,1),h.Position(:,2));
Catalog=newCat(Catalog,in,s1);
hold on;plot(XCO(in),YCO(in),'rx')
    case 'Circular'
        h=drawcircle;clc
        display('Use mouse to define the area, then press any key to continue')       
        pause
in=inpolygon(XCO,YCO,h.Vertices(:,1),h.Vertices(:,2));
Catalog=newCat(Catalog,in,s1);
hold on;plot(XCO(in),YCO(in),'rx')
end




Cmag=Cmag(in);
Ctime=Ctime(in);
Mc=min(Cmag);

pause(1)
close,clc

n=length(Ctime);
disp(['number of events: ',num2str(n)]) 
end

%Functions

function Data=newCat(Catalog,in,s1)
cou=1;
for i=1:length(s1)
    x=Catalog(s1(i)).val(in);
    index=isnan(x)==0;
    x=x(isnan(x)==0);
    Data(cou).field=Catalog(s1(i)).field;
    Data(cou).fieldType=Catalog(s1(i)).fieldType;
    Data(cou).val=nan(size(index)); Data(cou).val(index)=x;
    cou=cou+1;
end



end



