function varargout = KspaceImageSpace(varargin)
% KSPACEIMAGESPACE M-file for KspaceImageSpace.fig
%      KSPACEIMAGESPACE, by itself, creates a new KSPACEIMAGESPACE or raises the existing
%      singleton*.
%
%      H = KSPACEIMAGESPACE returns the handle to a new KSPACEIMAGESPACE or the handle to
%      the existing singleton*.
%
%      KSPACEIMAGESPACE('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in KSPACEIMAGESPACE.M with the given input arguments.
%
%      KSPACEIMAGESPACE('Property','Value',...) creates a new KSPACEIMAGESPACE or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before KspaceImageSpace_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to KspaceImageSpace_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help KspaceImageSpace

% Last Modified by GUIDE v2.5 30-Oct-2009 08:44:59

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
    'gui_Singleton',  gui_Singleton, ...
    'gui_OpeningFcn', @KspaceImageSpace_OpeningFcn, ...
    'gui_OutputFcn',  @KspaceImageSpace_OutputFcn, ...
    'gui_LayoutFcn',  [] , ...
    'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before KspaceImageSpace is made visible.
function KspaceImageSpace_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to KspaceImageSpace (see VARARGIN)

% Choose default command line output for KspaceImageSpace
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);
% handles.dims=(get(hObject,'String'));
handles.dims=str2double(get(handles.edit_dimensions,'String'));
handles.FractKspace=str2double(get(handles.edit_FractKspace,'String'));
handles.DSkspace=str2double(get(handles.edit_DSkspace,'String'));
handles.partialkspace=str2double(get(handles.edit_partialkspace,'String'));
handles.Image2CreateValue=get(handles.popupmenu_Image,'Value');
handles.weighting=ones(handles.dims);
handles.WeightingConstant=str2double(get(handles.edit_WeightingConstant,'String'));
handles.artefactmat=zeros(handles.dims);
handles.FourierValue=1;
handles.showphase=0;%get(handles.radiobutton_showphase,'Value')


guidata(findobj('Tag','KspaceImageSpaceFigure'),handles);
Initiate_ImageObject()

% UIWAIT makes KspaceImageSpace wait for user response (see UIRESUME)
% uiwait(handles.KspaceImageSpaceFigure);


% --- Outputs from this function are returned to the command line.
function varargout = KspaceImageSpace_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;



function edit_dimensions_Callback(hObject, eventdata, handles)
% hObject    handle to edit_dimensions (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit_dimensions as text
%        str2double(get(hObject,'String')) returns contents of edit_dimensions as a double

handles=guidata(findobj('Tag','KspaceImageSpaceFigure'));
handles.dims=str2double(get(hObject,'String'));
guidata(findobj('Tag','KspaceImageSpaceFigure'),handles);


% --- Executes on selection change in popupmenu_FT.
function popupmenu_FT_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu_FT (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns popupmenu_FT contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu_FT

handles=guidata(findobj('Tag','KspaceImageSpaceFigure'));
contents = get(hObject,'String');
handles.FourierToPerform=contents{get(hObject,'Value')};
handles.FourierValue=get(hObject,'Value');
guidata(findobj('Tag','KspaceImageSpaceFigure'),handles);



function edit_FractKspace_Callback(hObject, eventdata, handles)
% hObject    handle to edit_FractKspace (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit_FractKspace as text
%        str2double(get(hObject,'String')) returns contents of edit_FractKspace as a double
handles=guidata(findobj('Tag','KspaceImageSpaceFigure'));
handles.FractKspace=str2double(get(hObject,'String'));
guidata(findobj('Tag','KspaceImageSpaceFigure'),handles);


function edit_DSkspace_Callback(hObject, eventdata, handles)
% hObject    handle to edit_DSkspace (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit_DSkspace as text
%        str2double(get(hObject,'String')) returns contents of edit_DSkspace as a double
handles=guidata(findobj('Tag','KspaceImageSpaceFigure'));
handles.DSkspace=str2double(get(hObject,'String'));
guidata(findobj('Tag','KspaceImageSpaceFigure'),handles);



function edit_partialkspace_Callback(hObject, eventdata, handles)
% hObject    handle to edit_partialkspace (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit_partialkspace as text
%        str2double(get(hObject,'String')) returns contents of edit_partialkspace as a double

handles=guidata(findobj('Tag','KspaceImageSpaceFigure'));
handles.partialkspace=str2double(get(hObject,'String'));
guidata(findobj('Tag','KspaceImageSpaceFigure'),handles);


% --- Executes on button press in pushbutton_DisplayImage.
function pushbutton_DisplayImage_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_DisplayImage (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


kspaceSamplingRegion();
handles=guidata(findobj('Tag','KspaceImageSpaceFigure'));
handles.artefactmat(end/2,end/2);
handles.kspace(end/2,end/2);

% in the case it performs fourier transform or discrete fourier transform
if handles.FourierValue==1
    handles.kspace2=handles.weighting.*handles.SampledPoints.*handles.kspace+handles.artefactmat.*handles.SampledPoints;
    handles.PhDImage2=(ifftshift(ifftn(fftshift(handles.kspace2))));
    dims2=size(handles.PhDImage2,1);
elseif handles.FourierValue==2
    
    handles.kspace2=reshape(handles.SampledPoints(handles.SampledPoints4DFT==1).*handles.weighting(handles.SampledPoints4DFT==1)...
        .*handles.kspace(handles.SampledPoints4DFT==1)+...
        handles.SampledPoints(handles.SampledPoints4DFT==1).*handles.artefactmat(handles.SampledPoints4DFT==1),...
        [sqrt(length(find(handles.SampledPoints4DFT==1))) sqrt(length(find(handles.SampledPoints4DFT==1)))]...
        );
    handles.PhDImage2=(ifftshift(ifftn(fftshift(handles.kspace2))));
    dims2=size(handles.PhDImage2,1)
elseif handles.FourierValue==3 %readout filtering 
    Imagefraction=handles.DSkspace;
    dims1=handles.dims;
        SampleRegion=zeros(handles.dims);
    if Imagefraction==1
        SampleRegion=ones(handles.dims);
    else
        SampleRegion(:,...
            round(dims1/2-dims1/(2*Imagefraction)+1):1:round(dims1/2+dims1/(2*Imagefraction)-1))=1;
    end

    handles.kspace2=(fftshift(fftn(ifftshift(handles.PhDImage1.*SampleRegion))));


    handles.kspace2=reshape(handles.SampledPoints(handles.SampledPoints4DFT==1).*handles.weighting(handles.SampledPoints4DFT==1)...
        .*handles.kspace2(handles.SampledPoints4DFT==1)+...
        handles.SampledPoints(handles.SampledPoints4DFT==1).*handles.artefactmat(handles.SampledPoints4DFT==1),...
        [sqrt(length(find(handles.SampledPoints4DFT==1))) sqrt(length(find(handles.SampledPoints4DFT==1)))]...
        );
%     handles.kspace2=reshape(handles.weighting(handles.SampledPoints==1)...
%         .*handles.kspace2(handles.SampledPoints==1)+handles.artefactmat(handles.SampledPoints==1),...
%         [sqrt(length(find(handles.SampledPoints==1))) sqrt(length(find(handles.SampledPoints==1)))]...
%         );
    handles.PhDImage2=(ifftshift(ifftn(fftshift(handles.kspace2))));
    dims2=size(handles.PhDImage2,1)
elseif handles.FourierValue==4 %homodyne filtering
    
    handles.kspace2=reshape(handles.weighting(handles.SampledPoints==1)...
        .*handles.kspace(handles.SampledPoints==1)+...
        handles.artefactmat(handles.SampledPoints==1),...
        [(length(find(handles.SampledPoints==1)))/sqrt(length(find(handles.SampledPoints4DFT==1))) sqrt(length(find(handles.SampledPoints4DFT==1)))]...
        );
    
    handles.PhDImage2 = permute(homodyne_recon(permute(handles.kspace2,[2 1])),[2 1]);
     handles.kspace2=(fftshift(fftn(ifftshift(handles.PhDImage2))));
    dims2=size(handles.PhDImage2,1);

end;

DisplayImages(handles.PhDImage2,handles.kspace2)

guidata(findobj('Tag','KspaceImageSpaceFigure'),handles);


% --- Executes on selection change in popupmenu_kspace2show.
function popupmenu_kspace2show_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu_kspace2show (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns popupmenu_kspace2show contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu_kspace2show
% --- Executes on selection change in popupmenu_Image.
handles=guidata(findobj('Tag','KspaceImageSpaceFigure'));
contents = get(hObject,'String');
handles.kspace2show=contents{get(hObject,'Value')};
handles.kspace2showValue=get(hObject,'Value');
guidata(findobj('Tag','KspaceImageSpaceFigure'),handles);

if handles.kspace2showValue==2
    kspaceSamplingRegion()
    handles=guidata(findobj('Tag','KspaceImageSpaceFigure'));
    temp=(ifftshift(ifftn(fftshift(handles.SampledPoints))));
    DisplayImages(temp,handles.SampledPoints)

elseif handles.kspace2showValue==3
    temp=(ifftshift(ifftn(fftshift(handles.weighting))));
    DisplayImages(temp,handles.weighting)

elseif handles.kspace2showValue==1
    DisplayImages(handles.PhDImage2,handles.kspace2)

end;
guidata(findobj('Tag','KspaceImageSpaceFigure'),handles);


function popupmenu_Image_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu_Image (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns popupmenu_Image contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu_Image

%cheks which is the image you want to work with
handles=guidata(findobj('Tag','KspaceImageSpaceFigure'));
contents = get(hObject,'String');
handles.Image2Create=contents{get(hObject,'Value')};
handles.Image2CreateValue=get(hObject,'Value');
guidata(findobj('Tag','KspaceImageSpaceFigure'),handles);
Initiate_ImageObject()

% --- Executes on button press in pushbutton_createimage.
function pushbutton_createimage_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_createimage (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
Initiate_ImageObject()
popupmenu_kspaceweighting_Callback(handles.popupmenu_kspaceweighting,[],handles)
kspaceSamplingRegion()

% --- Executes on selection change in popupmenu_kspaceweighting.
function popupmenu_kspaceweighting_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu_kspaceweighting (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns popupmenu_kspaceweighting contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu_kspaceweighting
handles=guidata(findobj('Tag','KspaceImageSpaceFigure'));
contents = get(hObject,'String');
handles.kspaceweighting=contents{get(hObject,'Value')};
handles.kspaceweightingValue=get(hObject,'Value');


if handles.kspaceweightingValue==1
    handles.weighting=ones(handles.dims);
elseif handles.kspaceweightingValue==2 % T2star on gradient echo
    handles.weighting=exp(-repmat(handles.FractKspace*(1:handles.dims),[handles.dims 1])...
        /(handles.dims*handles.WeightingConstant) );
elseif handles.kspaceweightingValue==3 % T2star on spin echoecho
    handles.weighting=exp(-repmat(handles.FractKspace*([[flipdim(1:(handles.dims/2),2)],[1:(handles.dims/2)]]),[handles.dims 1])...
        /(handles.dims*handles.WeightingConstant) );
elseif handles.kspaceweightingValue==4 % Tse with 4 echos
nechos=4
    handles.weighting=exp(-repmat(ceil(([[1:(handles.dims/2)],[flipdim(1:(handles.dims/2),2)]])/(handles.dims/2)*handles.FractKspace*nechos)*(handles.dims/2)...
                                    ,[handles.dims 1])...
        /(handles.dims*handles.WeightingConstant) );
elseif handles.kspaceweightingValue==5 % EPI
    temp=repmat([zeros(handles.DSkspace,1)' ones(handles.DSkspace,1)'],[handles.dims ceil(handles.dims/handles.DSkspace)]);
    temp=temp(1:handles.dims,1:handles.dims)';

    handles.weighting=exp(-i*handles.WeightingConstant*2*pi*repmat(handles.FractKspace,[handles.dims handles.dims])...
        .*temp );
elseif handles.kspaceweightingValue==6 % appodization
    dims=round(handles.dims/handles.FractKspace);
    k=(-dims/2+1):(dims/2);
    wm=dims/2*1/handles.WeightingConstant;
    k0=max(abs(k))-wm/2;
    window_2(1:length(k))=1;

    window_2(1:wm)=(cos(pi*(abs(k(1:wm))-(k0+1-(wm/2)))/(2*wm))).^2;
    window_2((length(k)-wm+1):length(k))=(cos(pi*(abs(k(((length(k)-wm+1):length(k))))-(k0-(wm/2)))/(2*wm))).^2;

    window_2([1 length(k)])=0;
    %     length(window_2)
    %     length(k)
    kspacedataW=zeros([handles.dims 1]);
    %     size(kspacedataW(round(handles.dims/2-dims/2+1):round(handles.dims/2-
    %     dims/2+length(k))))
    %     size((squeeze(window_2)))
    kspacedataW(round(handles.dims/2-dims/2+1):round(handles.dims/2-dims/2+length(k)))=(squeeze(window_2))';
    handles.weighting=repmat(kspacedataW,[1 handles.dims]).*repmat(kspacedataW',[handles.dims 1]);
elseif handles.kspaceweightingValue==7 % phase ramp
    handles.weighting=exp(-i*handles.WeightingConstant*2*pi*repmat(handles.FractKspace*(1:handles.dims),[handles.dims 1])...
        /(handles.dims) );
elseif handles.kspaceweightingValue==8 % translation half way through
    handles.weighting=exp(-i*handles.WeightingConstant*2*pi*repmat(handles.FractKspace*(1:handles.dims),[handles.dims 1])...
        /(handles.dims) );
        handles.weighting(1:round(handles.dims/2+rand(1)*handles.dims/4),:)=1;

end;

guidata(findobj('Tag','KspaceImageSpaceFigure'),handles);


function edit_WeightingConstant_Callback(hObject, eventdata, handles)
% hObject    handle to edit_WeightingConstant (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit_WeightingConstant as text
%        str2double(get(hObject,'String')) returns contents of edit_WeightingConstant as a double

handles=guidata(findobj('Tag','KspaceImageSpaceFigure'));
handles.WeightingConstant=str2double(get(hObject,'String'));

guidata(findobj('Tag','KspaceImageSpaceFigure'),handles);
popupmenu_kspaceweighting_Callback(handles.popupmenu_kspaceweighting,[],handles)

% --- Executes on selection change in popupmenu_artefact.
function popupmenu_artefact_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu_artefact (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns popupmenu_artefact contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu_artefact


handles=guidata(findobj('Tag','KspaceImageSpaceFigure'));

contents = get(hObject,'String');
handles.kspaceartefact=contents{get(hObject,'Value')};
handles.kspaceartefactValue=get(hObject,'Value');

handles.artefactmat=zeros(handles.dims);
if handles.kspaceartefactValue==1 %no artefacts
    handles.artefactmat=zeros(handles.dims);
elseif handles.kspaceartefactValue==2 % spiking
    handles.artefactmat(round(rand(1)*handles.dims),round(rand(1)*handles.dims))=(2*rand(1)+2)*max(handles.kspace(:));
elseif handles.kspaceartefactValue==3 % rfnoise
    handles.artefactmat(:,round(rand(1)*handles.dims))=rand(handles.dims,1)/2*max(abs(handles.kspace(:))).*exp(i*2*pi*rand(handles.dims,1));
elseif handles.kspaceartefactValue==4 % ADCoverflow
    maximumADC=(rand(1))*max(abs(handles.kspace(:)))/2;
    handles.artefactmat(abs(real(handles.kspace))>maximumADC)=-real(handles.kspace(abs(real(handles.kspace))>maximumADC))+maximumADC;
    handles.artefactmat(abs(imag(handles.kspace))>maximumADC)=handles.artefactmat(abs(imag(handles.kspace))>maximumADC)...
        -imag(handles.kspace(abs(imag(handles.kspace))>maximumADC))*i +i * maximumADC;
elseif handles.kspaceartefactValue==5 % digitizer quantization
    handles.artefactmat=-mod(real(handles.kspace),1/1000*max(abs(handles.kspace(:))))+...
        -i*mod(imag(handles.kspace),1/100*max(abs(handles.kspace(:))));
elseif handles.kspaceartefactValue==6 % kspace shift
    handles.artefactmat=-handles.kspace+circshift(handles.kspace,[ 0 round(rand(1)*handles.dims/8)]);%+i*rand(handles.dims);
    %         handles.artefactmat(end/2,end/2);
elseif handles.kspaceartefactValue==7 % no phantom
    handles.artefactmat=-handles.kspace+rand(handles.dims);%+i*rand(handles.dims);
elseif handles.kspaceartefactValue==8 % chemical shift
    [FatImagekspace]=Initiate_FatObject();
    handles.artefactmat=exp(-i*1/handles.WeightingConstant*2*pi*repmat(handles.FractKspace*(1:handles.dims),[handles.dims 1])...
        /(handles.dims) ).*FatImagekspace;
    
end;

guidata(findobj('Tag','KspaceImageSpaceFigure'),handles);



% --- Executes on button press in radiobutton_showphase.
function radiobutton_showphase_Callback(hObject, eventdata, handles)
% hObject    handle to radiobutton_showphase (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of radiobutton_showphase
handles=guidata(findobj('Tag','KspaceImageSpaceFigure'));
handles.showphase=get(hObject,'Value')

guidata(findobj('Tag','KspaceImageSpaceFigure'),handles);



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% my extra functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function Initiate_ImageObject()


handles=guidata(findobj('Tag','KspaceImageSpaceFigure'));

dims1=handles.dims;
%  dims1=512;
radius=0.2;
radiussmall=0.04;
handles.PhDImage1=zeros(dims1);
if handles.Image2CreateValue==1
    for m=1:dims1
        for n=1:dims1
            if ((m-dims1/2)^2+(n-dims1/2)^2)<(dims1/2*radius)^2
                handles.PhDImage1(m,n)=1;
            end
        end
    end;

    for m=1:dims1
        for n=1:dims1
            if ((m-(dims1/2-0.5*dims1/2*radius/2))^2+(n-(dims1/2+dims1/2*radius/2))^2)<(dims1/2*radiussmall)^2
                handles.PhDImage1(m,n)=1/2;
            end
        end
    end;

    for m=1:dims1
        for n=1:dims1
            if ((m-(dims1/2-0.5*dims1/2*radius/2))^2+(n-(dims1/2-dims1/2*radius/2))^2)<(dims1/2*radiussmall)^2
                handles.PhDImage1(m,n)=1/2;
            end
        end
    end;
    handles.PhDImage1(round(dims1/2+dims1/2*radius/2-dims1*radiussmall/4):round(dims1/2+dims1/2*radius/2+dims1*radiussmall/4),round(dims1/2-dims1/2*radius/2):round(dims1/2+dims1/2*radius/2))=3/4;

    handles.PhDImage1(round(dims1/2-dims1/2*radius/3):round(dims1/2+dims1/2*radius/3),round(dims1/2-dims1*radiussmall/4):round(dims1/2+dims1*radiussmall/4))=1/4;
    handles.PhDImage1=circshift(handles.PhDImage1,[round(dims1*0.025) 0]);
elseif handles.Image2CreateValue==2
    for m=1:dims1
        for n=1:dims1
            if ((m-dims1/2)^2+(n-dims1/2)^2)<(dims1/2*radius)^2
                handles.PhDImage1(m,n)=1;
            end
        end
    end;
elseif handles.Image2CreateValue==3
    handles.PhDImage1(round(dims1/2-dims1*radiussmall):round(dims1/2+dims1*radiussmall),:)=1;

elseif handles.Image2CreateValue==4
    handles.PhDImage1(:,round(dims1/2-dims1*radiussmall):round(dims1/2+dims1*radiussmall))=1;

elseif handles.Image2CreateValue==5
    for m=1:dims1
        for n=1:dims1
            if (abs(m-n))<(dims1/2*radius)
                handles.PhDImage1(m,n)=1;
            end
        end
    end;

end;
handles.kspace=(fftshift(fftn(ifftshift(handles.PhDImage1))));


DisplayImages(handles.PhDImage1,handles.kspace)
handles.PhDImage2=handles.PhDImage1;
handles.kspace2=handles.kspace;

guidata(findobj('Tag','KspaceImageSpaceFigure'),handles);

function kspaceSamplingRegion()
handles=guidata(findobj('Tag','KspaceImageSpaceFigure'));


SampleRegion=zeros(handles.dims);
samplepart=handles.FractKspace;
dims1=handles.dims;
if samplepart==1
    SampleRegion=ones(handles.dims);
else
    SampleRegion(round(dims1/2-dims1/(2*samplepart)):1:round(dims1/2+dims1/(2*samplepart)),...
        round(dims1/2-dims1/(2*samplepart)):1:round(dims1/2+dims1/(2*samplepart)))=1;
end

GridSampling=zeros(dims1);
downsample=handles.DSkspace;
middlekspace=dims1/2+1;
b2=[middlekspace:downsample:dims1];
b1=fliplr([(middlekspace-downsample):-downsample:1]);
b=cat(2,b1,b2);

SampleRegion2=zeros(handles.dims);
samplepartf=handles.FractKspace;
samplepartp=handles.partialkspace;
dims1=handles.dims;
if samplepartf==1
if samplepartp==1
    SampleRegion2=ones(handles.dims);
else
    SampleRegion2=ones(handles.dims);
    SampleRegion2(1:round((1-samplepartp)*dims1),:)=0;
end;
else
if samplepartp==1
    SampleRegion2(round(dims1/2-dims1/(2*samplepartf)):1:round(dims1/2+dims1/(2*samplepartf)),...
        round(dims1/2-dims1/(2*samplepartf)):1:round(dims1/2+dims1/(2*samplepartf)))=1;
else
    SampleRegion2(round(dims1/2-dims1/(2*samplepartf)*(samplepartp-1/2)*2):1:round(dims1/2+dims1/(2*samplepartf)),...
            round(dims1/2-dims1/(2*samplepartf)):1:round(dims1/2+dims1/(2*samplepartf)))=1;
end;
end
% figure(1)
% subplot(121)
% imagesc(SampleRegion)
% subplot(122)
% imagesc(SampleRegion2)

for m=b
    for n=b
        GridSampling(m,n)=1;
    end
end;

handles.SampledPoints=GridSampling.*SampleRegion2;
handles.SampledPoints4DFT=GridSampling.*SampleRegion;

guidata(findobj('Tag','KspaceImageSpaceFigure'),handles);

function DisplayImages(realspace,kspace)
handles=guidata(findobj('Tag','KspaceImageSpaceFigure'));
dims2=size(realspace,1);
colormap('gray')

if handles.showphase==0

axes(handles.axesImage)
imagesc(abs(realspace));
axis off
axis tight

axes(handles.axesImagePlot)
plot(abs(realspace(round(end/2)+1,:)))
axis tight
% V = AXIS;

elseif handles.showphase==1
axes(handles.axesImage)
imagesc(angle(realspace));
axis off
axis tight

axes(handles.axesImagePlot)
plot(angle(realspace(round(end/2)+1,:)))
axis tight
% V = AXIS;

end;
axes(handles.axesKspace)
% imagesc(log(abs(handles.kspace)),[0 max(log(abs(handles.kspace(:))))-1]);title('k space ');
imagesc((real(kspace)),[0 max((abs(kspace(:))))]);%title('k space ');
axis off
axis tight

axes(handles.axesKspacePlot)
% plot(real(log(abs(handles.kspace(end/2,:)))))
plot((real((kspace(round(end/2)+1,:)))))
% axis off
axis tight

function [FatImagekspace]=Initiate_FatObject()


handles=guidata(findobj('Tag','KspaceImageSpaceFigure'));

dims1=handles.dims;
%  dims1=512;
radius=0.2;
radiussmall=0.04;
FatImage=zeros(dims1);
if handles.Image2CreateValue==1
    for m=1:dims1
        for n=1:dims1
            if ((m-dims1/2)^2+(n-dims1/2)^2)>(dims1/2*radius)^2
            if ((m-dims1/2)^2+(n-dims1/2)^2)<(dims1/2*radius*1.1)^2
                FatImage(m,n)=1.5;
            end
            end
        end
    end;
    FatImage=circshift(FatImage,[round(dims1*0.025) 0]);
end;
FatImagekspace=(fftshift(fftn(ifftshift(FatImage))));


DisplayImages(FatImage,FatImagekspace)

guidata(findobj('Tag','KspaceImageSpaceFigure'),handles);

function im = homodyne_recon(ksp)
% USAGE: im=homodyne_recon(ksp)
%
% Reconstructs images out of raw epi data.
% K-space is only partially sampled (along second dimension)
% lower spatial frequencies should be first
%
% Based on the homodyne reconstruction algorithm.
%
%  Noll DC, Nishimura DG, Macovski A. Homodyne Detection in Magnetic
%  Resonance Imaging.  IEEE Trans. on Medical Imaging 1991; 10(2):154-163
%
[kxres,kyres]=size(ksp);
im = zeros(kxres);

% Zero-padding
ksp = cat(2,zeros(kxres,kxres-kyres),ksp);

%number of extra lines
extra=kyres-kxres/2;

% Estimate phase error from low resolution image
ksp_LR=zeros(size(ksp));
ksp_LR(:,kxres/2-extra:kxres/2+extra)=ksp(:,kxres/2-extra:kxres/2+extra);

ph_cor= angle(k2i_rn(ksp_LR));

% k-space weighting function
%----------------------------------------
fil=[1:2*extra]/extra;

w=[fil repmat(2,[1 kxres/2-extra])];
w=cat(2,zeros(kxres,kxres/2-extra),repmat(w,[kxres 1]));

% Image Reconstruction
%----------------------------------------
 im= real(fftshift(fft2(ifftshift((ksp.*w)))).*exp(-i*ph_cor))/kxres;
im=flipdim(im,2);

function img=k2i_rn(ksp)
%IMAGE_MATRIX goes from K-space to image-space
%image=k2i_rn(ksp)

ksp=double(ksp);

[n_rows,n_cols,n_slices,n_vols]=size(ksp);

for vol=1:n_vols
   for slice=1:n_slices
      img(:,:,slice,vol)=fftshift(fft2(ifftshift(ksp(:,:,slice,vol))));
   end;
end

img=img/sqrt(n_rows*n_cols);
  
function ksp=i2k_rn(im)
%KSPACE_MATRIX goes from image-space to k-space
%ksp=i2k_rn(fid)

im=double(im);

[n_rows,n_cols,n_slices,n_vols]=size(im);

for vol=1:n_vols
   for slice=1:n_slices
     ksp(:,:,slice,vol)=fftshift(ifft2(ifftshift(im(:,:,slice,vol))));
   end;
end;


ksp=ksp*sqrt(n_rows*n_cols);
  

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CreateFcn %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% --- Executes during object creation, after setting all properties.
function edit_DSkspace_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_DSkspace (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes during object creation, after setting all properties.
function popupmenu_kspace2show_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu_kspace2show (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes during object creation, after setting all properties.
function edit_dimensions_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_dimensions (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes during object creation, after setting all properties.
function edit_FractKspace_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_FractKspace (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes during object creation, after setting all properties.
function popupmenu_FT_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu_FT (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



% --- Executes during object creation, after setting all properties.
function popupmenu_Image_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu_Image (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end




% --- Executes during object creation, after setting all properties.
function popupmenu_kspaceweighting_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu_kspaceweighting (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end




% --- Executes during object creation, after setting all properties.
function edit_WeightingConstant_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_WeightingConstant (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes during object creation, after setting all properties.
function popupmenu_artefact_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu_artefact (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes during object creation, after setting all properties.
function edit_partialkspace_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_partialkspace (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


