#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "shcard.h"


#define ADDRESS 	(unsigned long)0x9038000L
int  fd;

/********************************************************/
/*      initialize SH chip                              */
/********************************************************/
int initsh( char *devname )
{
  if ((fd = open(devname, O_RDWR)) == -1){
    fprintf(stderr, "can not open %s\n", devname);
    exit(1);
  }

	return ERR_NOTHING;
}

int closesh( char *devname)
{
  if ( close(fd) == -1){
    fprintf(stderr, "can not close %s\n", devname);
    exit(1);    
  }
  return ERR_NOTHING;
}

int downloadvcv( char *filename)
{
  FILE *fp;
  char buf[BUFSIZ];
  unsigned long address, length;
  long count,sum,len;
  struct stat status;

  if( ( fp = fopen( filename, "rb" ) ) == NULL ) return ERR_FILE_OPEN ;
  stat(filename, &status);
  address = htonl(ADDRESS);
  count	  = status.st_size;  

  length = htonl(count / 2);

  write(fd,"@1\0\004", 4);
  write(fd, &address, 4 );
  write(fd, &length, 4 );
  
  sum = 0;
  while(len = fread(buf,1,1024,fp))
    {
      write(fd, buf,len );
      sum += len;
      fprintf(stderr,"%d \n",sum);
    }
	if( fclose( fp ) ) return ERR_FILE_CLOSE;
	return ERR_NOTHING;
}

int startsh()
{
  write(fd,"@3\0\0", 4);

  return ERR_NOTHING;
}

int teststart()
{
  unsigned char buf[3];
  read(fd,buf,1);
  if ( buf[0] == 0x81) return ERR_NOTHING;

  if ( write(fd,"$",1) != 1) return ERR_CARD_WRITE;
  

  read(fd,buf,1);
  if ( buf[0] != 0x81) return ERR_CARD_READ;

  return ERR_NOTHING;
}

int kisoku(unsigned char *text)
{
  unsigned short tmp;
  unsigned int text_length, all_length;
  static unsigned short text_count;
  static unsigned short item;
  unsigned char buf[3];
  size_t len;

  len = (size_t) strlen(text);
  if ( len > 94) ERR_TEXT_LENGTH;

  text_count     = len  + ( len % 2 );
  text_length  = len;               /* byte */

  all_length   = ( 2 + text_count     ) / 2;     /* word */

  write(fd,"@",1);
  write(fd,"6",1);

  tmp =  htons(all_length);
  write(fd, &tmp, 2);

  tmp =  htons(text_length);
  write(fd, &tmp, 2);

  write(fd, text, len );

	if (read(fd, buf, 1) != 1) {
		return ERR_CARD_READ;	
	}
	if (buf[0] == 0x82) {
		return ERR_MIN_VALUE;	
	}
	if (buf[0] == 0x83) {
		return ERR_MAX_VALUE;	
	}
	return ERR_NOTHING;
}

int kisokustop()
{
  write(fd,"$",1);
  return ERR_NOTHING;
}

int resetsh()
{
  kisoku("S4P4U0V32X0\n");
  return ERR_NOTHING;
}
