function [status,code] = setupCS100A( port )
%
%    Use previously established serial connection to initialize 
%    Minolta CS-100A Photometer/Colorimeter in STANDARD setup mode
%
%    Assumes C2K serial connection with following format:
%       4800 baud; 7 data bits; 2 stop bits; even parity
%       { e.g., config_serial(port,4800,2,2,7) }
%
%    Usage:
%       [status,code] = setupCS100A( port )
%    Inputs:
%       port      - COM port number (usually = 1)
%    Returns:
%       status    - 0=OK, 1=CS100A error, -1=COM1 error
%       code      - 0=OK, -1=COM1 error (same as status)
%                   (also see Minolta CS-100A manual)

clearserialbytes(port);        %clear serial buffers
msg=['MDS,00',char(13),char(10)]; %construct CS-100A initialization command
nmsg=abs(msg); %convert text to numeric array
sendserialbytes(port, nmsg); %send message via COM1:

%retrieve <LF> terminated feedback from CS-100A
line_buffer = []; bytes = []; matches = [];
found = 0;
loop = 1;
ftime=time+4000;  %set 4 sec timeout
while( loop > 0 )
    readserialbytes(port);  %drain low-level serial input data buffer
    [bytes,times,n]=getserialbytes(port); %fetch buffered characters (if any)
    %update line array if any data found
    if( n > 0 )
        line_buffer = [line_buffer; bytes]; %concatenate new chars to old
        %search for <LF> terminator
        matches = find(bytes == 10);
        if(~isempty(matches))
            found = 1; %signify successfully terminated input line
            loop = 0;  %exit if <LF> received
        end
    end
    %test for time-out condition
    if( time > ftime )
        loop = 0;  %exit if timed-out
    end
end

%set default return value (COM1 error condition)
status=-1; code=-1;

%exit if problem with CS100A return string length
n=length(line_buffer);
if( n < 6 )
    return
end

%extract parameters from CS100A return string
%
%extract status:
if(line_buffer(1) == 79 )
    status = 0;  %status = OK
end
if(line_buffer(1) == 69 )
    status = 1;  %status = ERROR
end
%extract error code:
temp = char( line_buffer(3:4) );
code = str2num(temp');
