function varargout = flipimages(varargin)
spm_defaults
global defaults;
warn=1;
pack
k=1;
checkdims = 0;
track=0;
overwrite=0;
while k<=nargin
    if nargin<1 
        break
    elseif isstruct(varargin{k})
        V=varargin{k};
    elseif isstr(varargin{k})& strcmp(varargin{k},'str')
        P=varargin{k+1};
        k=k+1;
    elseif isstr(varargin{k}) & strcmp(varargin{k},'rotate')
        rotate=1;
    elseif isstr(varargin{k}) & strcmp(varargin{k},'track')
        vars.varargin=varargin;
        track=1;
    elseif isstr(varargin{k}) & strcmp(varargin{k},'checkdims')
        checkdims=1;
    elseif isstr(varargin{k}) & strcmp(varargin{k},'FixOrigin')
        FixOrigin=1;
    elseif isstr(varargin{k}) & strcmp(varargin{k},'scaleNpad')
        scaleNpad=1;
    elseif isstr(varargin{k}) & strcmp(varargin{k},'silent')
        warn=0;
    elseif isstr(varargin{k}) & strcmp(varargin{k},'flip')
        flip=1;
        if isnumeric(varargin{k+1})
            k=k+1;
            dim=varargin{k};
        end    
    elseif isstr(varargin{k}) & strcmp(varargin{k},'interp')
        if isnumeric(varargin{k+1})
            k=k+1;
            interp=varargin{k};
        end  
    elseif isstr(varargin{k}) & strcmp(varargin{k},'perm')
        if isnumeric(varargin{k+1})
            k=k+1;
            perm=varargin{k};
        else
        perm=1;
        end
    elseif isstr(varargin{k}) & strcmp(varargin{k},'overwrite')
        overwrite=1;	
    end
    k=k+1;
end
if ~(exist('flip','var') | exist('rotate','var') | exist('perm','var'))
    flip=1;
    disp('no operation specified ...')
    disp('default: flipping in 2nd dimension')
end
if ~exist('scaleNpad','var')
    scaleNpad=0;
end
if ~exist('FixOrigin','var')
    FixOrigin=0;
end

clear varargin
clear k
pack
f='';
if  ~exist('dim','var')
    dim =2;
end
if ~exist('V','var')
    if dim
        dims={'st','nd','rd'};
        if ~exist('P','var')
            P = spm_get(Inf,'IMAGE',['Select images to flip (',num2str(dim),dims{dim},'-dimension)']);
        end
    else
        if ~exist('P','var')
            P = spm_get(Inf,'IMAGE',['Select images ']);
        end
    end
    %V =spm_vol(P(ind,:));
    clear dims
end
if ~exist('P','var') & exist('V','var')
    P='';
    for i1=1:length(V)
        P = strvcat(P,V(i1).fname);
    end
end
if scaleNpad
    
    for ind=1:size(P,1)
        [pth,nam,ext] =fileparts(P(ind,:));
        if ~overwrite
            oname = fullfile(pth,['scaled_' ,nam]);
        else
            oname = fullfile(pth,nam);
        end
        %syscall = ['scaleNpad ',V(ind).fname , ' -S1 -o',oname]
        
        syscall = ['scaleNpad -S1 ',P(ind,:),' -o',oname]
        system(syscall);
    end
end
V=spm_vol(P);
if ~exist('interp','var')
    interp=0;
end
reset_flip=0;
for ind=1:length(V)
    if track
        [pth,nam,ext]=fileparts(V(ind).fname);
        trackfname=fullfile(pth,[nam '_flipped.mat']);
        if exist(trackfname,'file')
            disp(['found ', trackfname])
            if nargout>=1
                out{ind}=V(ind).fname;
            end
            if nargout>=2
                out2{ind} = trackfname;
            end
            continue
        end
    end
    if checkdims
        vox = abs(GetVoxSize(V(ind)));
        imdims = V(ind).dim(1:3);
        avw_orient = V(ind).private.hdr.hist.orient;
        fv = vox(:)-vox(1);
        fd = imdims(:)-imdims(1);
        for fvl = 1:3
            if abs(fv(fvl))<1e-3
                fv(fvl)=0;
            else
                fv(fvl)=1;
            end
        end
        for fvl = 1:3
            if abs(fd(fvl))<1e-3
                fd(fvl)=0
            else
                fd(fvl)=1
            end
        end
        if ~(avw_orient==0 & fv(1:3)==[0;0;1] & fd==[0;0;1])% orient is set as transverse
            disp('flipping .. dimensions may be wrong')
            if ~exist('flip','var') | ~flip
                flip=1;
                reset_flip=-1;
                dim=2;
            end
        else
            disp('working')
        end
        
    end
    f='';
    NumSlices = V(ind).dim(3);
    % Print progress information in command window
    str   = ['reading ',V(ind).fname];%sprintf('Slice %3d/%-3d ',SliceNumber,NumSlices);
    fprintf('\r%-100s: %90s',str,' ')       
    %    disp(['reading ',V(ind).fname])
    %    data = squeeze(get_voxel_values3d(V(ind),NumSlices,interp));
    data = squeeze(spm_read_vols(V(ind)));
    
    if FixOrigin
        %% check to see that origin is set correctly
        tmp      = spm_imatrix(V(ind).mat);
        if any(tmp(1:3) ~= -tmp(7:9).*V(ind).dim(1:3)./2)
            disp(['setting origin on ',V(ind).fname])
            % disp(['tmp = ',num2str(tmp)])
            tmp(1:3) = -tmp(7:9).*V(ind).dim(1:3)./2;
            V(ind).mat   = spm_matrix(tmp);
            %             Yf       = data;%
            if ~overwrite
                [pth,nam,ext] = fileparts(V(ind).fname);
                V(ind).fname = fullfile(pth,['Fixed_' ,nam,ext]);
                %f=[f 'Fixed_'];
            end
            %             V(ind)       = spm_write_vol(V(ind),Yf);
            %             [pth,nam,ext] = fileparts(V(ind).fname);
            %             oldhdr = fullfile(pth,[nam,'.hdr']);
            disp('... done')
        else
            disp(['origin = ',num2str(tmp(1:3))])
        end
    end
    
    
    if exist('perm','var') & perm==1
        str   = ['permuting ',V(ind).fname];
        %      disp(['permuting ',V(ind).fname])
        data = permute(data,[1 3 2]);
        fprintf('\r%-100s: %90s',str,' ');   
        %	dim1=V(ind).dim
        a= [V(ind).dim(1), V(ind).dim(3), V(ind).dim(2) ,V(ind).dim(4)];
        V(ind).dim = a;%permute(V(ind).dim,[2 3 1 4])
        %	dim2=V(ind).dim
        newmat=V(ind).mat;
        oldmat=newmat;
        newmat(2,2)=oldmat(3,3);
        newmat(3,3)=oldmat(2,2);	
        newmat(2,4)=oldmat(3,4);
        newmat(3,4)=oldmat(2,4);
        V(ind).mat=newmat;
        clear oldmat
        clear newmat
        
        %	V(ind).pinfo = permute(V(ind).pinfo,[2 3 1]);
        f=[f 'p'];
    end
    if exist('perm','var') & perm==2
        str   = ['permuting ',V(ind).fname];
        %      disp(['permuting ',V(ind).fname])
        data = permute(data,[3 2 1]);
        fprintf('\r%-100s: %90s',str,' ');   
        %	dim1=V(ind).dim
        a= [V(ind).dim(3), V(ind).dim(2), V(ind).dim(1) ,V(ind).dim(4)];
        V(ind).dim = a;%permute(V(ind).dim,[2 3 1 4])
        %	dim2=V(ind).dim
        newmat=V(ind).mat;
        oldmat=newmat;
        newmat(1,1)=oldmat(3,3);
        newmat(3,3)=oldmat(1,1);	
        newmat(1,4)=oldmat(3,4);
        newmat(3,4)=oldmat(1,4);
        V(ind).mat=newmat;
        clear oldmat
        clear newmat
        
        %	V(ind).pinfo = permute(V(ind).pinfo,[2 3 1]);
        f=[f 'p'];
    end
    if exist('flip','var') & flip & dim
        disp(['flipping ',V(ind).fname])
        str   = ['flipping ',V(ind).fname];
        fprintf('\r%-100s: %90s',str,' ');
        for j=1:length(dim)
            data = flipdim(data,dim(j));
        end
        f=[f 'f'];
    end
    if exist('rotate','var') & rotate
        NumSlices=size(data,dim);
        % disp(['rotating ',V(ind).fname])
        str   = ['rotating ',V(ind).fname];
        fprintf('\r%-100s: %90s',str,' ');   
        f=[f 'r'];
        for j=1:NumSlices
            disp(['slice ',num2str(j),'/',num2str(NumSlices)])
            if dim==1
                data(j,:,:)=reshape(rot90(squeeze(data(j,:,:))),[1,V(ind).dim(2),V(ind).dim(3)]);
            elseif dim==2
                data(:,j,:)=reshape(rot90(squeeze(data(:,j,:))),[V(ind).dim(1),1,V(ind).dim(3)]);
            elseif dim==3
                data(:,:,j)=reshape(rot90(squeeze(data(:,:,j))),[V(ind).dim(1),V(ind).dim(2),1]);
            end   
        end
    end
    
    [pth,nam,ext]=fileparts(V(ind).fname);
    if ~exist('overwrite','var') 
        V(ind).fname=fullfile(pth,[f nam ext]);
    elseif exist('overwrite','var') & ~overwrite
        V(ind).fname=fullfile(pth,[f nam ext]);
    else
        if warn,
            fprintf(sprintf('\n'))%-#
            disp(['Warning: about to overwrite',V(ind).fname]),
        end
    end
    
    
    %  disp(['writing ',V(ind).fname])
    str   = ['writing ',V(ind).fname];
    fprintf('\r%-100s: %90s',str,' ');   
    spm_write_vol(V(ind),data);
    if scaleNpad 
        [pth,nam,ext] = fileparts(V(ind).fname);
        if ~overwrite
            oname = fullfile(pth,['scaled_' ,nam]);
        else
            oname = fullfile(pth,nam);
        end
        syscall = ['scaleNpad ',V(ind).fname , ' -S1 -o',oname];
        [s,w]=system(syscall);
        if s
            disp(w)
        else
            disp(syscall)
        end
    end  
    if nargout>=1
        out{ind}=V(ind).fname;
    end
    
    [pth,nam,ext]=fileparts(V(ind).fname);
    clear data
    pack
    
    if track
        vars.fname=fullfile(pth,nam,ext);
        trackfname=fullfile(pth,[nam '_flipped.mat']);
        save(trackfname,'vars')
        if nargout>=1
            out{ind}=V(ind).fname;
        end
        if nargout>=2
            out2{ind} = trackfname;
        end
    end
    if exist('flip','var')
        flip = flip+reset_flip;
    end
    %Print 'done' followed by new line in command window
    
    fprintf('%s%90s',repmat(sprintf('\b'),1,90),'... done',sprintf('\n'))%-#
    
end
if nargout>=1
    if exist('out','var')
        varargout{1}=out;
    else
        varargout{1}={};
    end
end

if nargout>=2 
    if exist('out2','var')
        varargout{2}=out2;
    else
        varargout{2}={};
    end
end

%disp(['f = ',f])
%spm_check_registration;
return;