cleaned code; fixed corner case error