function [tmp_subdir]=CreateTMPdir(tmp_dir,mfile);
%function [tmp_subdir]=CreateTMPdir(tmp_dir,mfile);
%
% Creates a unique sub(working) directory in the tmp_dir 
%  name of subdirectory will consist of:
%   "mfile"-"date"-"time"-"unique number" 
% Example CreateTMPdir-2000814-120000-1 

% ---------------------------------
% Copyright (c) 2003 Serge Dumoulin
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License version 2
% as published by the Free Software Foundation.
% ---------------------------------

if nargin < 1,
   tmp_dir=tempdir;
end;
if nargin < 2,
   mfile=mfilename;
end;

if(exist(tmp_dir,'dir')~=7),
   disp(sprintf('%s does not exist -> changing to %s',tmp_dir,tempdir));   
   tmp_dir=tempdir;
   if(exist(tmp_dir,'dir')~=7),
      disp(sprintf('%s does not exist - exit program',tmp_dir));
      return;
   end;
end;

% create sub(working) directory:
t=fix(clock);
mydir=sprintf('%s-%d%d%d-%d%d%d',mfile,t(1),t(2),t(3),t(4),t(5),t(6));
tmp_subdir=[tmp_dir filesep mydir];

status=0;
un=1;
while status~=1,
   status=mkdir(tmp_dir,[mydir '-' sprintf('%d',un)]);
   un=un+1;
end;
tmp_subdir=[tmp_subdir '-' sprintf('%d',un-1) filesep];
