%% Data Arrays

function nc_loaddap_text (deployment)
urlbase = 'http://dods.mbari.org/cgi-bin/nph-nc/data/ssdsdata/deployments/m0/';
basedir = '/ssdsdata/deployments/m0/';
addpath('/usr/local/bin');
%addpath('/usr/local/bin');

ncfiles = dir([basedir deployment '/' 'm0*.nc']);

%loops through the multiple netcdf files for each instrument
for f = 2:length(ncfiles),

    clear p[wcruise data inst_data header out_data depth time_esecsx
    
    filename = ncfiles(f).name;

    %using the name of the instrument (inst) and the url base, load_data
    %retrieves the variable names and data contained in the netcdf files.
    %Data is obtained using loaddap and returned in a structure array
    %(inst_data).
    [variable_names, inst_data] = load_data (filename, urlbase, deployment);

    max_num_depths = 1;
    depths = 0;
    
    %loops through each field name for each netcdf file
    for v = 1:length(variable_names),

        attribute = char(variable_names{v});

        %checks that the attribute returns a structure, this indicates
        %that it is a multiple dimension variable and contains data
        attribute_struct = inst_data.(attribute);
        if ~isstruct(attribute_struct),
            continue,
        end

        %puts the different fields within the attribute structure into
        %a cell array.  The first contains data, the second contains
        %time markers
        attribute_names = fieldnames(attribute_struct);

        %reads data into a cell/structure array for each attribute.
        %concatenates the data from each attribute across netcdf files.
        %Checks the size to determine if there are multiple data points
        %for each time, this indicates multiple depths.

        time_esecsx.(attribute) = inst_data.(attribute).(char(attribute_names(2)));
        temp = squeeze(inst_data.(attribute).(char(attribute_names(1))));
        lon.(attribute) = inst_data.(attribute).(char(attribute_names(5)));
        lat.(attribute) = inst_data.(attribute).(char(attribute_names(4)));

        [m, n] = size(temp);
                
        if n == length(inst_data.(attribute).(char(attribute_names(2)))),
            temp = temp';
        end
        out_data.(attribute) = temp;
        
        depth.(attribute) = inst_data.(attribute).(char(attribute_names(3)));
        if length(depth.(attribute))>max_num_depths,
            max_num_depths = length(depth.(attribute));
            depths = depth.(attribute);
        end

    end

     
    data_names = fieldnames(time_esecsx);
    
    max_time = 0;
    count = 0;
    for d = 1:length(data_names),
        [g, h, i] = size(time_esecsx.(char(data_names(d))));
        if g> max_time,
            max_time = g;
            index = d;
            count = count+1;
        end
        if g~=max_time,
            count=count+1;
        end
    end

    if count > 1,
        master_time = time_esecsx.(char(data_names(index)));

        for d = 1:length(data_names),
            for tt = 1:length(master_time),
                temp3 = find((time_esecsx.(char(data_names(d)))>(master_time(tt)-10))& ...
                    (time_esecsx.(char(data_names(d)))<(master_time(tt)+10))); % matches times to longest time +/- 10 seconds
                if isempty (temp3),
                    matched_time_esecs.(char(data_names(d)))(tt,1) = master_time(tt);
                    matched_out_data.(char(data_names(d)))(tt,1) = NaN;
                else
                    matched_time_esecs.(char(data_names(d)))(tt,1) = master_time(tt);
                    matched_out_data.(char(data_names(d)))(tt,1) = out_data.(char(data_names(d)))(temp3);
                end
                clear temp3
            end
        end
        clear time_esecsx out_data
        
        time_esecsx = matched_time_esecs;
        out_data = matched_out_data;
    end
            
    time_edays = time_esecsx.(char(data_names{1}))/(3600*24);
    epoch_start = datenum('1-jan-1970');
    time = epoch_start + time_edays;
    mdy = datestr(time, 'mm/dd/yyyy');
    hhmm = datestr(time, 'HH:MM');

    %sets "Bot.Depth" to 0, purely for file structure benefit
    %depth(1:length(time),1) = 0;
    days_2003 = time - (datenum('1-Jan-2003'));

    for row = 1:length(time_esecsx.(char(data_names{1}))),
        for dep = 1:length(depths),

            cruise{(row-1)*length(depths)+dep,1} = 'M0';
            cruise{(row-1)*length(depths)+dep,2} = num2str((row-1)*length(depths)+dep);
            cruise{(row-1)*length(depths)+dep,3} = '*';
            cruise{(row-1)*length(depths)+dep,4} = mdy(row,1:10);
            cruise{(row-1)*length(depths)+dep,5} = hhmm(row,1:5);


            data((row-1)*length(depths)+dep,1) = lon.(char(data_names{1}));
            data((row-1)*length(depths)+dep,2) = lat.(char(data_names{1}));
            data((row-1)*length(depths)+dep,3) = 0;
            data((row-1)*length(depths)+dep,4) = days_2003(row);
            data((row-1)*length(depths)+dep,5) = time_esecsx.(char(data_names{1}))(row);
            data((row-1)*length(depths)+dep,6) = depths(dep);

            for d = 1:length(data_names),
                data((row-1)*length(depths)+dep,6+d) = out_data.(char(data_names(d)))(row,dep);
               disp(row)
               disp(dep)
               disp(d)
            end
        end
    end
    header = {'Cruise', 'Station', 'Type', 'mon/day/yr', 'hh:mm',...
        'Longitude [degrees_east]', 'Latitude [degrees_north]', 'Bot.Depth [m]',...
        'DaysSince2003[d]','TimeEpochSecs[s]', 'SensorDepth[m]'};

    for d = 1:length(data_names),
        header{end+1} = char(data_names{d});
    end


    fid = fopen([basedir deployment '/ascii_output/' filename(1:end-3) '.txt'], 'wt');

    %fprintf(fid, '%s\n', ['//' int2str(datalines)]);
    for h = 1:length(header),
        if h~= length(header),
            fprintf(fid, '%s\t', char(header{h}));
        else
            fprintf(fid, '%s\n', char(header{h}));
        end
    end
    fclose(fid);
    tblwrite_smb(data, header, cruise, [basedir deployment '/ascii_output/' filename(1:end-3) '.txt'],'\t',4,1)
end

end

%% Load Variables
function [variable_names, instrument] = load_data(inst, urlbase, deployment)

variable_names = fieldnames(loaddap([urlbase deployment '/' inst]));
instrument = loaddap([urlbase deployment '/' inst]);

end
