@@ -152,10 +152,30 @@ export class Processor {
152152 } 
153153
154154 private  convertToBCD ( value : number ) : number  { 
155-  value  =  value  %  100 ;  //discard any remainder 
155+  while  ( value  <  0 )  { 
156+  value  +=  100 ; 
157+  } 
158+  value  =  value  %  100 ;  //discard any remainder over 100 
156159 const  highNibble  =  Math . floor ( value  /  10 ) ; 
157160 const  lowNibble  =  value  -  highNibble  *  10 ; 
158-  return  highNibble  <<  ( 4  +  lowNibble ) ; 
161+  return  ( highNibble  <<  4 )  +  lowNibble ; 
162+  } 
163+ 
164+  //We can't use the adc with ~v2 for subtraction in decimal mode 
165+  private  decimalSub ( v1 : number ,  v2 : number )  { 
166+  const  c  =  ( this . registers [ FLAGS ]  &  FLAG_C )  >  0  ? 0  : 1 ;  //not-c 
167+  v1  =  this . convertFromBCD ( v1 ) ; 
168+  v2  =  this . convertFromBCD ( v2 ) ; 
169+  const  sum  =  v1  -  v2  -  c ; 
170+  if  ( sum  <  0 )  { 
171+  this . unsetFlag ( FLAG_C ) ; 
172+  }  else  { 
173+  this . setFlag ( FLAG_C ) ; 
174+  } 
175+  const  result  =  this . convertToBCD ( sum ) ; 
176+  //only C is valid in Decimal mode, but try to set the others anyway 
177+  this . setFlagsFor ( result ) ; 
178+  return  result ; 
159179 } 
160180
161181 private  internaladc ( v1 : number ,  v2 : number )  { 
@@ -398,9 +418,15 @@ export class Processor {
398418 private  sbc ( operand : number ,  getAddress ?: ( operand : number )  =>  number )  { 
399419 const  v1  =  this . registers [ A ] ; 
400420 const  v2  =  getAddress  ? this . readMem ( getAddress ( operand ) )  : operand ; 
401-  //sbc should be the same operation as adc but with the bits of the memory byte flipped 
402-  //>>> coerces to an unsigned int so that the bitwise invert ~ works as expected, otherwise in JS ~0xff == -255 
403-  const  sum  =  this . internaladc ( v1 ,  ( ~ v2  >>>  0 )  &  0xff ) ; 
421+  const  decimalMode  =  ( this . registers [ FLAGS ]  &  FLAG_D )  >  0 ; 
422+  let  sum ; 
423+  if  ( decimalMode )  { 
424+  sum  =  this . decimalSub ( v1 ,  v2 ) ; 
425+  }  else  { 
426+  //binary sbc should be the same operation as adc but with the bits of the memory byte flipped 
427+  //>>> coerces to an unsigned int so that the bitwise invert ~ works as expected, otherwise in JS ~0xff == -255 
428+  sum  =  this . internaladc ( v1 ,  ( ~ v2  >>>  0 )  &  0xff ) ; 
429+  } 
404430 this . registers [ A ]  =  sum ; 
405431 } 
406432
0 commit comments