clear
close all

while 1
%request (prompt) for file name (infinite loop till successful or exit)
%input returns the entered text, the 's' says to return it without
%evaluating the input as an expression.
infile=input("input file name (<CR> (or whitespace) to quit): ",'s');
%by experiment bunch of spaces, tabs also quit
    if isempty(infile)
        return %this returns from function or script to the command window
    else
%If fopen cannot open the file, it returns -1. Go back and try again
        fid=fopen(infile);
        if fid == -1
            display('error - file not found - try again')
            continue %this skips the rest of the stuff in the loop
        else
%here - have found a file, good to go
            break %stop looping, continue with code after loop
        end
    end
end

%notice that the smart matlab editor draws lines to show the loops
%connecting the start and end statements of the loop, it does not "help"
%with the ifs. using the same command (end) for both causes much gnashing
%of teeth.

%notice the indeting - this is optional - it is not required as in python.
%it makes it easier to read, but when you add a loop or if you have to
%indent everything inside it.

%reads whole file in at once and puts it in a cell array named inbuf
%note - in addition to the format specifier (that says the input is  a
%character string) you also need to tell textscan what the delimiter
%between elements of the cell array is - in this case it is the newline
%(the invisible character at the end of each line that tells the OS to go
%to the next line. These codes can be problematic as different systems do
%them differently - some separate the new line and carriage return
%functions - so a new line goes to the next line, but where it is, not the
%beginning, and a carriage return, goes to the beginning of the line YOU
%ARE ON, or does both new line and return.
inbuf = textscan(fid, '%s', 'Delimiter', '\n');

%show info about what read in (basically get number lines_
inbuf
%interpret output of "inbuf" 
%  1×1 cell array
%    {8×1 cell}

%display sample line (first) so we can figure out what it is
inbuf{1}{1}
%or "disp(inbuf{1}{1}"
%what is the difference between a=z{1}{1} and b=z{1}(1)? - {} vs ().
%how find out?

%make xy plot, read in columns to plot
xcol=input("input column for x: "); %here no 's', so processes into double
%should check input - should make subroutine since have to do 2x
ycol=input("input column for y: ");

%get number lines in input file and preallocate memory
nlines=length(inbuf{1});
x = zeros(1, nlines);
y = x;

%now get x and y values out of cell array, forced to loop
for cnt=1:nlines
    tmp=strsplit(inbuf{1}{cnt});
    x(cnt)=str2double(tmp{xcol}); %str2double(tmp(xcol)) also works
    y(cnt)=str2double(tmp{ycol});
end

plot(x,y,'o','MarkerFaceColor',[1 0 0],'MarkerSize',24,'LineWidth',5)
