function [E t]=load_E(date,time,instr_name,chname,start_time,stop_time)
% This code loads the E-field data for the date, minute, intrument, and
% channel designated by the user.

%USAGE:  load_E(date,time,instr_name,chname) Loads and converts to E-field for
%        instr_name.
%        
% USES:
%    BDAT_READ, FITANDREMOVE60HZ, SEGMENTED_MEDIAN2, NEW_DEDROOP, 
%
%Requires .bdat files from process_bin_file version 1.7 or above

%DEFINITIONS:
%start/stop_sec ... first second to plot (coarse data)
%If data is saved as mat file, it runs from start_sec to stop_sec
%Dedrooping uses this median.  

start_sec=0;
stop_sec=60;

%Path to data
datestr=date; %Date of storm.
instrument=instr_name; %Instrument name
hour=time(1:2);       %Set to UTC hour of data file
minute=time(3:4);   %Set to UTC minute of data file
disp(strcat(datestr,'-',hour,minute,'00'));

%Generate filename for the flash of interest based on hour, minute
%instrument and date.
hrstr=num2str(hour,'%02i');
minutestr=num2str(minute,'%02i');
timestr=strcat(hrstr,minutestr);
fname=strcat(instrument,'_',datestr(3:8),'-',timestr,'00.bdat'); 
dirname=strcat('/home/jeff/Research/',datestr,'/');
fn=strcat(dirname,fname);

%Load data. With GPS, there are five data columns
if strcmp(instrument,'lefa2')
    try
        AA=bdat_read(fn,5);
    catch ME
        AA=bdat_read(fn,4);
    end
else
  AA=bdat_read(fn,5);      
end

%With GPS we have time relative to 00:00Z in seconds.
%We want the minute of interest to start at t=0.
first_sec=str2double(hour)*3600+60*str2double(minute); 
if strcmp(instrument,'lefa2')
  t=linspace(0,60,length(AA(:,1)))';
else
  t=AA(:,1)-first_sec;      
end
         

%Extract channel to work with.
switch chname        
    case {'2'}
        ch=AA(:,2);
        chname='S';
    case {'I','3'}
        chname='S';
        ch=AA(:,3);  
    case {'M','4'}
        chname='M';
        ch=AA(:,4);
    case {'S','5'}
        chname='I';
        ch=AA(:,5);
end

%Calculate offset
ref_idx1=find(t>=start_sec,1);
ref_idx2=find(t>=stop_sec,1);
if isempty(ref_idx2)
    ref_idx2 = length(ch);
end
Vref=ch(ref_idx1:ref_idx2);
[k,~,~,med] = segmented_median2(Vref,10);
offset=med(k); 


Istart=find(t>=start_time,1);
Istop=find(t>=stop_time,1);
t = t(Istart:Istop);
%Filter out 60Hz data from lefa4 and from S-channel for all other
%instruments.
% if chname=='S' || strcmp(instrument,'lefa4')  
%   [Vfilt]=FitandRemove60Hz(ch(Istart:Istop),t); 
% else
%   Vfilt=ch(Istart:Istop);  
% end
Vfilt = ch(Istart:Istop);
%Dedroop voltage
Vdedroop=new_dedroop(Vfilt-offset,3);

%Convert from Voltage to E-field using calibrations constant
% sensitivity = calibrations_20120907(instrument,chname);
sensitivity = calibrations_20110916(instrument,chname);
E=Vdedroop*sensitivity;
