function [newPath]  = make_cruise_dir(varargin)
% MAKE_CRUISE_DIR - setup a new working directory for CTD calibration
% 
% USAGE:
%	 [newdir] = make_cruise_dir(parent_dir,calibration_dir)
%       	 or
%        [newdir] = make_cruise_dir(calibration_dir)
%       	 or
% 	 [newdir] = make_cruise_dir(parent_dir,calibration_dir, cruiseid)
%	The first form creates calibration_dir relative to
%	parent_dir. The second form creates calibration_dir
%	relative to the current directory (determined by pwd).
%	Use the third form if the cruiseid is to be different than the
%	calibration_dir name. 
%
% INPUT: 
%   parent_dir: Full or relative path to the parent directory of
%                   the calibration_dir
%   calibration_dir: Name of the desired directory 
%
% OUTPUT:
%   newdir: the absolute path to the new cruise directory.    
%
% DESCRIPTION:
%   This program will create a new cruise calibration working 
% directory and all the necessary subdirectories to store the CTD  data.
% Additionally, several m files are created which must be edited for each
% new calibration project.
%
% Depending on the calling syntax, the "calibration_dir" directory will
% be created in the current working directory or in the given "parent_dir"
%
% >> theDir = make_cruise_dir('stc02');
% will make a directory called stc02 in the current working directory.
%
% >> theDir = make_cruise_dir('/data/cruises/','stc02')
% will put the cruise directory in the parent directory /data/cruises.
% 
% SEE ALSO: mkdir

% CTD Calibration toolbox
%

% ERRORS: If there is an error, newdir, will be returned empty and the error
%    message can be retrieved using the lasterr syntax.
%
%

% AUTHOR:
%			Carlos Fonseca
%         UM/CIMAS
%         Mon Jul 12 13:02:10 EDT 2004
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 
% VERSION: 
%	$Revision: 1.13 $
%	$Date: 2008/03/23 23:38:16 $
%	$Id: make_cruise_dir.m,v 1.13 2008/03/23 23:38:16 duncombe Exp duncombe $
%
% CHANGELOG: 
%   08-Jul-2004, Version 1.0
%		* Initial version.
% 10-Aug-2004   DPS 
%	* create_cruise_dir.m (): Added different error checking, fixed
%	one logical bug associated with isempty(dir())
% 	16-Sep-2004, DPS 
%	* Renamed to make_cruise_dir for consistency with ctdcal toolbox
% 23-Sep-2004  DPS 
%	*  (make_cruise_dir): Eliminate cruiseid in favor of calib_dir to
%	emphasize that the cruiseid and the name of the directory do not need
%	to be the same. 
%  22-Mar-2006 MB
%   	* fixed ctdcalpath.m to allow for directory names including spaces
%  08-Aug-2007 CMDR
%   	* use cell array and loops
%   	* additional help explanation and formatting changes to
%   	(slightly) lessen opacity of the help text.
%  2007/11/29 CMDR
%	* make a default cruiseid if it is not provided.
%  2008/01/07 CMDR
%	* fixing one of my misconceptions and making code more robust 
%	just a tad
%	* when we copy rg_register_cruise.m, rename it with the cruiseid
%  2008/01/10 CMDR
%	* some fixes to stop mkdir complaining about empty directories
%	* fixing another one of my oopses
%	* create a local startup.m file that initializes future matlab 
%	sessions with the ctdcalpath and register_cruise_{cruise_id} scripts 
%  2008/01/11 CMDR
%	* Cosmetic changes to the help text
%  2008/03/18 CMDR
%	* add assignment to cruiseid in the local.m script
%  2008/03/21 CMDR
%	* adding dat_dir to the preferences
%  2008/03/23 CMDR
%	* fixing typo in cruiseid assignment
%

% BUGS AND TODOS
%	* platform independence
%	

% default output in case of error
newPath = '';

% Parse input parameters
%%%%%%%%%%%%%%%%% CMDR
% msg = nargchk(1,2,nargin);
msg = nargchk(1,3,nargin);
if ~isempty(msg)
	lasterror(struct('message',msg,'identifier','CTD:IncorrectNargin'));
	return
end

if nargin == 1
%%%%% CMDR what happens if what we are given is something of the form
% "[drive letter:][directory delimiter][path string][directory delimiter]cruiseid"
% instead of "cruiseid"? 
% split up what we are given and trust that whoever is calling us knows 
% where they want the directory to go. The remainder of the function expects
% that calibration_dir is the lowest level directory name. Therefore make it so.
	[parent_dir,calibration_dir,ext]=fileparts(varargin{1});
%%%%% CMDR put something in parent_dir to stop mkdir whining later.
	if isempty(parent_dir), parent_dir=pwd; end;
	cruiseid=lower(calibration_dir); % not sure about this, but I think 
					 % cruiseid should be lowercase

%%%%%% CMDR other options (nargin==2, nargin==3) should probably also get 
%%%%%%      a more rigorous treatment. Leave that for another time, however.
%%%%%%      At the least, cruiseid obtained from the calibration dir should 
%%%%%%      be lowercased.
elseif nargin == 2
	parent_dir = varargin{1};
	calibration_dir = varargin{2};
%%%%%%%% CMDR
	cruiseid=lower(calibration_dir);
%%%%%%%% CMDR
elseif nargin == 3
	parent_dir = varargin{1};
	calibration_dir = varargin{2};
%%%%%%%% CMDR
	cruiseid=lower(varargin{3});
%%%%%%%% CMDR
else
	lasterror(struct('message','Error parsing input arguments.',...
			'identifier','CTD:UnknownAssertion'));
	return
end


%-------------------------------------------------------------------------------									       
%- Create the top level output directory
namedir = fullfile(parent_dir,calibration_dir);
fprintf('Creating directory %s...\n',namedir);  		       
[status,msg,msgid] = mkdir(parent_dir,calibration_dir);
if ~status
%%%%%%%% CMDR comment
%%%%%%%% I don't understand the point of putting in the lasterror(struct..
%%%%%%%% business if it never gets used. The intended 
%%%%%%%% functionality is to allow errors to be caught and
%%%%%%%% appropriate action taken. If you are not going to 
%%%%%%%% take that action, then it's all just blah, blah, blah.
	lasterror(struct('message',msg,'identifier',['CTD:' msgid]));
	fprintf('Unable to create the directory %s ...\n',namedir); 
	return
end
%%%%%%%% CMDR - display a comment warning that the directory
%%%%%%%%        already exists
if size(msg,2)>0,
	disp(msg)
else
	fprintf('%s successfully created.\n',namedir);  		       
end;

% Rename the namedir since calibration_dir serves as parent_dir for the
% remainder of this function.
calibration_dir = namedir;

%-------------------------------------------------------------------------------
%- Create directory tree beneath the calibration_dir

%%% use a cell array and put in a loop --- CMDR 
dirnames={'mfiles', 'bottle', 'salts', 'oxy', 'proc_data', ...
	'raw_data', 'calibrated', 'log', 'tmp', 'figures'};

for ndir=1:length(dirnames), 
   [status, msg, msgid] = mkdir(calibration_dir, dirnames{ndir});
   if ~status,
	lasterror(struct('message',msg,'identifier',['CTD:' msgid]));
	fprintf('Unable to create the directory %s%s...\n', ...
		calibration_dir,dirnames{ndir}); 
	return;
   end;
   if size(msg,2)>0,
		% disp([calibration_dir, dirnames{ndir},':' msg]);
		disp([dirnames{ndir},' : ' msg]);
	end;
end;

%-------------------------------------------------------------------------------
%- Create and/or copy the user editable templates into the calibration_dir
% TODO: There must be a better way to do this.  It requires /demo/
%	be below ctdcal.

%%%%%% CMDR the registercruise.m file that is copied must then be edited. Can 
%%%%%%      we not make some changes right now while we are copying the file?
%%%%%%      At the least we can rename it with the cruiseid that is the 
%%%%%%      following step after editing. Rigo does it by using 
%%%%%%      rg_register_cruise.m with the variable things as arguments. Let me 
%%%%%%      try using the demos file and change that while we are copying it.
inst_dir = CTDCal('path');
% [status,msg,msgid] =	...
ffid=fopen(fullfile(inst_dir,'demos','register_cruise.m'),'r');
tfid=fopen(fullfile(calibration_dir,'mfiles',...
	['register_cruise_' cruiseid '.m']),'w');

%%% defaults for these two are not easily found. May still have to
%%% edit the script
file_name_prefix = [ upper(cruiseid)]; 
%% ndigits could be got if we knew how many files/stations there
%% are. Then we could do ndigits=num2str(fix(log10(Nstns))+1);
nDigits = '3'; 
while 1,
        rec=fgetl(ffid);
        if ~ischar(rec), break; end;

        nrec=regexprep(rec,'^cruiseid\s*=\s*''.*'';',['cruiseid=''' cruiseid ''';']);
        nrec=regexprep(nrec,'^file_name_prefix\s*=\s*''.*'';',['file_name_prefix=''' file_name_prefix ''';']);
        nrec=regexprep(nrec,'^nDigits\s*=\s*.*;',['nDigits=' nDigits ';']);
        nrec=regexprep(nrec,'^calibration_dir\s*=.*;',['calibration_dir=''' calibration_dir ''';']);

        fprintf(tfid,'%s\n', nrec);
end;

fclose(ffid);
fclose(tfid);


%%%%%% CMDR figure out what to do about the error messages later
% if ~status
% 	warning(msgid,msg)
% 	fprintf('Unable to copy register_cruise.m from %s to %s.\n', ...
% 		fullfile(inst_dir,'demos'),calibration_dir); 
% end;

% Create a new startup type file for easy path management.
[fid,msg] = fopen(fullfile(calibration_dir,'ctdcalpath.m'),'wt');
if fid < 0
  fprintf('Unable to create  %s. \n',fullfile(calibration_dir,'ctdcalpath.m'));
else
	fprintf(fid,['%%  ctdcalpath - Add ctdcal and current cruise ' ...
		'calibration directories to matlabpath.\n'],' ');
	fprintf(fid,'%% \n',' ');
	fprintf(fid,'%% \n',' ');
	fprintf(fid,' \n',' ');
	fprintf(fid,'addpath '' %s '' \n',inst_dir);
	fprintf(fid,'addpath '' %s '' \n',calibration_dir);
	fprintf(fid,'addpath '' %s '' \n',fullfile(calibration_dir,'mfiles'));
	fprintf(fid,' \n',' ');
	fclose (fid);	
end

%%%%%%%%%%%%%%%% CMDR
% create a cruise_id file with the cruise_id therein.
[fid,msg] = fopen(fullfile(calibration_dir,'cruise_id'),'wt');
fprintf(fid,'%s\n',cruiseid);
fclose(fid);
%
% create a local.m file that runs when matlab starts and invokes
% ctdcalpath and register_cruise_ scripts
disp( [	'Creating a local.m file that runs ctdcalpath.m and ' ...
	'register_cruise_' cruiseid '.m']);
disp( [ 'when you start matlab. Remember to add a line' ]);
disp( [ '        if exist(''./local.m''), local; end;' ]);
disp( [ 'to your $MATLAB/startup.m file' ] );

[fid,msg] = fopen(fullfile(calibration_dir,'local.m'),'wt');
	fprintf(fid,'%s\n', ...
		'disp(''Local startup script (local.m) running...'');');
	fprintf(fid,'%s\n','ctdcalpath');
	fprintf(fid,'%s%s\n','register_cruise_',cruiseid);
	fprintf(fid,'%s%s%s\n','cruiseid=''',cruiseid,''';');
fclose(fid);
%%%%%%%%%%%%%%%% CMDR ends
if nargout > 0,
        newPath = calibration_dir;
else
        assignin('caller', 'ans', calibration_dir);
end;
return;


