/*
 A command-line FX2/FPGA block write tool. Takes an address and length
 and writes a block of data to the FPGA. Data is read from the stdin

 Copyright (c) 2006 Dimtel, Inc., All Rights Reserved

 $Id: usbwblk.c,v 1.2 2013/10/08 19:27:17 dim Exp $
 $Date: 2013/10/08 19:27:17 $
 $Author: dim $
 $Revision: 1.2 $
 $Log: usbwblk.c,v $
 Revision 1.2  2013/10/08 19:27:17  dim
 Added BOARD_SERNO support to all command-line utilities

 Revision 1.1  2012/11/11 05:25:19  dim
 Moved from iGp12/src/usbio, updated to handle LLRF4 and iGp12

 Revision 1.1.1.1  2010/10/05 16:42:44  dim
 Initial import of iGp12

 Revision 1.1.1.1  2009/06/02 20:26:02  dim
 Initial import

 Revision 1.2  2009/06/02 19:56:51  dim
 Full support for service functions (fw load, 8051 control, EEPROM) added

 Revision 1.1.1.1  2006/11/16 19:38:15  dim
 Initial import

*/

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "usbio.h"

extern char *exnm;

int main(int argc, char **argv)
{
  unsigned int addr, count, rc, *data;
  struct timeval tv[2];
  usbio_context *ctxt;

  exnm = basename(argv[0]);

  if (argc != 3)
  {
    fprintf(stderr, "Usage: %s address count\n", exnm);
    return 0;
  }
  
  addr = (unsigned int) strtod(argv[1], NULL);
  count = (unsigned int) strtod(argv[2], NULL);
  
  data = (unsigned int *)malloc(count*sizeof(unsigned int));
  
  ctxt = usbio_open_serial(0, getenv("BOARD_SERNO"));
  if (ctxt == NULL)
  {
    fprintf(stderr, "%s: usbio_open() failed\n", exnm);
    return 1;
  }
  
  fread(data, sizeof(unsigned int), count, stdin);
  gettimeofday(tv, NULL);
  rc = usbio_block_write(ctxt, addr, data, count);
  gettimeofday(tv + 1, NULL);
  if (rc != count)
  {
    fprintf(stderr, "%s: usbio_block_write() failed\n", exnm);
    return 2;
  }
  usbio_close(ctxt, 0);
  fprintf(stderr, "Time %.3f s, %.2f MiB/s\n",
         (double)deltaT(tv, tv + 1)/1.0e6,
         ((double)count/(double)deltaT(tv, tv+1))*sizeof(int)/1024.0e-6/1024);
  
  return 0;
}

