function [STATE] = loadstate(varargin)
%loadstate()
%loadstate(DIRECTORY)
%loadstate(ITERATION)
%loadstate(DIRECTORY,ITERATION)
%
%Reads MITgcm parameter input files and output to create a STATE structure
%If ITERATION is not specified, the last model state is read by default.
%If DIRECTORY is not specified the current working directory is used.
%
%e.g.
% >> STATE=loadstate;
% >> STATE2=loadstate('/scratch/john/run2/');
% >> STATE3=loadstate(3000);
% >> STATE4=loadstate('/scratch/john/run2/',2460);
%
% Elements  (u,v,w,t,s,eta) correspond to snap-shots.
% Elements  (U,V,W,T,S,ETA) correspond to time averages.
%
%Written by adcroft@mit.edu, 2002
%$Header:

Dir='./';
iter=inf;
if nargin~=0
 for k = 1:nargin;
  if isstr(varargin{k})
   Dir=[varargin{k} '/'];
  else
   iter=varargin{k};
  end
 end
end

Its=[];
[STATE.t,its]=rdmds([Dir 'T'],iter); if isempty(Its); Its=its; end
[STATE.s,its]=rdmds([Dir 'S'],iter); if isempty(Its); Its=its; end
[STATE.u,its]=rdmds([Dir 'U'],iter); if isempty(Its); Its=its; end
[STATE.v,its]=rdmds([Dir 'V'],iter); if isempty(Its); Its=its; end
[STATE.w,its]=rdmds([Dir 'W'],iter); if isempty(Its); Its=its; end
[STATE.eta,its]=rdmds([Dir 'Eta'],iter); if isempty(Its); Its=its; end
[STATE.T,its]=rdmds([Dir 'Ttave'],iter); if isempty(Its); Its=its; end
[STATE.S,its]=rdmds([Dir 'Stave'],iter); if isempty(Its); Its=its; end
[STATE.U,its]=rdmds([Dir 'uVeltave'],iter); if isempty(Its); Its=its; end
[STATE.V,its]=rdmds([Dir 'vVeltave'],iter); if isempty(Its); Its=its; end
[STATE.W,its]=rdmds([Dir 'wVeltave'],iter); if isempty(Its); Its=its; end
[STATE.ETA,its]=rdmds([Dir 'ETAtave'],iter); if isempty(Its); Its=its; end
STATE.iters=Its;

datafile=[Dir 'data'];
dtClock = grepparameter(datafile,'deltatclock');
dtTracer = grepparameter(datafile,'deltattracer');
dtMom = grepparameter(datafile,'deltatmom');
dt = grepparameter(datafile,'deltat');
dt=[dt dtClock dtTracer dtMom]; dt=dt(1);
 
STATE.dt=dt;
STATE.time_secs=its*dt;
STATE.time_days=its*dt/86400;
STATE.time_years=its*dt/86400/360;
