   .include #macros
   .include #16bit
   
   .zext _string1
   .zext _value
   .zext _tmp1

;; -------------------------------------------------------------
;; Char in A
;; isdigit returns Carry set if true
;;                 Carry clr if false   
;; -------------------------------------------------------------
isdigit:
   cmp   #'9+1
   bcs   :no
   cmp   #'0
   rts
:no:
   clc
   rts   

;; -------------------------------------------------------------
;; Convert a decimal number ASCII into an unsigned word
;; the input number must be decimal integer no sign
;; This function does not really check for overflow
;;                                  (maybe it should...)
;; string must end with $00 or $9B (ATASCII return)
;; Parameters via zeropage STRING1 and VALUE
;; returns: Carry set on success
;;          Carry clr on failure
;; -------------------------------------------------------------
atou:
   ldy   #0
   tya
   sta   _value
   sta   _value+1
   lda   (_string1),y
   bne   :firsttime
   clc
   rts
          
:more
   jsr   times10
   lda   (_string1),y         ; _value += digit - '0'
:firsttime   
   jsr   isdigit
   bcc   :failure
   sbc   #'0                  ; no carry trix possible (sigh)
   clc                
   adc   _value
   sta   _value
   bcc   :convert
   inc   _value+1
:convert
   iny
   cpy   #5                   ; possibly superflous
   bcs   :done
   lda   (_string1),y
   beq   :done
   cmp   #$9B
   bne   :more

:failure   
:done
   rts   
      

;; times10:
;; Multiplies a 16bit value with 10
;; the input number must be decimal integer no sign
;; This function does not really check for overflow
;;                                  (maybe it should...)
;; Parameters via zeropage _VALUE, tmp storage in _TMP1
;; returns: Carry contains oveflow (as expected) 

times10:
   dmove _value,_tmp1
   jsr   :val_lshift          ; _value *= 10
   jsr   :val_lshift
   jsr   :val_lshift
   jsr   :val_a_tmp
   
:val_a_tmp:
   adc.w _tmp1,_value,@special   ;; carry will be clear
   bcs   :error
   rts

:val_lshift:
   asl.w _value
   bcs   :error               ;; really success
:success
   rts  

:error
   pla
   pla
   rts
   
 

