+int uuencode(u8 *in,u8 *out) {
+
+ out[0]=0x20+((in[0]>>2)&0x3f);
+ out[1]=0x20+(((in[0]<<4)|(in[1]>>4))&0x3f);
+ out[2]=0x20+(((in[1]<<2)|(in[2]>>6))&0x3f);
+ out[3]=0x20+(in[2]&0x3f);
+
+ return 0;
+}
+
+int write_to_ram(t_lpc *lpc,u8 *buf,int addr,int len) {
+
+ int lcount;
+ u8 checksum;
+ u8 txrxbuf[BUFSIZE];
+ int count,bcnt;
+ int nlen,slen;
+ int i;
+
+ /* check length */
+ if(len%4) {
+ printf("ram write: not a multiple of 4\n");
+ return -1;
+ }
+
+ /* make it a multiple of 3 (reason: uuencode) */
+ nlen=(len/3+1)*3;
+ if(nlen>BUFSIZE) {
+ printf("ram write: too much data\n");
+ return -1;
+ }
+ for(i=len;i<nlen;i++) buf[i]=0;
+
+ /* prepare write command */
+ snprintf(txrxbuf,BUFSIZE,"W %d %d",addr,len);
+ slen=strlen(txrxbuf);
+ txrxbuf[slen]='\r';
+ txrxbuf[slen+1]='\0';
+ slen+=2;
+
+ /* send command and check return code */
+ txrx(lpc,txrxbuf,slen,TXRX_TYPE_CMD);
+ if(strncmp(txrxbuf,"OK\r\n",4)) {
+ printf("ram write: write command failed\n");
+ return -1;
+ }
+
+ /* send data */
+ lcount=0;
+ bcnt=0;
+ count=0;
+ checksum=0;
+ while(bcnt<nlen) {
+
+ /* uuencode / prepare data bytes */
+ uuencode(buf+bcnt,txrxbuf);
+ txrxbuf[4]='\0';
+ txrxbuf[5]='\0';
+
+ /* checksum */
+ checksum+=(buf[0]+buf[1]+buf[2]);
+
+ /* send a data line */
+ txrx(lpc,txrxbuf,6,TXRX_TYPE_DATA);
+
+ /* increase counters */
+ lcount+=1;
+ bcnt+=3;
+ count+=3;
+
+ /* checksum */
+ if(!(lcount%20)) {
+ /* send checksum */
+ txrxbuf[0]=checksum;
+ txrx(lpc,txrxbuf,1,TXRX_TYPE_CMD);
+ if(!strncmp(txrxbuf,"RESEND\r\n",8)) {
+ printf("ram write: resending ...\n");
+ bcnt-=count;
+ }
+ if(strncmp(txrxbuf,"OK\r\n",4)) {
+ printf("ram write: bad response\n");
+ return -1;
+ }
+ /* reset checksum & counter */
+ checksum=0;
+ count=0;
+ }
+
+ }
+
+ return 0;
+}
+
+int firmware_to_ram(t_lpc *lpc) {
+
+ char line[BUFSIZE];
+ char buf[BUFSIZE];
+
+ /* read file */
+ while(ret) {
+ /* read line */
+ while(ret) {
+ ret=read(lpc->fwfd,line,1);
+ if(line[0]!=':') {
+ printf("fw to ram: no ihex format\n");
+ return -1;
+ }
+ ret=read(lpc->fwfd,line+1,2);
+ line[3]='\0';
+ len=atoi(line+1);
+ ret=read(lpc->fwfd,line+3,4);
+ line[7]='\0';
+ addr=strtol(line+3);
+
+ }
+ }
+
+ return 0;
+}
+