function []=prep_ztf_images_db(varargin)
% SHORT DESCRIPTION HERE
% Package: VO.ZTF
% Description: 
% Input  : - 
%          * Arbitrary number of pairs of arguments: ...,keyword,value,...
%            where keyword are one of the followings:
%            'Class'  - The class of images to retrieve:
%                       Default is {'sci','raw','cal'}.
%            'YMD'    - If given, then retrieve only data in specific date
%                       [Year Month Day]. Default is empty.
%            'User'   - Archive username.
%                       or a cell containing a full path to a file with
%                       user/pass.
%            'Pass'   - Archive password.
%            'DirStore'- Directory in which to store DB.
%            'RetrieveNew' - Only attempt to retrieve new files.
%                       Default is true.
%            'CatFile'- Catalog file name format.
%                       Default is 'ZTF%sImages'.
% Output : - 
% License: GNU general public license version 3
%     By : Eran O. Ofek                    Nov 2017
%    URL : http://weizmann.ac.il/home/eofek/matlab/
% Example: 
% Reliable: 
%--------------------------------------------------------------------------


DefV.Class                = {'sci','raw','cal'};  % 'ref'
DefV.YMD                  = [];
DefV.DirStore             = {'~/matlab/data/+cats/+ZTF/'};
DefV.RetrieveNew          = true;
DefV.CatFile              = 'ZTF%sImages';
DefV.User                 = '~/matlab/passwords/ztf_archive_pass';
DefV.Pass                 = [];
InPar = InArg.populate_keyval(DefV,varargin,mfilename);

%Options = weboptions('Username',InPar.User,'Password',InPar.Pass)
%BaseURL = 'https://ztfweb.ipac.caltech.edu/ztf/archive/';

if (iscell(InPar.User))
    [InPar.User,InPar.Pass]=Util.code.read_user_pass_file(InPar.User{1});
end
    

PWD = pwd;
% cd to DB directory
cd(InPar.DirStore);



Nclass = numel(InPar.Class);
for Iclass=1:1:Nclass
    DataClass = InPar.Class{Iclass};
    
    CatFileName = sprintf(InPar.CatFile,DataClass);
    CatFile = sprintf('cats.ZTF.%s;',CatFileName);
    try
        eval(sprintf('D=cats.ZTF.%s;',CatFileName));
    catch
        % Data doesn't exist
        D = [];
    end
    
    LastJDInDB   = celestial.time.julday([max([Data.Day]), max([Data.Month]), max([Data.Year])]);
    CurrentDate  = clock;
    CurrentJD    = celestial.time.julday(CurrentDate([3 2 1]));
    
    VecJD        = (LastJDInDB:1:CurrentJD).';
    Njd          = numel(VecJD);
    for Ijd=1:1:Njd
        try
            ZTF = VO.ZTF.prep_link_ztf_images('YMD',[2017 10 28],'Class',{DataClass},'User',InPar.User,'Pass',InPar.Pass);
            D   = [D; ZTF.(DataClass)(:)];
        catch
            % skip
        end
       
    end
    
    % save data
    eval(sprintf('%s=D;',CatFileName));
    save(sprintf('%s.mat',CatFileName),CatFileName,'-v7.3');

end


% cd back
cd(PWD);
