/* more.c - Display a file or send it.
 *  Copyright (C) 2022 by Jed Marti
 *   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 3 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, see https://www.gnu.org/licenses/.
 */


#include <C8051F380.h>
#include <stdint.h>

#include "lfxmit.h"
#include "config.h"
#include "serial.h"
#include "lex.h"
#include "fs.h"
//#include "morse.h"

// Lexical interface.
extern __xdata uint8_t ttype;
extern __xdata char    STR[];
extern __bit           errorThrown;


void more(void)
// Display a file on the serial port. This is a top level only command.
{
  uint8_t fh;
  int16_t c;

  // Punt if no file name.
  ntok();
  if (!(ttype == LEXID || ttype == LEXSTRING))
  {
    putstring("bad file name\n");
    errorThrown = 1;
    return;
  }

  // If we can't open it then quit.
  if ((fh = openFile(STR)) == 255)
  {
    putstring("Can't opn ");
    putstring(STR);
    terpri();
    errorThrown = 1;
    return;
  }

  // Move beyond file name.
  ntok();

  // Echo it and close.
  for (c = getchFile(fh); c != -1; c = getchFile(fh))
    if (c != 13) putch(c);
  closeFile(fh);
  terpri();

}



void sendFile(void)
// Send a file by Morse code. From the FSEND command.
{
  uint8_t fh;
  int16_t  c;

  // Error if no file name given.
  ntok();
  if (!(ttype == LEXID || ttype == LEXSTRING))
  {
    putstring("bad file name\n");
    errorThrown = 1;
    return;
  }

  // If we can't open it, then punt.
  if ((fh = openFile(STR)) == 255)
  {
    putstring("Can't open ");
    putstring(STR);
    terpri();
    errorThrown = 1;
    return;
  }
 
  // Skip token.
  ntok();

  // Read the file, convert characters to upper case.
  for (c = getchFile(fh); c != -1; c = getchFile(fh))
    if (c != 13 && c != 10) 
    {
      if (c >= 'a' && c <= 'z') c -= 32; 
      sendChar(c);
    }
  closeFile(fh);
  terpri();
}



// EOF
