function lcplotw(startTime,readChans,segLength,dataFiles)
%LCPLOTW Plot L-Cheapo Ocean Bottom Seismometer data (uses AnyPlot)
% Usage: type lcplotw
%        OR lcplotw(startTime,readChans,segLength,dataFiles);
%           where:  ('[]' indicates default value)
%             startTime (ap_time object) is the start time to suggest in
%                   the dialog box [the latest start time for all files]
%             readChans (vector) is a list of the channels to read by
%                 default [all channels]
%             segLength is the default read length (minutes) [15]
%             dataFiles is a cell array of ap_dataFiles to read (allows
%                 you to pre-specify the clock drift, for example)
%
%             If any of the first three are unspecified or set to 0, the default values
%             are used
%
%            If dataFiles isn't specified, the program will ask how many sites to read
%            then open dialog boxes to choose each file
%
%  Afterwards, a dialog box opens allowing you to modify the start
%  time, read length, clock drift and which channels to read

% W Crawford 3/2005

% Handle input arguments (default values always 0)
if ~exist('startTime'), startTime=0; end
if ~exist('readChans'), readChans=0; end
if ~exist('segLength'), segLength=0; end
if ~exist('dataFiles'), dataFiles=0; end

%nSites = input('Enter number of sites to plot: ');

% INPUT FILENAMES AND DISPLAY THEIR DATE RANGES
%disp('Index      Filename   First Write           Last Write')
[fileName, filePath]=uigetfile('*','Select ALL Files','MultiSelect','on');
if isa(fileName,'cell'),
	nSites = length(fileName);
else,
	nSites=1; fileName = {fileName};;
end

for i=1:nSites,
	%[siteInfo(i).fileName, siteInfo(i).filePath]=uigetfile('*',sprintf('Select File %d',i));
	siteInfo(i).fileName = fileName{i};
	siteInfo(i).filePath = filePath;
	cd(siteInfo(i).filePath);
	dfile{i} = ap_datafile(siteInfo(i).fileName,'LCPO');
	dfile{i} = set(dfile{i},'pathname',siteInfo(i).filePath);
	tdata = ap_readLCPO(dfile{i},0,1);	% Just to get file info
	fileInfo = get(tdata,'Custom');

	siteInfo(i).firstDir=fileInfo{1};
	siteInfo(i).lastDir=fileInfo{2};
	siteInfo(i).bits=fileInfo{3};
	siteInfo(i).sampFreq=get(tdata,'sampFreq');
	dfile{i} = set(dfile{i},'numChans',get(tdata,'numChans'));
	siteInfo(i).numChans=get(tdata,'numChans');
%	disp(sprintf('%4d   %12s   %s  %s',...
%			i,get(dfile{i},'fileName'),char(siteFirstTime{i}),char(siteLastTime{i})));
end

[startTime,lengthSecs,outInfo] = chooseParameters(siteInfo,startTime,segLength,readChans);

for i = 1:nSites,
%	outInfo(i)
	dfile{i} = set(dfile{i},'instnum',outInfo(i).instNum);
	dfile{i} = set(dfile{i},'readchans',outInfo(i).readChans);
%	disp(sprintf('Reading %s',get(dfile{i},'filename')));
%	newdata = ap_readLCPO(dfile{i},startTime,lengthSecs);
%	if i==1,
%		tdata = newdata;
		%	else,
%		tdata = merge(tdata,newdata); % should handle empty tdata
		%	end
end
%tdata = set(tdata,'plotStart',startTime);
%apview(tdata);
apview(dfile,startTime,lengthSecs);


%----------------------------------------------------------------------
% Open a dialog box to show the instrument times and to choose a plot time
% and length.  Modified from lcplot.m by Kerry Key
function [startTime,lengthSecs,info] = chooseParameters(site,startTime,segLength,readChans)
%
% Input
%	site().fileName, 	   string
%	site().firstDir,	ap_time object
%	site().lastDir,	    ap_time object
%	site().bits,        
%	site().numChans,        
%	site().sampFreq,    scalar
% Outut
%	info().readChans,    vector
%	info().instNum,		 ap_time object
%	info().clockDrift,	    ap_time object
%----------------------------------------------------------------------

nSites = length(site);


maxNumChans = max([site.numChans]);
% FILL UP GLOBALS FOR THE DIALOG BOX
global SHOWCHANS INSTNUM DRIFT YY MO DD HH MM SS PLTLEN LENUNITS

if readChans==0,
	SHOWCHANS = ones(nSites,maxNumChans);
else,
	SHOWCHANS = ones(nSites,1)*readChans(:)';
end
if segLength==0,
	PLTLEN=15;
	LENUNITS = 2; % 2=minutes
else
	PLTLEN=segLength;
	LENUNITS = 2; % 2=seconds
end
if ~isa(startTime,'ap_time'),	% Set startTime to the latest startTime of all sites
	startTime = site(1).firstDir;
	for i = 2:nSites, if site(i).firstDir - startTime > 0, startTime=site(i).firstDir; end, end
end

INSTNUM = 1:nSites;
%DRIFT = zeros(nSites,1);
YY = startTime.year;
MO = startTime.month;
DD = startTime.day;
HH = startTime.hour;
MM = startTime.minute;
SS = startTime.second;

%%%% MAKE THE DIALOG BOX
dy = 22;		% Height of info lines
wirdWidth = 545+30*maxNumChans;
%%% FLAG FOR COMPUTER TYPE (SPECIAL CASE IF A MAC)    
    comp = computer;
    if strcmp(comp,'MAC2'); % it's a mac, adjust plot stuff
        FS = 11; % SMALLER FONT SIZE
	    h0 = figure('Units','points', ...
	    'Color',[0.8 0.8 0.8], ...
	    'Position',[248.64 100.64 wirdWidth 167.28+(nSites-1)*21.32], ...
        'Tag','pltdialogfig');
    else  % PC, OR UNIX
        FS = 12;	% LARGER FONT SIZE
        h0 = figure('Units','points', ...
	    'Color',[0.8 0.8 0.8], ...
	    'Position',[248.64 100.64 wirdWidth 167.28+(nSites-1)*21.32], ...
        'Tag','pltdialogfig',...
	    'ToolBar','none');  % TOOLBAR NONE OPTION SET 
    end
%%%%%%%%%%%% Lower Control Panel Stuff, always same postion:
l1 = mkFrame([ 10   7   wirdWidth-20    58],       0.7,h0,'Framelower');

% START TIME INPUT
l1 = mkStatTxtB([ 50 40 100   20],'Start Time',16, 0.7,h0);
l1 = mkETInt(   [ 10 12 50    20],'YY',        FS, 1  ,h0);
l1 = mkStatTxt( [ 60 12 10    20],'/',         FS, 0.7,h0);
l1 = mkETInt(   [ 70 12 30    20],'MO',        FS, 1  ,h0);
l1 = mkStatTxt( [100 12 10    20],'/',         FS, 0.7,h0);
l1 = mkETInt(   [110 12 30    20],'DD',        FS, 1  ,h0);
l1 = mkETInt(   [150 12 30    20],'HH',  FS, 1  ,h0);
l1 = mkStatTxt( [180 12 10    20],':',         FS, 0.7,h0);
l1 = mkETInt(   [190 12 30    20],'MM',  FS, 1  ,h0);
l1 = mkStatTxt( [220 12 10    20],':',         FS, 0.7,h0);
l1 = mkETInt(   [230 12 30    20],'SS',  FS, 1  ,h0);
% Plot Length INPUT
l1 = mkStatTxtB([320 40  70    20],'Length', 16, 0.7,h0);
l1 = mkETInt(   [300 12  50    20],'PLTLEN',FS, 1  ,h0);
l1 = mkPopUp(   [360 12  90    26],'LENUNITS','Seconds|Minutes|Hours|Days',14,0.7,h0);
% GO Button
l1 = mkButton(  [wirdWidth-(70+30) 13.44  70  46.08],'PLOT','close(gcf);',18, 0.7,h0);

%%%%%%%%%%%%% Upper stuff, has NSITES varying positions:
%u1 = mkFrame(  [ 10 70    423    53+(NSITES-1)*21.32], 0.7, h0, 'FrameUpper');

u1 = mkStatTxtB([220 120+dy*(nSites-1) 200  40],'LCPLOTW',      30, 0.8,h0);
y = 95+(nSites-1)*dy; fs=13;
u1 = mkStatTxtB([  5 y    20  19],'#',         fs, 0.8,h0);
u1 = mkStatTxtB([ 25 y    60  19],'File',      fs, 0.8,h0);
u1 = mkStatTxtB([ 80 y    42  19],'Bits',      fs, 0.8,h0);
u1 = mkStatTxtB([115 y    52  19],'Rate',      fs, 0.8,h0);
u1 = mkStatTxtB([160 y    90  19],'First Dir', fs, 0.8,h0);
u1 = mkStatTxtB([295 y    90  19],'Last Dir',  fs, 0.8,h0);
%u1 = mkStatTxtB([440 y    90  19],'Drift',     fs, 0.8,h0);
u1 = mkStatTxtB([440 y+fs+3 90  19],'Channels',  fs, 0.8,h0);
for j=1:maxNumChans,
	u1 = mkStatTxt([445+(j-1)*25 y 20  20],num2str(j),  fs, 0.8,h0);
end

%%% loop over files:
for i=1:nSites,
   %%% DEFINE TEXT FOR FIRST AND LAST DIRECTORY TIMES:
   FIRST   = char(site(i).firstDir);
   %L       = FILES(i).DIR_COUNT;
   LAST    = char(site(i).lastDir);
   %%%
   y = 80+(nSites-i)*dy;
   u1 = mkETInt(   [  5 y  24 16],sprintf('INSTNUM(%d)',i),  11, 1  ,h0);
   u1 = mkStatTxtR([ 25 y  62 16],site(i).fileName,          11, 0.8,h0);
   u1 = mkStatTxtR([ 80 y  24 16],num2str(site(i).bits),     11, 0.8,h0);
   u1 = mkStatTxtR([115 y  40 16],num2str(site(i).sampFreq), 11, 0.8,h0);
   u1 = mkStatTxtR([160 y 130 16],FIRST,                     11, 0.8,h0);
   u1 = mkStatTxtR([295 y 130 16],LAST,                      11, 0.8,h0);
%   u1 = mkETExp(   [445 y  80 16],sprintf('DRIFT(%d)',i),    11, 1  ,h0);
	for j=1:site(i).numChans,
		u1 = mkChkBx([445+(j-1)*25 y 20 20], sprintf('SHOWCHANS(%d,%d)',i,j)  ,h0);
	end
end

waitfor(h0);

% TRANSFER FROM GLOBALS TO RETURN VARIABLES
%	info().readchans,    string
%	info().instNum,		 ap_time object
%	info().clockDrift,	    ap_time object
%----------------------------------------------------------------------
startTime = ap_time(YY,MO,DD,HH,MM,SS)
if LENUNITS==1,lengthSecs = PLTLEN;
elseif LENUNITS==2, lengthSecs = PLTLEN*60;
elseif LENUNITS==3, lengthSecs = PLTLEN*3600;
elseif LENUNITS==4, lengthSecs = PLTLEN*86400;
end

for i = 1:nSites,
	info(i).instNum = INSTNUM(i);
%	info(i).clockDrift = DRIFT(i);
	info(i).readChans = [];
	for j=1:site(i).numChans,
		if SHOWCHANS(i,j)==1,
			info(i).readChans=[info(i).readChans j];
		end
	end
	%SHOWCHANS = ones(nSites,max(inst.numChans));
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = mkStatTxt(pos,str,fSize,grayLvl,par)
	h = uicontrol('Parent',par, ...
	'Units','points', ...
	'BackgroundColor',[1 1 1]*grayLvl, ...
	'FontSize',fSize, ...
	'HorizontalAlignment','left', ...
	'ListboxTop',0, ...
	'Position',pos, ...
	'String',str, ...
	'Style','text', ...
	'Tag','StaticText2'); 
	
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = mkStatTxtB(pos,str,fSize,grayLvl,par)
	h = uicontrol('Parent',par, ...
	'Units','points', ...
	'BackgroundColor',[1 1 1]*grayLvl, ...
	'FontSize',fSize, ...
	'FontWeight','bold', ...
	'HorizontalAlignment','left', ...
	'ListboxTop',0, ...
	'Position',pos, ...
	'String',str, ...
	'Style','text', ...
	'Tag','StaticText2'); 
	
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = mkStatTxtR(pos,str,fSize,grayLvl,par)
	h = uicontrol('Parent',par, ...
	'Units','points', ...
	'BackgroundColor',[1 1 1]*grayLvl, ...
	'FontSize',fSize, ...
	'HorizontalAlignment','left', ...
	'ForegroundColor','red', ...
	'ListboxTop',0, ...
	'Position',pos, ...
	'String',str, ...
	'Style','text', ...
	'Tag','StaticText2'); 
	
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%function h = mkEditTxt(str,callBk,pos,fSize,grayLvl,prnt,tag)
%h = uicontrol('Parent',prnt, ...
%	'Units','points', ...
%	'BackgroundColor',[1 1 1]*grayLvl, ...
%	'ListboxTop',0, ...
%	'Position',pos, ...
%    'FontSize',fSize, ...
%	'Callback', callBk,...
%    'Style','edit', ...
%	'Tag',tag);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = mkETInt(pos,vblStr,fSize,grayLvl,prnt)

endVbl = strfind(vblStr,'(');
if ~isempty(endVbl),
	vblBase = vblStr(1: (endVbl(1)-1));
else, vblBase = vblStr;
end
eval(sprintf('global %s',vblBase));
%eval(vblStr);
eval(['Str = sprintf(''%d'',' vblStr ');']);
callBk = sprintf('global %s, %s = str2num(get(gcbo,''String''));',vblBase,vblStr);
h = uicontrol('Parent',prnt, ...
	'Units','points', ...
	'BackgroundColor',[1 1 1]*grayLvl, ...
	'ListboxTop',0, ...
	'Position',pos, ...
    'FontSize',fSize, ...
	'Callback', callBk,...
	'String', Str,...
    'Style','edit', ...
	'Tag','ETint');
return;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = mkETExp(pos,vblStr,fSize,grayLvl,prnt)

endVbl = strfind(vblStr,'(');
if ~isempty(endVbl),
	vblBase = vblStr(1: (endVbl(1)-1));
else, vblBase = vblStr;
end
eval(sprintf('global %s',vblBase));

eval(['Str = sprintf(''%e'',' vblStr ');']);
callBk = sprintf('global %s, %s = str2num(get(gcbo,''Value''))',vblBase,vblStr);
h = uicontrol('Parent',prnt, ...
	'Units','points', ...
	'BackgroundColor',[1 1 1]*grayLvl, ...
	'ListboxTop',0, ...
	'Position',pos, ...
    'FontSize',fSize, ...
	'Callback', callBk,...
	'String', Str,...
    'Style','edit', ...
	'Tag','ETint');
return;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = mkPopUp(pos,vblName,menuStr,fSize,grayLvl,prnt)
eval(sprintf('global %s',vblName));
eval(sprintf('val = %s;',vblName));
%sprintf('val = %s;',vblName);
%vblName, val
callBk = sprintf('global %s; %s = get(gcbo,''Value'');',vblName,vblName);
h = uicontrol('Parent',prnt, ...
	'Units','points', ...
	'BackgroundColor',[1 1 1]*grayLvl, ...
	'FontSize',fSize, ...
	'FontWeight','bold', ...
	'ListboxTop',0, ...
	'Min',1, ...
	'Position',pos, ...
	'Callback',callBk,...
	'String',menuStr,...
    'Style','popupmenu', ...
	'Tag','myPopupMenu', ...
	'Value',val);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = mkChkBx(pos, vblStr, prnt)

endVbl = strfind(vblStr,'(');
if ~isempty(endVbl),
	vblBase = vblStr(1: (endVbl(1)-1));
else, vblBase = vblStr;
end
eval(sprintf('global %s',vblBase));
eval(sprintf('val = %s;',vblStr));
callBk = sprintf('global %s, %s = get(gcbo,''Value'')==get(gcbo,''Max'');',vblBase,vblStr);
h = uicontrol('Parent',prnt, ...
	'Units','points', ...
	'Position',pos, ...
	'Value',val, ...
	'String','Hi',...
	 'Callback',callBk,...
	 'Style','checkbox', ...
	'Tag','myChkBox');
%	'ListboxTop',0, ...
%	'FontSize',pos(4), ...

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = mkButton(pos,str,callBk,fSize,grayLvl,prnt)
h = uicontrol('Parent',prnt, ...
	'Units','points', ...
	'BackgroundColor',[1 1 1]*grayLvl, ...
	'FontSize',fSize, ...
	'FontWeight','bold', ...
	'ListboxTop',0, ...
	'Position',pos, ...
	'String',str, ...
	'Callback',callBk,...
	'Tag','myButton');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = mkFrame(pos,grayLvl,par,tag)
h = uicontrol('Parent',par, ...
	'Units','points', ...
	'BackgroundColor',[1 1 1]*grayLvl,  ...
	'ListboxTop',0, ...
	'Position',pos, ...
	'Style','frame', ...
	'Tag',tag);
