disp(' ');
disp(' extract.m   ver 1.3   June 21, 2006 ');
disp(' by Tom Irvine Email: tomirvine@aol.com ');
disp(' ')
disp(' This program extracts a segment from a time history');
disp(' ')
disp(' The time history must be in a two-column matrix format: ')
disp(' Time(sec)  & amplitude ')
disp(' ')
disp(' Select file input method ');
disp('   1=external ASCII file ');
disp('   2=file preloaded into Matlab ');
file_choice = input('');
%
clear THM;
clear TT;
clear te;
clear ts;
clear t;
clear y;
clear x;
clear segment;
%
if(file_choice==1)
    [filename, pathname] = uigetfile('*.*');
    filename = fullfile(pathname, filename);     
%    disp(' Enter the input filename ');
%    filename = input(' ','s');
    fid = fopen(filename,'r');
    THM = fscanf(fid,'%g %g',[2 inf]);
    THM=THM';
else
    THM = input(' Enter the matrix name:  ');
end
%
t=THM(:,1);
y=THM(:,2);
%
tmx=max(t);
tmi=min(t);
n = length(y);
%
out1 = sprintf('\n  %d samples \n',n);
disp(out1)
%
dt=(tmx-tmi)/(n-1);
sr=1./dt;
%
out1 = sprintf(' SR  = %g samples/sec    dt = %g sec \n',sr,dt);
out3 = sprintf(' start  = %g sec    end = %g sec            ',tmi,tmx);
disp(out1)
disp(out3)
%
disp(' ');
ts=input(' Enter segment start time  ');
te=input(' Enter segment end   time  ');
disp(' ');
%
if(ts>tmx)
    ts=tmx;
end
if(te<tmi)
    ts=tmi;
end
%
n1=fix((ts-tmi)/dt);
n2=fix((te-tmi)/dt);
%
if(n1<1)
    n1=1;
end
%
if(n2>n)
    n2=n;
end
%
if(n1>n2)
    n2=n1;
end
%
x=y(n1:n2)';
TT=t(n1:n2)';
np=length(TT);
%
out1 = sprintf(' np  = %d  \n',np);
disp(out1)
%
disp(' ')
disp(' Plot time history file? ')
choice = input(' 1=yes 2=no ');
if(choice == 1)
    figure(1);
    plot(TT,x)
    xlabel(' Time (sec)');
end
disp(' ')
disp(' Save output time history to ASCII text file? ');
choice=input(' 1=yes   2=no  ' );
disp(' ')   
if choice == 1 
        disp(' Enter output filename ');
        g_filename = input(' ','s');
%
        fid = fopen(g_filename,'w');
        for j=0:(np-1)
            fprintf(fid,'%12.5e %10.4e \n',TT(j+1),x(j+1));
        end
        fclose(fid);   
%       load(g_filename);
end    
%
%  Rename matlab matrices with descriptive names
%
segment=[TT;x]'; 
out5 = sprintf('\n The time history is renamed as "segment" \n');
disp(out5);         