From d7865a0aef3dee52244b3e8b7c42d534789c2e1e Mon Sep 17 00:00:00 2001
From: Ramakrishnan Muthukrishnan <ram@rkrishnan.org>
Date: Fri, 24 Jul 2015 14:06:18 +0530
Subject: [PATCH] pickPiece: a simple algorithm to download the pieces in order

---
 src/FuncTorrent/Peer.hs | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)

diff --git a/src/FuncTorrent/Peer.hs b/src/FuncTorrent/Peer.hs
index 2130ffe..4da3d0b 100644
--- a/src/FuncTorrent/Peer.hs
+++ b/src/FuncTorrent/Peer.hs
@@ -18,7 +18,7 @@ import Control.Monad (replicateM, liftM, forever)
 import Control.Applicative ((<$>), liftA3)
 import Data.Bits
 import Data.Word (Word8)
-import Data.Map (Map(..), fromList, (!), mapWithKey)
+import Data.Map (Map(..), fromList, toList, (!), mapWithKey)
 
 import FuncTorrent.Metainfo (Info(..), Metainfo(..))
 import FuncTorrent.Utils (splitN)
@@ -227,6 +227,17 @@ msgLoop state pieceStatus = do
        _ -> do
          msgLoop state pieceStatus
 
+-- simple algorithm to pick piece.
+-- pick the first piece from 0 that is not downloaded yet.
+pickPiece :: PieceMap -> Maybe Integer
+pickPiece m =
+  let pieceList = toList m
+      allPending = filter (\(k, v) -> state v == Pending) pieceList
+  in
+   case allPending of
+    [] -> Nothing
+    ((i, _):_) -> Just i
+
 updatePieceAvailability :: PieceMap -> Peer -> [Integer] -> PieceMap
 updatePieceAvailability pieceStatus p pieceList =
   mapWithKey (\k pd -> if k `elem` pieceList
-- 
2.45.2