function H = tsamain(dirname,filename,maxlag,arord,predhorizon)

% This function replicates most of the functionality that tsa.pl provides. 
% It is mainly targeted at Windows users who don't have access to a Unix 
% implementation of Matlab. 

% It plots four graphs :
%		1. The time series plot itself
%		2. The Autocorrelation function (ACF)
%		3. An predhorizon-step ahead prediction of the data using an AR(arord) model
%		4. The PSD for the data

% This function also outputs the four graphs in .EPS format. The EPS file is
% placed in the same directory as the one where the data resides in, and
% is named "your-original-filename-here".figs.eps.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This should be one of only two sections you really need to modify to use this
% code. My data happened to reside in a set of directories located under 
% the base path '/my documents/extracted/' (which Matlab interprets as 
% c:\my documents\extracted). Just change the following "datafile" 
% variable to relect your dir structures. BTW, the function strcat works
% the same way as its C/C++ version, except that it can take multiple 
% string arguments. See postscript file generation at the bottom of the
% file to see the other section which you might need to modify.

base_dir = '/my documents/extracted/';
datafile = strcat(base_dir, dirname, filename);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

x=load(datafile);

length(x)

acfall=xcov(x,maxlag,'coeff');
acf = acfall(maxlag+1:2*maxlag+1);
n = length(x); 
bound95 = 1.96./sqrt(n:-1:n-maxlag);
lags = 0:maxlag;
sigp = 100*sum(abs(acf(2:maxlag))>bound95(2:maxlag)')/maxlag
subplot(2,2,2);
plot(lags,acf,lags,bound95,'r--',lags,-bound95,'r--');
xlabel('Lag');
ylabel('Acf');
t = sprintf('ACF of %s (%g %% sig at p=0.05)',filename,sigp);
title(t);
subplot(2,2,1);
plot(x);
xlabel('time');
ylabel('signal');
t = sprintf('time series of %s', filename);
title(t);
f = abs(fft(x));
f = f(1:n/2);
subplot(2,2,4);
loglog(f);
xlabel('log(freq)');
ylabel('log(abs(fft))');
t = sprintf('PSD of %s', filename);
title(t);
th=ar(x(1:n/2),arord);
yp=predict(x(n/2+1:n),th,predhorizon);
subplot(2,2,3);
plot(1:n,x,n/2+1+arord:n,yp(arord+1:length(yp)),'r--');
xlabel('time');
ylabel('signal/prediction');
t = sprintf('%d step ahead preds of AR(%d) on %s', predhorizon,arord,filename);      
title(t);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Generating the postscript file
% If you want the EPS file to be placed somewhere else, you might also
% need to change any necessary directory paths here.

epsname = strcat(base_dir, dirname, '.', filename, '.figs.eps');
print('-depsc', epsname)