function [err]=publishtoWeb(file,allopt,varargin)
% publishtoWeb <Publish file to web.>
% Usage:: err=publishToWeb(file,options[[]])
%

% revision history:
% 05/05/20 Mark D. Shattuck <mds> publishtoWeb.m

%% valid options and defaults
err=false;
[~,base,~]=fileparts(file);
file=sprintf('%s.m',base);
str=fileread(file);
mfiles=unique(regexp(str,'(?<=<)[^\/:*"<>| ]*?(?=>)','match'));
optdef={...
  'cssfile','pubsty.css',...
  'pdir','C:\gweb\teaching\s2020\labs\MolecularDynamicsLab\',...
  'hfile',sprintf('html/%s.html',base),...
  'zfile',sprintf('%s.zip',base),...
  'mfiles',mfiles(:)',...
  'createPdf',true,...
  'preview',false,...
  'debug',1};
defs=cell2struct(optdef(2:2:end),optdef(1:2:end),2);

%% Parse options
if(nargin>2)
  allopt=[{allopt} varargin];
  allopt=cell2struct(allopt(2:2:end),allopt(1:2:end),2);
end
if(~exist('allopt','var') || isempty(allopt))
  allopt=defs;
else
  allopt=mergeStruct(defs,allopt);
end

%% Main
pubopt=rmfield(allopt,fieldnames(defs));
webopt=rmfield(allopt,fieldnames(pubopt));
debug=webopt.debug;

htmopt=mergeStruct(defPublishOpt('html'),pubopt);
pdfopt=mergeStruct(defPublishOpt('pdf'),pubopt);

ifprintf(debug>0,'Publish html...');
ifprintf(debug>1,'Filename: %s',file);
if(debug>1);disp(htmopt);end

publish(file,htmopt);
% fix bold face mathcal
hfile=sprintf('html/%s.html',base);
subRegexFile(hfile,'(?<=rlap{)\$([^\/:*"<>| ]*?)\$','$1');
ifprintf(debug>0,'Done.\n');

style=false;
if(isfield(pdfopt,'stylesheet') && ~isempty(pdfopt.stylesheet))
  pdfopt.stylesheet=[];
  style=true;
end
%% create pdf
if(allopt.createPdf)
  ifprintf(debug>0,'Publish pdf...');
  publish(file,pdfopt);
  ifprintf(debug>0,'Done.\n');
end
%%
if(~isempty(webopt.mfiles(~strcmpi(webopt.mfiles,webopt.zfile))))
  ifprintf(debug>0,'Zipping...');
  zip(webopt.zfile,webopt.mfiles(~strcmpi(webopt.mfiles,webopt.zfile)));
  ifprintf(debug>0,'Done.\n');
  mfiles=unique([webopt.zfile,webopt.mfiles]);
end

ifprintf(debug>0,'Copy to html...');
Nf=length(mfiles);
for nf=1:Nf
  [s r]=dosCopy(mfiles{nf},'html\',debug>1);
  if(s)
    ifprintf(debug>0,'%s',r);
  end
end
ifprintf(debug>0,'Done.\n');

if(exist(webopt.cssfile,'file'))
  if(style)
    subFileLines(webopt.hfile,webopt.cssfile,[15 61]);
  else
    subFileLines(webopt.hfile,webopt.cssfile,[10 56]);
  end
end

if(~allopt.preview)
  ifprintf(debug>0,'Copy to %s...',webopt.pdir);
  [s r]=dosCopy('html\*',webopt.pdir,debug>1);
  if(s)
    ifprintf(debug>0,'%s',r);
  end
  ifprintf(debug>0,'Done.\n');
end
web(webopt.hfile);



