clear all 
close all
clc

%ingrid 31/10/2011 // modified by CT Elides 18/11/2015

% Converte XBT para o ODV

pathname='\\Server-5_dados\4 - pirata\XBT\EDF\';
pathout='\\Server-5_dados\4 - pirata\XBT\XBT2ODV\';
files=dir([pathname '*.edf']);


disp('----------------------------------------');
disp('Convert XBT-format into ODV Spreadsheet');
disp('----------------------------------------');

% ODV header
hline1=['Cruise' char(9) 'Station' char(9) 'mon/day/yr' char(9) 'hh:mm' char(9) 'Longitude' char(9)];
hline2=['Latitude' char(9) 'Depth [m]' char(9)];
hline3=['Temperature [°C]'];

hl=[hline1 hline2 hline3];

    
  

for i=1:numel(files)
    
    name=files(i).name;
    eval(['file=' '''' pathname name '''' ';'])
    
    station= name(6:8);
    cruise='PIRAXVI';
    flag='1';
    
    fid=fopen(file,'rt');
    
    str='// This is a MK21 EXPORT DATA FILE  (EDF)';
    while isnumeric(str)~=1;
        str=fgetl(fid);
        if (strncmp(str,'Date of Launch',14))
            is=findstr(str,':  ');
            isub=is+1:length(str);
            date=sscanf(str(isub),'%s',2);
        elseif (strncmp(str,'Time of Launch',14))
            is=findstr(str,':  ');
            isub=is+1:length(str);
            time=sscanf(str(isub),'%s',2);
        elseif (strncmp(str,'Latitude',8))
            is=findstr(str,':  ');
            isub=is+1:length(str);
            dm=sscanf(str(isub),'%f',2);
            if (findstr(str(isub),'N'));
                lat=dm(1)+dm(2)/60;
            else
                lat=-(dm(1)+dm(2)/60);
            end
        elseif (strncmp(str,'Longitude',9))
            is=findstr(str,':  ');
            isub=is+1:length(str);
            dm=sscanf(str(isub),'%f',2);
            if (findstr(str(isub),'W'));
                lon=-(dm(1)+dm(2)/60);
            else
                lon=dm(1)+dm(2)/60;
            end
        end
    end;
    [text data]=mhdrload(file);
    
    if numel(size(data))==3 
    data=squeeze(data(:,:,2));
    depth=data(:,3);
    temp=data(:,4); 
    %press=data(:,1,2);
    %temp=data(:,2,2);
    elseif numel(size(data))==2
    depth=data(:,3);
    temp=data(:,4); 
    end
    
    outfile=[pathout name(1:end-4) '.txt'];
    fidout=fopen(outfile,'w');
    fprintf(fidout,'%s',hl);

    for j=1:length(depth),
        fprintf(fidout, ...
            '\n %s\t %4s\t %s\t %s\t %5d\t %9.4f\t %6.1f\t %8.4f\t %8.4f', ...
            cruise,station,date,time,lon,lat,depth(j),temp(j));
    
    end
   
end

