/*
 *  Flasher Source File
 *
 *  GNU Copyright (C) 2003 Gaspar Sinai <gsinai@yudit.org>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License, version 2,
 *  dated June 1991. See file COPYYING for details.
 *
 *  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., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/**
 * This program is not yet fully integrated into
 * flasher-0.1.tar.gz, which can be downloaded from:
 * http://www.yudit.org/uc/
 * To compile put pluto.cpp into flasher-0.1/src
 * and manually do 
 *  c++  -I. pluto.cpp -o pluto  -L. -lflasher
 * after everything has been compiled.
 */
#include "flasher.h"

#include <stdlib.h>
#include <string.h>

using namespace FLASHER;

// Write Raw Binary Format into EP1K10 FPGA. 
static void pluto(const char* filename);

/*!
 * \brief Flasher Tester Program.
 */
int
main (int argc, char* argv[])
{
  if (argc<2)
  {
    fprintf (stderr, "usage: pluto filename\n");
    return 1;
  }
  try {
    pluto (argv[1]);
  }
  catch (const Exception& e)
  {
    fprintf (stderr, "pluto: failed - %s\n", e.toString());
    return 1;
  }
  return 0;
}

/**
 * Write data in Raw Binary Format to Pluto card of
 *   http://fpga4fun.com/
 * EP1K100 via a clock generated from stream via a monostable multivibrator.
 */
static void pluto(const char* filename)
{
  FILE* file = fopen (filename, "r");
  if (file == 0)
  {
    THROW ("Can not read: " << filename);
  }
  // 19200N1
  Serial serial("/dev/ttyS1");
  serial.setBaudRate (Serial::BPS_115200);
  int c;
  int i= 0;
  while ((c = fgetc(file)) != EOF)
  {
    if ((i % 256)==0)
    {
      fprintf (stderr, ".");
      fflush (stderr);
    }
    i++;
    /* push 8 bits through */
    unsigned int outc = (c & 0xff);
    for (int j=0; j<8; j++)
    {
      serial.write (((outc >> j) & 1) ? 0x80 : 0xff);
    }
  }
  fprintf (stderr, "\n");
  fclose (file);
}
