Skip to content

Instantly share code, notes, and snippets.

@stepan-a
Created October 1, 2013 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stepan-a/6780885 to your computer and use it in GitHub Desktop.
Save stepan-a/6780885 to your computer and use it in GitHub Desktop.
Matlab routine for converting dates in a mod file. This function has to be called as a hook before the preprocessing of the mod file.
function convert_dates_in_mod_file(name)
fidin = fopen(name,'r');
lines = textscan(fidin,'%s','Delimiter','\n'); fclose(fidin); lines = lines{1};
[a,b] = get_date_idx(lines);
lines_with_dates = find(~cellfun('isempty',a));
for l=1:length(lines_with_dates)
k = lines_with_dates(l);
for h = 1:length(a{k})
date = lines{k}(a{k}(h):b{k}(h)); nd = length(date);
if replace_date(lines{k}, a{k}(h), b{k}(h))
DATE = ['dynDate(''', date, ''')']; nD = length(DATE);
tmp = [ lines{k}(1:(a{k}(h)-1)), DATE, lines{k}((b{k}(h)+1):end)];
lines(k) = {tmp};
a{k}(h:end) = a{k}(h:end) + (nD-nd);
b{k}(h:end) = b{k}(h:end) + (nD-nd);
a{k}(h) = a{k}(h)+2; % For quotes
b{k}(h) = b{k}(h)+2; % For quotes
end
end
end
if length(lines_with_dates)
fidout = fopen([name '-subs-dates'],'w');
for i=1:length(lines)
if isempty(lines{i})
fprintf(fidout, '\n');
else
fprintf(fidout, [lines{i} '\n']);
end
end
fclose(fidout);
end
function [idx, jdx] = get_date_idx(str)
[idx, jdx] = regexp(str,'[1-9][0-9]+([YyAa]|[Qq][1-4]|[Mm]([1-9]|[1][1-2])|[Ww]([1-9]|[1-4][0-9]|[5][1-2]))');
function yes = replace_date(str, thisidx, thisjdx)
yes = 1;
% Is date in a commented line?
ic = strfind(str,'%');
if ic<thisidx
yes = 0;
return
end
ic = strfind(str,'//');
if ic<thisidx
yes = 0;
return
end
% Is date in set_time commnand?
[id, jd] = regexp(str,['set_time\([1-9][0-9]+([YyAa]|[Qq][1-4]|[Mm]([1-9]|[1][1-2])|[Ww]([1-9]|[1-4][0-9]|[5][1-2]))\)']);
if ~isempty(id) && id<thisidx && jd>thisjdx
yes = 0;
return
end
% Is date in the data command (first_obs and last_obs options)?
[id, jd] = regexp(str,'data\(.*last_obs=[1-9][0-9]+([YyAa]|[Qq][1-4]|[Mm]([1-9]|[1][1-2])|[Ww]([1-9]|[1-4][0-9]|[5][1-2])).*)');
if ~isempty(id) && id<thisidx && jd>thisjdx
yes = 0;
return
end
[id, jd] = regexp(str,'data\(.*first_obs=[1-9][0-9]+([YyAa]|[Qq][1-4]|[Mm]([1-9]|[1][1-2])|[Ww]([1-9]|[1-4][0-9]|[5][1-2])).*)');
if ~isempty(id) && id<thisidx && jd>thisjdx
yes = 0;
return
end
% Is date in a string?
[id, jd] = regexp(str,'''.*\''');
if ~isempty(id) && id<thisidx && jd>thisjdx
yes = 0;
return
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment