/* i1620_cd.c: IBM 1622 card reader/punch

   Copyright (c) 2002-2004, Robert M. Supnik

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
   ROBERT M SUPNIK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
   IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

   Except as contained in this notice, the name of Robert M Supnik shall not
   be used in advertising or otherwise to promote the sale, use or other dealings
   in this Software without prior written authorization from Robert M Supnik.

   cdr		1622 card reader
   cdp		1622 card punch

   25-Apr-03	RMS	Revised for extended file support

   Cards are represented as ASCII text streams terminated by newlines.
   This allows cards to be created and edited as normal files.
*/

#include "i1620_defs.h"

#define CD_LEN		80

extern uint8 M[MAXMEMSIZE];
extern uint8 ind[NUM_IND];
extern UNIT cpu_unit;
extern int32 io_stop;

char cdr_buf[CD_LEN + 2];
char cdp_buf[CD_LEN + 2];

t_stat cdr_reset (DEVICE *dptr);
t_stat cdr_attach (UNIT *uptr, char *cptr);
t_stat cdr_boot (int32 unitno, DEVICE *dptr);
t_stat cdr_read (void);
t_stat cdp_reset (DEVICE *dptr);
t_stat cdp_write (uint32 len);
t_stat cdp_num (uint32 pa, uint32 ndig, t_bool dump);

/* Card reader data structures

   cdr_dev	CDR descriptor
   cdr_unit	CDR unit descriptor
   cdr_reg	CDR register list
*/

UNIT cdr_unit = {
	UDATA (NULL, UNIT_SEQ+UNIT_ATTABLE+UNIT_ROABLE, 0) };

REG cdr_reg[] = {
	{ FLDATA (LAST, ind[IN_LAST], 0) },
	{ DRDATA (POS, cdr_unit.pos, T_ADDR_W), PV_LEFT },
	{ NULL }  };

DEVICE cdr_dev = {
	"CDR", &cdr_unit, cdr_reg, NULL,
	1, 10, 31, 1, 8, 7,
	NULL, NULL, &cdr_reset,
	&cdr_boot, &cdr_attach, NULL };

/* CDP data structures

   cdp_dev	CDP device descriptor
   cdp_unit	CDP unit descriptor
   cdp_reg	CDP register list
*/

UNIT cdp_unit = {
	UDATA (NULL, UNIT_SEQ+UNIT_ATTABLE, 0) };

REG cdp_reg[] = {
	{ DRDATA (POS, cdp_unit.pos, T_ADDR_W), PV_LEFT },
	{ NULL }  };

DEVICE cdp_dev = {
	"CDP", &cdp_unit, cdp_reg, NULL,
	1, 10, 31, 1, 8, 7,
	NULL, NULL, &cdp_reset,
	NULL, NULL, NULL };

/* Data tables.  The card reader presents unusual problems.
   - Unique codes needed for 11-2-8 (uses !) and 12-7-8 (uses ") .
   - Can punch both 11 (-) and 11-0 (uses ]).
   On input, the nul and nl generated by C are converted to
   spaces; tabs and line feeds are also converted to spaces.

/* Card reader (ASCII) to numeric (one digit) */

const char cdr_to_num[128] = {
 0x00,   -1,   -1,   -1,   -1,   -1,   -1,   -1,	/* 00 */
   -1, 0x00, 0x00,   -1,   -1, 0x00,   -1,   -1,
   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,	/* 10 */
   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
 0x00, 0x1A, 0x1F, 0x00, 0x1B, 0x0A, 0x0F, 0x0A,	/*  !"#$%&' */
 0x0C, 0x0C, 0x1C, 0x00, 0x0B, 0x10, 0x1B, 0x01,	/* ()*+,-./ */
 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,	/* 01234567 */
 0x08, 0x09, 0x00, 0x1E, 0x1E, 0x0B, 0x0E, 0x1A,	/* 89:;<=>? */
 0x0C, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,	/* @ABCDEFG */
 0x08, 0x09, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16,	/* HIJKLMNO */
 0x17, 0x18, 0x19, 0x02, 0x03, 0x04, 0x05, 0x06,	/* PQRSTUVW */
 0x07, 0x08, 0x09, 0x00, 0x0E, 0x10, 0x0F, 0x1F,	/* XYZ[\]^_ */
   -1, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,	/*  abcdefg */
 0x08, 0x09, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16,	/* hijklmno */
 0x17, 0x18, 0x19, 0x02, 0x03, 0x04, 0x05, 0x06,	/* pqrstuvw */
 0x07, 0x08, 0x09,   -1,   -1,   -1,   -1,   -1 };	/* xyz      */

/* Numeric (flag + digit) to card punch (ASCII) */

const char num_to_cdp[32] = {
 '0', '1', '2', '3', '4', '5', '6', '7',		/* 0 */
 '8', '9', '\'', ',', ' ', '&', ' ', '&',
 ']', 'J', 'K', 'L', 'M', 'N', 'O', 'P',		/* F + 0 */
 'Q', 'R', '!', '$',  -1,  -1,  -1, '"' };

/* Card reader (ASCII) to alphameric (two digits)

   11-2-8 (!) reads as 5A
   11-7-8 (_) reads as 5F
   12-2-8 (?) reads inconsistently (here 02)
   12-6-8 (<) reads inconsistently (here 5E)
   12-7-8 (") reads as 5F
*/

const char cdr_to_alp[128] = {
 0x00,   -1,   -1,   -1,   -1,   -1,   -1,   -1,	/* 00 */
   -1, 0x00, 0x00,   -1,   -1, 0x00,   -1,   -1,
   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,	/* 10 */
   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
 0x00, 0x5A, 0x5F, 0x60, 0x13, 0x0A, 0x0F, 0x0A,	/*  !"#$%&' */
 0x24, 0x04, 0x14, 0x10, 0x23, 0x20, 0x03, 0x21,	/* ()*+,-./ */
 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,	/* 01234567 */
 0x78, 0x79, 0x70, 0x5E, 0x5E, 0x33, 0x0E, 0x02,	/* 89:;<=>? */
 0x34, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,	/* @ABCDEFG */
 0x48, 0x49, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56,	/* HIJKLMNO */
 0x57, 0x58, 0x59, 0x62, 0x63, 0x64, 0x65, 0x66,	/* PQRSTUVW */
 0x67, 0x68, 0x69, 0x40, 0x0E, 0x50, 0x0F, 0x5F,	/* XYZ[\]^_ */
   -1, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,	/*  abcdefg */
 0x48, 0x49, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56,	/* hijklmno */
 0x57, 0x58, 0x59, 0x62, 0x63, 0x64, 0x65, 0x66,	/* pqrstuvw */
 0x67, 0x68, 0x69,   -1,   -1,   -1,   -1,   -1 };	/* xyz      */

/* Alphameric (two digits) to card punch (ASCII).  Oddities:

	02 -> 12-2-8 (?), symmetric
	07 -> 12-7-8 ("), reads as 5F
	12 -> 11-2-8 (!), reads as 5A
	15 -> 11,0 (]), reads as 50
	22 -> 0-2-8 ('), reads as 0A
	32 -> 2-8 (%), reads as 0A
	5B -> 11-3-8 (=), reads as 13
	6A -> 0-2-8 ('), reads as 0A
	6B -> 0-3-8 (,), reads as 23
	AA -> 0-2-8 ('), reads as 0A

   There is no way to punch 0-5-8 (#), 0-6-8 (\),
   11-5-8 (]), 11-6-8 (;), 11-7-8 (_),
   12-5-8 ([), or 12-6-8 (<)
*/

const char alp_to_cdp[256] = {
 ' ',  -1, '?', '.', ')',  -1,  -1, '"',		/* 00 */
  -1,  -1, '\'', -1,  -1,  -1,  -1, '&',
 '+',  -1, '!', '$', '*', ']',  -1,  -1,		/* 10 */ 
  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
 '-', '/', '\'', ',', '(', -1,  -1,  -1,		/* 20 */
  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
  -1,  -1, '%', '=', '@', ':', ' ',  -1,		/* 30 */
  -1,  -1, '\'', -1,  -1,  -1,  -1, '&',
  -1, 'A', 'B', 'C', 'D', 'E', 'F', 'G',		/* 40 */
 'H', 'I',  -1,  -1,  -1,  -1,  -1,  -1,
 '_', 'J', 'K', 'L', 'M', 'N', 'O', 'P',		/* 50 */
 'Q', 'R', '?', '=',  -1,  -1,  -1, '"',
  -1, '/', 'S', 'T', 'U', 'V', 'W', 'X',		/* 60 */
 'Y', 'Z', '\'', ',', -1,  -1,  -1,  -1,
 '0', '1', '2', '3', '4', '5', '6', '7',		/* 70 */
 '8', '9',  -1,  -1,  -1,  -1,  -1,  -1,
  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,		/* 80 */
  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,		/* 90 */
  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,		/* A0 */
  -1,  -1, '\'', -1,  -1,  -1,  -1,  -1,
  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,		/* B0 */
  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,		/* C0 */
  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,		/* D0 */
  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,		/* E0 */
  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,		/* F0 */
  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1 }; 

/* Card reader IO routine
 
   - Hard errors stop the operation and halt the system.
   - Invalid characters place a blank in memory and set RDCHK.
     If IO stop is set, the system halts at the end of the operation.
*/

t_stat cdr (uint32 op, uint32 pa, uint32 f0, uint32 f1)
{
int32 i;
int8 cdc;
t_stat r, inv = SCPE_OK;

switch (op) {						/* case on op */
case OP_RN: 						/* read numeric */
	r = cdr_read ();				/* fill reader buf */
	if (r != SCPE_OK) return r;			/* error? */
	for (i = 0; i < CD_LEN; i++) {			/* transfer to mem */
	    cdc = cdr_to_num[cdr_buf[i]];		/* translate */
	    if (cdc < 0) {				/* invalid? */
		ind[IN_RDCHK] = 1;			/* set read check */
		inv = STOP_INVCHR;			/* set return status */
		cdc = 0;  }
	    M[pa] = cdc;				/* store digit */
	    PP (pa);  }					/* incr mem addr */
	break;
case OP_RA:						/* read alphameric */
	r = cdr_read ();				/* fill reader buf */
	if (r != SCPE_OK) return r;			/* error? */
	for (i = 0; i < CD_LEN; i++) {			/* transfer to mem */
	    cdc = cdr_to_alp[cdr_buf[i]];		/* translate */
	    if (cdc < 0) {				/* invalid? */
		ind[IN_RDCHK] = 1;			/* set read check */
		inv = STOP_INVCHR;			/* set return status */
		cdc = 0;  };
	    M[pa] = (M[pa] & FLAG) | (cdc & DIGIT);	/* store 2 digits */
	    M[pa - 1] = (M[pa - 1] & FLAG) | ((cdc >> 4) & DIGIT);
	    pa = ADDR_A (pa, 2);  }			/* incr mem addr */
	break;	
default:						/* invalid function */
	return STOP_INVFNC;  }
CRETIOE (io_stop, inv);
}

/* Fill card reader buffer - all errors are hard errors */

t_stat cdr_read (void)
{
int32 i;

ind[IN_LAST] = 0;					/* clear last card */
if ((cdr_unit.flags & UNIT_ATT) == 0) {			/* attached? */
	ind[IN_RDCHK] = 1;				/* no, error */
	return SCPE_UNATT;  }

for (i = 0; i < CD_LEN + 1; i++) cdr_buf[i] = ' ';	/* clear buffer */
fgets (cdr_buf, CD_LEN, cdr_unit.fileref);		/* read card */
if (feof (cdr_unit.fileref)) return STOP_NOCD;		/* eof? */
if (ferror (cdr_unit.fileref)) {			/* error? */
	ind[IN_RDCHK] = 1;				/* set read check */
	perror ("CDR I/O error");
	clearerr (cdr_unit.fileref);
	return SCPE_IOERR;  }
cdr_unit.pos = ftell (cdr_unit.fileref);		/* update position */
getc (cdr_unit.fileref);				/* see if more */
if (feof (cdr_unit.fileref)) ind[IN_LAST] = 1;		/* eof? set last */
fseek (cdr_unit.fileref, cdr_unit.pos, SEEK_SET);	/* "backspace" */
return SCPE_OK;
}

/* Card reader attach */

t_stat cdr_attach (UNIT *uptr, char *cptr)
{
ind[IN_LAST] = 0;					/* clear last card */
return attach_unit (uptr, cptr);
}

/* Card reader reset */

t_stat cdr_reset (DEVICE *dptr)
{
ind[IN_LAST] = 0;					/* clear last card */
return SCPE_OK;
}

/* Bootstrap routine */

const static uint8 boot_rom[] = {
 3, 6, 1, 9, 9, 0, 1, 0, 0, 5, 0, 0,			/* RNCD 19901 */
 2, 5, 0, 0, 0, 8, 0, 1, 9, 9, 1, 0x10,			/* TD 80,-19910 */
 3, 1, 1, 9, 9, 0, 0x15, 1, 9, 9, 2, 0,			/* TR -19905,19920 */
 2, 5, 1, 9, 9, 1, 0x10, 0, 0, 0, 8, 0,			/* TD -19910,80 */
 4, 9, 1, 9, 9, 1, 0x15, 0, 0, 0, 0, 0 };		/* BR -19915 */

#define BOOT_START	0
#define BOOT_LEN	(sizeof (boot_rom) / sizeof (uint8))

t_stat cdr_boot (int32 unitno, DEVICE *dptr)
{
int32 i;
extern int32 saved_PC;

if ((cpu_unit.flags & IF_IA) == 0) return SCPE_NOFNC;	/* must have IA */
for (i = 0; i < BOOT_LEN; i++) M[BOOT_START + i] = boot_rom[i];
saved_PC = BOOT_START;
return SCPE_OK;
}

/* Card punch IO routine 

   - Hard errors stop the operation and halt the system.
   - Invalid characters stop the operation and set WRCHK.
     If IO stop is set, the system halts.
*/

t_stat cdp (uint32 op, uint32 pa, uint32 f0, uint32 f1)
{
int32 i;
int8 cdc;
uint8 z, d;

switch (op) {						/* decode op */
case OP_DN:
	return cdp_num (pa, 20000 - (pa % 20000), TRUE); /* dump numeric */
case OP_WN:
	return cdp_num (pa, CD_LEN, FALSE);		/* write numeric */
case OP_WA:
	for (i = 0; i < CD_LEN; i++) {			/* one card */
	    d = M[pa] & DIGIT;				/* get digit pair */
	    z = M[pa - 1] & DIGIT;
	    cdc = alp_to_cdp[(z << 4) | d];		/* translate */
	    if (cdc < 0) {				/* bad char? */
		ind[IN_WRCHK] = 1;			/* set write check */
		CRETIOE (io_stop, STOP_INVCHR);  }
	    cdp_buf[i] = cdc;				/* store in buf */
	    pa = ADDR_A (pa, 2);  }			/* incr mem addr */
	return cdp_write (CD_LEN);			/* punch buffer */
default:						/* invalid function */
	return STOP_INVFNC;  }
return SCPE_OK;
}

/* Punch card numeric */

t_stat cdp_num (uint32 pa, uint32 ndig, t_bool dump)
{
int32 i, ncd, len;
uint8 d;
int8 cdc;
t_stat r;

ncd = ndig / CD_LEN;					/* number of cards */
while (ncd-- >= 0) {					/* until done */
	len = (ncd >= 0)? CD_LEN: (ndig % CD_LEN);	/* card length */
	if (len == 0) break;
	for (i = 0; i < len; i++) {			/* one card */
	    d = M[pa] & (FLAG | DIGIT);			/* get char */
	    if (dump && (d == FLAG)) cdc = '-';		/* dump? F+0 is diff */
	    else cdc = num_to_cdp[d];			/* translate */
	    if (cdc < 0) {				/* bad char? */
		ind[IN_WRCHK] = 1;			/* set write check */
		CRETIOE (io_stop, STOP_INVCHR);  }	/* stop */
	    cdp_buf[i] = cdc;				/* store in buf */
	    PP (pa);  }					/* incr mem addr */
	r = cdp_write (len);				/* punch card */
	if (r != SCPE_OK) return r;  }			/* error? */
return SCPE_OK;
}

/* Write punch card buffer - all errors are hard errors */

t_stat cdp_write (uint32 len)
{
if ((cdp_unit.flags & UNIT_ATT) == 0) {			/* attached? */
	ind[IN_WRCHK] = 1;				/* no, error */
	return SCPE_UNATT;  }

while ((len > 0) && (cdp_buf[len - 1] == ' ')) --len;	/* trim spaces */
cdp_buf[len] = '\n';					/* newline, null */
cdp_buf[len + 1] = 0;

if (fputs (cdp_buf, cdp_unit.fileref) == EOF) {		/* write card */
	ind[IN_WRCHK] = 1;				/* error? */
	perror ("CDP I/O error");
	clearerr (cdp_unit.fileref);
	return SCPE_IOERR;  }
cdp_unit.pos = ftell (cdp_unit.fileref);		/* count char */
return SCPE_OK;
}

/* Reset card punch */

t_stat cdp_reset (DEVICE *dptr)
{
return SCPE_OK;
}
