function varargout = Install_IMPACT(varargin)
% Install_IMPACT
%   Install the IMPACT tool

%   Project: IMPACT
%   Title of Code: wecModel2Body
%   Relevant additional documentation:
%   Developer: Carlos Gonzalez
%   External Dependencies: NA
%
%   Disclaimer
%   CAUTION: It is strongly recommended that changes to this code
%   should be avoided without first consulting with authors.

gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @Install_IMPACT_OpeningFcn, ...
                   'gui_OutputFcn',  @Install_IMPACT_OutputFcn, ...
                   'gui_LayoutFcn',  [], ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
   gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before Install_IMPACT is made visible.
function Install_IMPACT_OpeningFcn(hObject, eventdata, handles, varargin)
axes(handles.axes1);
image(imread('Start.png'));
set(handles.axes1,'Xtick',[],'Ytick',[],'XTickLabel',[],'YTickLabel',[],'xcolor',[1 1 1],'ycolor',[1 1 1]);
% load mls icon
warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame');
jframe=get(gcf,'javaframe');
logo = which('icon.png');
jIcon=javax.swing.ImageIcon(logo);
jframe.setFigureIcon(jIcon);
warning('on','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame');
movegui( gcf, 'center' );% move the gui to the center

set(handles.text_message,'ForegroundColor',[0.769 0.773 0.776]);
set(handles.pushbutton_next,'enable','on');



% --- Outputs from this function are returned to the command line.
function varargout = Install_IMPACT_OutputFcn(hObject, eventdata, handles)
varargout{1} = [];


% --- Executes on button press in next.
function pushbutton_next_Callback(hObject, eventdata, handles)
close(handles.fig_installation);
directory_name = fullfile(matlabroot,'toolbox');
full_name = fullfile(directory_name,'IMPACT');
folderPath = 'source';

terms = LicenceTerms();
%%
if terms==0
    return
else
% start copying files
if directory_name ~= 0    
    if exist(fullfile(directory_name,'IMPACT'),'file')
        [name vers] = readVers(fullfile(directory_name,'IMPACT','version.txt'));
        button = questdlg(sprintf('The %s toolbox %s is already installed in your computer. Would you like to overwrite it?',name,vers));
        if strcmp(button,'Cancel') || strcmp(button,'No')
            return
        else
            warning('off','MATLAB:RMDIR:RemovedFromPath');
            [SUCCESS,MESSAGE,MESSAGEID] = rmdir(fullfile(directory_name,'IMPACT'),'s');
            warning('on','MATLAB:RMDIR:RemovedFromPath');
        end
    end
        
    % create a folder for the MLS toolbox
    [SUCCESS,MESSAGE,MESSAGEID] = mkdir(fullfile(directory_name,'IMPACT'));
    
    failed = 0;
    failed2 = 0;
    h = waitbar(0,'Please wait while the toolbox is being installed');
    warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame');
    jframe=get(h,'javaframe');
    logo = which('icon.png');
    jIcon=javax.swing.ImageIcon(logo);
    jframe.setFigureIcon(jIcon);
    warning('on','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame');
    
    
    cd_ori = cd;
    
    errorList = {};
    warningList = {};
    
    folders2copy = {'code','functions','temp','demo','simulink'};
    errorCodes = {'ERROR 001','ERROR 002','ERROR 003','ERROR 004','ERROR 005'};
    
    files2copy = {'icon.png','version.txt','Contents.m'};
    warningCodes = {'WARNING 001','WARNING 002','WARNING 003'};
       
    no_wait_counts = numel(folders2copy) + numel(files2copy) + 1; % +1 because of help
    wait_count = 0;
    
    % Copy folders
    noFolders = numel(folders2copy);
    status = zeros(size(folders2copy));
    for i = 1:noFolders
        folderi = folders2copy{i};
        folder_path = fullfile(full_name,folderi);
        [status(i) ,MESSAGE,MESSAGEID] = copyfile(fullfile(folderPath,folderi),folder_path,'f');
        if (status(i) == 1)
            addpath(folder_path); 
        else
            try
                dosRes = dos(['xcopy "',fullfile(folderPath,folderi),'" "',folder_path,'" /e/q/r/y/c']);
                if dosRes==0
                    status(i) = 1;
                    addpath(folder_path); 
                end
            catch
            errorList = [errorList,errorCodes{i}];
            failed = 1;
            end
        end
        wait_count = wait_count + 1;
        if exist('h','var')
            waitbar(wait_count/no_wait_counts,h);
        end
    end
    
    % Copy files
    noFiles = numel(files2copy);
    status = zeros(size(files2copy));
    for i = 1:noFiles
        filei = files2copy{i};
        [status(i) ,MESSAGE,MESSAGEID]= copyfile(fullfile(folderPath,filei),full_name,'f');
        if (status(i) == 0)
            warningList = [warningList,warningCodes{i}];
        end
        wait_count = wait_count + 1;
        if exist('h','var')
            waitbar(wait_count/no_wait_counts,h);
        end
    end        
    
    % copy 'Help'
    gp = genpath(fullfile(cd_ori,folderPath,'help'));
    colon = [0,find(gp==';')];
    folders_help=[];
    for i=1:length(colon)-1
        folders_help{i} = gp(colon(i)+1:colon(i+1)-1);
    end
    
    status_help = 1;
    for i=1:length(folders_help)
        folder_help=folders_help{i};
        folder2copy = fullfile(full_name,'help',folder_help(length(fullfile(cd_ori,folderPath,'help',filesep))+1:end));
        [SUCCESS,MESSAGE,MESSAGEID] = mkdir(folder2copy);
        dirH= dir(folders_help{i});
        for j=1:length(dirH)
            if dirH(j).isdir==0
                [status_help1 msg5] = copyfile(fullfile(folders_help{i},dirH(j).name), folder2copy,'f');
                status_help = status_help*status_help1;
            end
        end
    end
    
    if status_help~=1 
        warningList = [warningList, 'WARNING 004, the help could not be installed'];
    end
    
    if exist('h','var')
        wait_count = wait_count + 1;
        waitbar(wait_count/no_wait_counts,h);
        pause(0.5);
        if exist('h','var')
            close(h);
        end
    end
    
    [versionNo,versionLet] = getMATLABVer() ;
    if versionNo>2012 || (versionNo==2012 && versionLet>'a')
        try
            appinfoC = matlab.apputil.install(fullfile(pwd,'Apps','IMPACT - Control Design'));
            appinfoD = matlab.apputil.install(fullfile(pwd,'Apps','IMPACT - Data Analysis'));
        catch
            failed = 1;
            errorList = [errorList,'ERROR 010'];
        end
    end
    
    if ~failed
        cd_old=cd;
        cd(fullfile(matlabroot,'toolbox','local'));
        pf = fopen('startup.m','r');
        startupFile={};
        if pf~=-1
            while 1
                line = fgets(pf);
                if ~ischar(line)
                    break
                end
                if isempty(strfind(line,'\IMPACT'))
                    startupFile = [startupFile,line];
                end
            end
        end
        
        pf = fopen('startup.m','w');
        if pf==-1
            failed2=1;
            cd(cd_old);
        else
            for i=1:numel(startupFile)
                fprintf(pf,'%s',startupFile{i});
            end
            
            foldersPath = ['',folders2copy];
            if status_help==1
                foldersPath = [foldersPath,'help'];
            end
            
            for i=1:numel(foldersPath)
                fprintf(pf,'addpath(''%s'')\n',fullfile(full_name,foldersPath{i}));
            end
            fclose(pf);
        end
        cd(cd_old);
    end
end


if ~isempty(errorList)
    finalInstall(2,warningList,errorList);
elseif ~isempty(warningList)
    finalInstall(1,warningList,errorList);
else
    finalInstall(0,warningList,errorList);
end
end


function pushbutton_cancel_Callback(hObject, eventdata, handles)
close(handles.fig_installation);


function [name vers] = readVers(file)
pf = fopen(file,'r');
if pf == -1;
    name = [];
    vers = [];
else
    line = fgetl(pf);
    nameC = regexp(line,'(\w*\S)*','match');
    name = nameC{1};
    versC = regexp(line,'([\d\.])*','match');  
    vers = versC{1};
    fclose(pf);
end

function [versionNo,versionLet] = getMATLABVer()
VerInfo = ver;
ind = 0;
for i=1:numel(VerInfo)
    if strcmp(VerInfo(i).Name,'MATLAB')
        ind = i;
        break;
    end
end
matVer = regexp(VerInfo(ind).Release, '\d+', 'match');
versionNo = str2double(matVer{1});
versionLet = regexp(VerInfo(ind).Release, '[a-z]', 'match');

    
