
(********************************************************************)
(*                                                                  *)
(*  cat.sd7       Concatenate and print files                       *)
(*  Copyright (C) 2015  Brian Callahan                              *)
(*                                                                  *)
(*  This program is free software; you can redistribute it and/or   *)
(*  modify it under the terms of the GNU General Public License as  *)
(*  published by the Free Software Foundation; either version 2 of  *)
(*  the License, or (at your option) any later version.             *)
(*                                                                  *)
(*  This program is distributed in the hope that it will be useful, *)
(*  but WITHOUT ANY WARRANTY; without even the implied warranty of  *)
(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the   *)
(*  GNU General Public License for more details.                    *)
(*                                                                  *)
(*  You should have received a copy of the GNU General Public       *)
(*  License along with this program; if not, write to the           *)
(*  Free Software Foundation, Inc., 51 Franklin Street,             *)
(*  Fifth Floor, Boston, MA  02110-1301, USA.                       *)
(*                                                                  *)
(********************************************************************)


$ include "seed7_05.s7i";
  include "stdio.s7i";

(**
 *  Open the file and print its contents.  Handle "-" as stdin.
 *)
const proc: cat (in string: fileName) is func
  local
    var file: inFile is STD_NULL;
    var char: ch is ' ';
  begin
    if fileName = "-" then
      inFile := IN;
    else
      inFile := open(fileName, "r");
    end if;
    if inFile <> STD_NULL then
      repeat
        ch := getc(inFile);
        if ch <> EOF then
          write(OUT, ch);
        end if;
      until ch = EOF;
      if fileName <> "-" then
        close(inFile);
      end if;
    else
      writeln("cat: " <& fileName <& ": Not found or not readable");
    end if;
  end func;

(**
 *  This is a POSIX compatible cat.
 *)
const proc: main is func
  local
    var integer: index is 0;
  begin
    if length(argv(PROGRAM)) < 1 then
      cat("-");
    elsif length(argv(PROGRAM)) = 1 and argv(PROGRAM)[1] = "-u" then
      cat("-");
    else
      for index range 1 to length(argv(PROGRAM)) do
        if index = 1 and argv(PROGRAM)[index][1] = '-' then
          if argv(PROGRAM)[index] = "-" then
            cat(argv(PROGRAM)[index]);
          elsif argv(PROGRAM)[index] <> "-u" then
            writeln("usage: cat [-u] [file ...]");
            exit(1);
          end if;
        else
          cat(argv(PROGRAM)[index]);
        end if;
      end for;
    end if;
  end func;
