/*
 A command-line FX2/FPGA block read tool. Takes an address and length
 and reads out a block of data. Data is dumped on stdout
 
 Copyright (c) 2006 Dimtel, Inc., All Rights Reserved

 $Id: usbrblk.c,v 1.1 2012/11/11 05:25:19 dim Exp $
 $Date: 2012/11/11 05:25:19 $
 $Author: dim $
 $Revision: 1.1 $
 $Log: usbrblk.c,v $
 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.2  2010/03/12 19:04:59  dim
 Updates for multiple boards, bug fixes

 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;
  }
  
  gettimeofday(tv, NULL);
  rc = usbio_block_read(ctxt, addr, data, count);
  gettimeofday(tv + 1, NULL);
  if (rc != count)
  {
    fprintf(stderr, "%s: usbio_block_read() failed (%d/%d)\n", exnm, rc, count);
    return 2;
  }
  fwrite(data, sizeof(unsigned int), count, stdout);
  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;
}

