function rp_flip_images_4D(input_image,folder_out,prefix)
% 160130 JI Gong-Jun JIA Xi-Ze
% 160225 support img/hdr JIA Xi-Ze
% 200717 support 4D image LI Zi-qi



if isdir(input_image)
    folder_in=input_image;
    subj_list=dir_NameList(folder_in);
    [~,filename,~]=fileparts(input_image);
    folder_out=[folder_out filesep prefix '_' filename];
    if ~isdir(folder_out)
       mkdir(folder_out);
    end
    for i = 1 : length (subj_list)
        [fliped_data,ot]=rp_flip_data([folder_in filesep subj_list{i}]);
        rp_write_filp_data(folder_out,subj_list{i},fliped_data,ot,prefix);
    end
else
    
    [fliped_data,ot]=rp_flip_data(input_image);
    [pathstr, name, ext] = fileparts(input_image);
    rp_write_filp_data(folder_out,name,fliped_data,ot,prefix);
end
end

function [fliped_data,ot]=rp_flip_data(data_pth) % flip data
%     FileList=dir_NameList(data_pth);
%     for i=1:length(FileList)
%         crt_pth=[data_pth filesep FileList{i}];
        [ot.data, ot.voxel,~, ot.header] = rp_to4d(data_pth);
        if length(size(ot.data))==4    %support 4D image flip, li ziqi 200717
            fliped_data(ot.header.dim(1):-1:1,:,:,:) = ot.data (1:1:ot.header.dim(1),:,:,:);
        elseif length(size(ot.data))==3
            fliped_data(ot.header.dim(1):-1:1,:,:) = ot.data (1:1:ot.header.dim(1),:,:);
        else
            error('Img dimension is wrong');
        end
%     end
end

function rp_write_filp_data(folder_out,subj_list,fliped_data,ot,prefix) % write in flip data file
     [pathstr,name,ext]=fileparts(subj_list);
     if length(size(fliped_data))==4
         fprintf('flip %s OK\n',subj_list);
         if strcmp(ext,'')
             rp_Write4DNIfTI(fliped_data,ot.header,[folder_out filesep prefix '_' subj_list '.nii']);
         else
             rp_Write4DNIfTI(fliped_data,ot.header,[folder_out filesep prefix '_' subj_list ext]);
         end
     elseif length(size(fliped_data))==3
         [pathstr,name,ext]=fileparts(subj_list); %support hdr,img, jia xize 160225
         if ~strcmp(ext,'.hdr')
              fprintf('flip %s OK\n',subj_list);
              rp_writefile(fliped_data,[folder_out filesep prefix '_' subj_list],ot.header.dim,ot.voxel,ot.header,'single') ;
         end
     else
         error('Input is not 3D image or 4D image ! Please input correct images');
     end
end