% Create images for 3D replay texture maps of CODAR current vectors
%
% Get .mat files from cencalcurrents.org and create lat/lon geoVRML texture maps
% for the current vecors for each day.
%
% This script writes directly to the /hosts/tornado/ShipData/3Dreplay/
% area, so running this off the shore network requires smoe modifications.
%
% $Id:$


% Hard coding of directory paths here
rootWeb = 'http://search.mbari.org/ARCHIVE/3Dreplay/';
%%pcRootDir = '//tornado/ShipData/3Dreplay/';
%%unixRootDir = '/hosts/tornado/ShipData/3Dreplay/';            % on mammoth
unixRootDir = '/hosts/tornado/vol/vol0/ShipData/3Dreplay/';     % on squid
pcRootDir = 's:/3Dreplay/';     % on squid
rootDir = pcRootDir;



% Where 25-hour avg data are
%%baseUrl = 'http://www.cencalcurrents.org/Data/MYBG/tuv25hr';
%%baseUrl = 'http://128.114.41.17/Data/MYBG/tuv25hr';
baseUrl = 'http://cencalcurrents.org/DataRealTime/AverageTotals/MNTY';    % New as of Feb 2008
% August 2006
%%yr = 2006;
%%yrDir = ['geo' num2str(yr) '/'];
%%mo = 8;

% September 2007
%%yr = 2007;
%%yrDir = ['geo' num2str(yr) '/'];
%%mo = 9;

% June 2008
%%yr = 2008;
%%yrDir = ['geo' num2str(yr) '/'];
%%mo = 6;

% October 2008
yr = 2008;
yrDir = ['geo' num2str(yr) '/'];
mo = 10;

% Use sftp to get all the files for the month with an mget for the specific hour
dataDir = '/Volumes/Extras/RealTime/Data/AverageTotals/MNTY/';
% Get files for 1900  hour GMT which is about noon local
filesToGet = [dataDir num2str(yr) '_' num2str(mo) '/OMA25hr_MNTY*_1900.mat']
% sftp is not working.  Permissions problem on server?
%%cmd = ['echo mget ' filesToGet ' | sftp -b - HFdata@cocmpmbdata.dyndns.org']  
cmd =['! scp "HFdata@cocmpmbdata.dyndns.org:' filesToGet '" /tmp/']

disp(cmd);
eval(cmd)

load('CaliforniaCoastline.mat');
       
for da=1:30
	for hr=19:19
        moStr = sprintf('%02i', mo);
        daStr = sprintf('%02i', da);
		hrStr = sprintf('%04i', hr * 100);
        %%fileBase = ['tuv25hr_MYBG_' num2str(yr) '_' moStr '_' daStr '_' hrStr];  % 2006 names
        %%fileBase = ['oma25hr_MYBG_' num2str(yr) '_' moStr '_' daStr '_' hrStr];  % 2007 names
        fileBase = ['OMA25hr_MNTY_' num2str(yr) '_' moStr '_' daStr '_' hrStr];  % 2008 names
      
		file = [fileBase '.mat' ];
		%%url = [ baseUrl '/' num2str(yr) '_' moStr '/' file ];
		%%disp (['url = ' url]);
        %%temp_name = [tempname '.mat'];
        %%keyboard
        
        %%[f,status] = urlwrite(url,temp_name);

        status = 1;

        if status
            load(['c:/tmp/' file]);
            delete(['c:/tmp/' file]);   
            
            % Open wrl Vector file template and replace url and points strings & save to wrl
            wrlVecFile = [ fileBase '_Vec.wrl'];
            vecTmpl = fopen('codarCurrentsVectorTemplate.wrl', 'rt');
            fQWrlVecFile = [rootDir yrDir 'codar/' wrlVecFile];
            outVecWrl = fopen(fQWrlVecFile, 'wt');
            disp (['fQWrlVecFile = ' fQWrlVecFile]);

            while ~feof(vecTmpl)
                    s = fgetl(vecTmpl);
                    if ( s ~= -1 )
                        fprintf(outVecWrl, '%s\n', s);     % Print out unmolested line
                    end
            end
            
            lat = TUV.LonLat(:,2);          % From new structure change made in Feb 2008
            lon = TUV.LonLat(:,1);
            for i=1:3:length(lat)
                
                avgU = TUV.U;               % From new structure change made in Feb 2008
                avgV = TUV.V;
                if ( isnan(avgU(i)) )
                    continue;
                end
                magnitude = sqrt(avgU(i) * avgU(i) + avgV(i) * avgV(i));                         
                           
                halfMagnitude = magnitude / 2;
                onetenthMagnitude = magnitude / 10;
                tipTranslation = magnitude + onetenthMagnitude / 2;
                direction = atan2(avgU(i), avgV(i));

                vrml = [...             
                'GeoLocation {		' char(10) ...
                '  geoOrigin USE ORIGIN' char(10) ...
                '  geoCoords "' num2str(lat(i)) ' ' num2str(lon(i)) ' 0"' char(10) ...
                '  children ' char(10) ...
                '    Velocity_Arrow { ' char(10) ...
                '      translation 0 0 0 ' char(10) ...
                '      magnitude ' num2str(magnitude) char(10) ...
                '      magnitude_half 0 ' num2str(halfMagnitude) ' 0 ' char(10) ...
                '      magnitude_neghalf 0 ' num2str(-halfMagnitude) ' 0 ' char(10) ...
                '      magnitude_onetenth ' num2str(onetenthMagnitude) char(10) ...
                '      tip_translation 0 ' num2str(tipTranslation) ' 0 ' char(10) ...
                '      direction 0 -1 0 ' num2str(direction) char(10) ...
                '    }' char(10) ...
                '}'];
                fprintf(outVecWrl, '%s\n', vrml);
            end
        
            fclose(vecTmpl);
            fclose(outVecWrl);
            disp(['Wrote file ' rootDir yrDir 'codar/' wrlVecFile]);
            disp(' ');
        
%             quiver(lon, lat, avgU, avgV, 2)
% 
%             hold on
%             title(url)
%             ax = axis;
%             plot(CST(:,1),CST(:,2), 'r')
%             axis(ax);
%             set(gca, 'Position', [0 0 1 1]);
%             set(gca, 'tickdir', 'out');
% 
%             % Save image file as a png and convert to transparent gif 
%             imgFile = [ fileBase '.png'];
%             [SUCCESS,MESSAGE,MESSAGEID] = mkdir([rootDir yrDir 'codar/']);
%             tic
%             disp(['Writing file ' imgFile ' to ' rootDir yrDir 'codar/']);
%             eval(['print -dpng -r300 ' rootDir yrDir 'codar/' imgFile ';'] );
%             proctime=toc; disp(['Elapsed time to save image: ' int2str(proctime) ' seconds']);
%             
%             disp(['Done writing file ' imgFile ]);
%             hold off	      
%             eval(['!convert ' rootDir yrDir 'codar/' imgFile ' -transparent white ' rootDir yrDir 'codar/' fileBase '.gif']);
%             imgUrl = [rootWeb yrDir 'codar/' fileBase '.gif'];
%             
%             % Compute geo and texture coordinates for the image registration in 3D
%             % Step clockwise around the texture
%             geoCoords = '';
%             texCoords = '';
%             texCoordsi = '';
% 
%             % Step across top of image (0 1) to (1 1)
%             ii = 0;
%             deltaLon = (ax(2) - ax(1)) / 10;
%             deltaLat = (ax(4) - ax(3)) / 10;
%             lat = ax(4);
%             for lon=ax(1):deltaLon:ax(2)
%                 geoCoords = [geoCoords sprintf('"%.4f %.4f 0", ', lat, lon)];
%                 texCoords = [texCoords sprintf('%.1f 1, ', 1 - (ax(2) - lon) / (ax(2) - ax(1)) )];
%                 texCoordsi = [texCoordsi num2str(ii) ' '];
%                 ii = ii + 1;
%             end
%             geoCoords = [geoCoords sprintf('\n') ];
%             texCoords = [texCoords sprintf('\n') ];
%             texCoordsi = [texCoordsi sprintf('\n') ];
%             
%             % Step down the right side (1 1) to (1 0)
%             lon = ax(2);
%             for lat=ax(4):-deltaLat:ax(3)
%                 geoCoords = [geoCoords sprintf('"%.4f %.4f 0", ', lat, lon)];
%                 texCoords = [texCoords sprintf('1 %.1f, ', 1 - (ax(4) - lat) / (ax(4) - ax(3)) )];
%                 texCoordsi = [texCoordsi num2str(ii) ' '];
%                 ii = ii + 1;
%             end
%             geoCoords = [geoCoords sprintf('\n') ];
%             texCoords = [texCoords sprintf('\n') ];
%             texCoordsi = [texCoordsi sprintf('\n') ];
%             
%             % Step back on the bottom side (1 0) to (0 0)
%             lat = ax(3);
%             for lon=ax(2):-deltaLon:ax(1)
%                 geoCoords = [geoCoords sprintf('"%.4f %.4f 0", ', lat, lon)];
%                 texCoords = [texCoords sprintf('%.1f 0, ', 1 - (ax(2) - lon) / (ax(2) - ax(1)) )];
%                 texCoordsi = [texCoordsi num2str(ii) ' '];
%                 ii = ii + 1;
%             end
%             geoCoords = [geoCoords sprintf('\n') ];
%             texCoords = [texCoords sprintf('\n') ];
%             texCoordsi = [texCoordsi sprintf('\n') ];
%             
%             % Step up the left side (0 0) to (0 1)
%             lon = ax(1);
%             for lat=ax(3):deltaLat:ax(4)
%                 geoCoords = [geoCoords sprintf('"%.4f %.4f 0", ', lat, lon)];
%                 texCoords = [texCoords sprintf('0 %.1f, ', 1 - (ax(4) - lat) / (ax(4) - ax(3)) )];
%                 texCoordsi = [texCoordsi num2str(ii) ' '];
%                 ii = ii + 1;
%             end
%             
%             texCoordsi = [texCoordsi '-1'];    
%             
%             % Open wrl file template and replace url and points strings & save to wrl
%             wrlFile = [ fileBase '.wrl'];
%             tmpl = fopen('codarCurrentsTemplate.wrl', 'rt');
%             outWrl = fopen([rootDir yrDir 'codar/' wrlFile], 'wt');
%             geoCoordinateFlag = 0;
%             textureCoordinateFlag = 0;
%             while ~feof(tmpl)
%                     s = fgetl(tmpl);
% 
%                     % To replace point attributes we need to detect ther node type
%                     if ( strcmp(strtrim(s), 'coord GeoCoordinate {') )
%                         geoCoordinateFlag = 1;
%                     end
%                     if ( strcmp(strtrim(s), 'texCoord TextureCoordinate {') )
%                         textureCoordinateFlag = 1;
%                     end
% 
%                     % Write out lines
%                     if (strncmp(strtrim(s), 'url', 3))
%                         fprintf(outWrl, 'url "%s"\n', imgUrl);
%                     elseif (geoCoordinateFlag && strncmp(strtrim(s), 'point', 5))
%                         geoCoordinateFlag = 0;
%                         fprintf(outWrl, 'point [ %s ]\n', geoCoords);
%                     elseif (strncmp(strtrim(s), 'coordIndex', 10))
%                         fprintf(outWrl, 'coordIndex [ %s ]\n', texCoordsi);
%                     elseif (textureCoordinateFlag && strncmp(strtrim(s), 'point', 5))
%                         textureCoordinateFlag = 0;
%                         fprintf(outWrl, 'point [%s]\n', texCoords);
%                     elseif ( strncmp(strtrim(s), 'texCoordIndex', 13) )
%                         fprintf(outWrl, 'texCoordIndex [%s]\n', texCoordsi);
%                     else
%                         fprintf(outWrl, '%s\n', s);     % Print out unmolested line
%                     end
% 
%             end
%             fclose(tmpl);
%             fclose(outWrl);
%             disp(['Wrote file ' rootDir yrDir 'codar/' wrlFile]);
%             disp(' ');

        else 
            disp(['Data from ' url ' not read']);
        end
	end
end
		