#!/bin/sh
: ; exec klone $0 "$@"
; The above line finds the klone executable in the $PATH
;;Skeleton of a typical klone script
;;(stack-dump-on-error t)
;;(kdb t)

(setq args (getopts "USAGE: floppy-salvage
reads floppy in /dev/fd0, retries 10 times on bad sectors and outputs
results on stdout"
    ("-r" N retries "number of time to retry on each sector (default 10)")
    ("-v" () verbose "verbose operation")
))

(setq *floppy-size* 1474560)
(setq device "/dev/fd0")
(setq skip-size 512)
(setq retry-n 10)
(if retries (setq retry-n (Int retries)))

(defun main (&aux
    to-read
    (buffer (copy ""))
    (rnum 1)
    fd
    (rnump 0)
    position-on-disk
    (oldlen 0)
  )
  (setq fd (open device))
  (while (/= (length buffer)  *floppy-size*)
    (setq position-on-disk (length buffer))
    (setq to-read (- *floppy-size* (length buffer)))
    (PF *standard-error* "Reading %1k (%0 bytes) from %3k (%2 bytes), try#%4\n" 
      to-read (/ to-read 1024) 
      position-on-disk (/ position-on-disk 1024) rnum
    )
    (file-position fd position-on-disk)
    (setq buffer (+ buffer (read-chars to-read fd)))
    (incf rnum)
    (if (= oldlen (length buffer)) (progn
	(incf rnump)
	(if (>= rnump retry-n) (progn
	    (PF *standard-error* "Skipping %0 bytes\n" skip-size)
	    (setq buffer (+ buffer (make-string skip-size 0)))
	    (setq rnump 0)
	  )
	)
      )
      (setq rnump 0)
    )
    (setq oldlen (length buffer))
  )
  (PF *standard-error* "Floppy read! after %0 tries\n" rnum)
  (write-chars buffer)
)

(main)

;;; EMACS MODES
;;; Local Variables: ***
;;; mode:lisp ***
;;; End: ***

