function status=fsplit(file,mb)
%Program to split a large file to smaller files
%
%Usage
%
% fsplit(file,mb)
%
% Simple function that splits file to smaller files, each of size mb (in megabytes)
% Named filename1.spt , filename2.spt , filename3.spt, etc
% Each file containing mb megabytes of file
%
% Can be used to split large raw data files (or any file) for transfer.
%
% SEE ALSO fappend, mfappend, uimfappend
%Suresh Joel - April 10,2003
switch(nargin)
case 0
[filename pathname]=uigetfile('*.*','File to append to');
file=strcat(pathname,filename);
mb=str2num(char(inputdlg('Size of files that you want to create')));
case 1
mb=str2num(char(inputdlg('Size of files that you want to create')));
case 2
%do nothing
end
if(~exist(file))
status=-1;
error(strcat('Cant find source file -',file));
end
fidin=fopen(file,'r');
fseek(fidin,0,'eof');
pos=ftell(fidin);
totmb=pos/(1024*1024);
if totmb<mb, %If file size is less than mb, no need to write new file
disp(strcat('File size is less than :',num2str(mb),'Mb'));
disp('No spt file written');
return;
end;
fseek(fidin,0,'bof');
mbcount=0;
i=1;
hw=waitbar(0,'Please wait till file is split ...');
prei='';
while(mbcount<totmb),
n=0;
%Sequential file naming
nprei=length(num2str(round(totmb/mb)))-length(num2str(round(i)));
for ii=1:nprei, prei(1,ii)='0'; end;
fidout=fopen(strcat(file,prei,num2str(i),'.spt'),'w');
prei='';
%Write mb bytes into new file
if mb>1, rmb=1; else rmb=mb; end;
while(n<mb),
c=fread(fidin,1024*1024*rmb,'uchar');
if isempty(c), break; end; %if c is empty (reached end of file) break out of loop
fwrite(fidout,c,'uchar');
n=n+1;
if(mb-n)>=1,rmb=1; else rmb=mb-n;end;
end;
fclose(fidout);
mbcount=mbcount+mb;
i=i+1;
waitbar(mbcount/totmb,hw);
end;
fclose(fidin);
status=0;
close(hw);