function [AM, tout, DataTime, ErrorFlag] = getabcd(varargin)
%getabcd - Returns the horizontal orbit
%  [AM, tout, DataTime]  = getabcd(DeviceList, t, FreshDataFlag, TimeOutPeriod)
%         or
%  [AM, tout, DataTime]  = getabcd(DataStructure, t, FreshDataFlag, TimeOutPeriod)
%
%  INPUTS
%  1. DeviceList or DataStructure  (see help getpv)
%  2. t  (see help getpv)
%  3. FreshDataFlag  (see help getpv)
%  4. TimeOutPeriod  (see help getpv)
%  5. 'Struct' will return a data structure
%     'Numeric' will return a vector output {default}
%  6. 'Archive' will save a BPM data structure to \<DataRoot>\BPM\
%      with filename BPMy<Date><Time>.mat
%
%  OUTPUTS
%  1. AM = orbit vector or data structure
%  2. tout  (see help getpv)
%  3. DataTime
%  4. ErrorFlag  (see help getpv)
%
%  NOTE
%  1. 'Struct', 'Numeric', and 'Archive' are not case sensitive
%  2. All inputs are optional
%
%  EXAMPLE
%  1. <a href="matlab: plot(getspos(gethbpmfamily),getabcd); xlabel('BPM Position [meters]'); ylabel('Horizontal Orbit');">plot(getabcd);</a>
%
%  See also gety, getbpm, getam, getpv
%
%  Written by Greg Portmann


%  Family = gethbpmfamily;
Family = 'BPMx'; % faster


% Get input flags
StructOutputFlag = 0;
ArchiveFlag = 0;
for i = length(varargin):-1:1
    if isstr(varargin{i})
        if strcmpi(varargin{i},'struct')
            StructOutputFlag = 1;
            %varargin(i) = [];
        elseif strcmpi(varargin{i},'numeric')
            StructOutputFlag = 0;
            %varargin(i) = [];
        elseif strcmpi(varargin{i},'archive')
            ArchiveFlag = 1;
            varargin(i) = [];
        end
    end
end

devName = family2tangodev('BPMx', []);
SwitchingFlag = 1;
Kx = 11.4; % mm
Kz = 11.4; % mm

for k=1:length(devName)

    attributes = {'XPosSA', 'ZPosSA', 'VaSA', 'VbSA', 'VcSA', 'VdSA', 'SumSA', 'QuadSA'};
    rep = tango_read_attributes2(devName{k}, attributes);
    for ik =1:8,
        data.(rep(ik).name) = rep(ik).value;
    end

    % get data from TANGO static database
    [libera_RF_offset,block_offset,BBA_offset,survey_offset]=get_bpm_offsets(devName{k});

    % Direct Build data
        Sumbuild = sum([data.(rep(3).name); data.(rep(4).name); data.(rep(5).name); data.(rep(6).name)]);

        Xbuild = Kx*(data.(rep(3).name)-data.(rep(4).name)-data.(rep(5).name)+data.(rep(6).name))./Sumbuild - ...
            (block_offset(1)+survey_offset(1)+BBA_offset(1));
        Zbuild = Kz*(data.(rep(3).name)+data.(rep(4).name)-data.(rep(5).name)-data.(rep(6).name))./Sumbuild - ...
            (block_offset(2)+survey_offset(2)+BBA_offset(2));

        if ~SwitchingFlag
            Xbuild = Xbuild - libera_RF_offset(1);
            Zbuild = Zbuild - libera_RF_offset(2);
        end
     AM(k) = data;
end
