{-# LANGUAGE BangPatterns #-}

module Main (main)
where
import System.Random
import Text.Printf
import Data.List
import System.IO


{-# INLINE r #-}
r = 1
{-# INLINE r2 #-}
r2 = r*r
n = 1000
time = 100
{-# INLINE l #-}
l = 25
{-# INLINE h #-}
h = 0.01

data Point = Point {-# UNPACK #-} !Double {-# UNPACK #-} !Double
data Particle = Particle { point :: !Point, angle :: !Double } -- point, angle

{-# INLINE distance #-}
distance :: Double -> Double -> Double
distance !x1 !x2
    | x1 < x2   = x2-x1
    | otherwise = let !d = x1-x2 in min d (l-d)
-- distance !x1 !x2 = {-# SCC "min" #-} min d1 d2
--     where
--     !d  = {-# SCC "d" #-}  x1 - x2
--     !d1 = {-# SCC "d1" #-} abs d
--     !d2 = {-# SCC "d2" #-} abs $ l - d

{-# INLINE pointsAreClose #-}
pointsAreClose :: Point -> Point -> Bool
pointsAreClose (Point x1 y1) (Point x2 y2) = sqr (distance x1 x2) + sqr (distance y1 y2) < r2
--    where sqr !x = x * x

{-# INLINE sqr #-}
sqr :: Double -> Double
sqr !x = x*x

{-# INLINE average #-}
average :: [Double] -> Double
average list = -- let (!s,!n) = foldl' (\(!s,!n) x -> (s+x,n+1)) (0,0) list in s / n
    case foldl' (\(!s, !n) !x -> (s + x, n + 1)) (0.0, 0.0) list of
      (!s, !n) -> s / n

{-# INLINE wrap #-}
wrap :: Double -> Double
wrap x | x < 0     = x + l
       | x > l     = x - l
       | otherwise = x

makeStep :: [Particle] -> Double -> [Particle]
makeStep allParticles dt = map (makeStep1 dt allParticles) allParticles

makeStep1 :: Double -> [Particle] -> Particle -> Particle
makeStep1 dt allParticles particle = updateParticle dt particle newAngle
    where
      !newAngle = average . map angle . filter (pointsAreClose (point particle) . point) $ allParticles

updateParticle dt (Particle (Point x0 y0) _) newAngle = Particle (Point x1 y1) newAngle
    where
    x1 = wrap $ x0 + cos newAngle * dt
    y1 = wrap $ y0 + sin newAngle * dt

create = zipWith3 (\x y a -> Particle (Point x y) a)

move t list = foldl' makeStep list (replicate t h)

prettyPrint list =
    withFile "output.txt" WriteMode $ \h -> do
    mapM_ (pp1 h) list
    where
        pp1 h (Particle (Point kx ky) ka) = hPrintf h "%.4f %.4f %.4f %.4f" kx ky (cos ka) (sin ka)

order list = let (c,s) = foldl' (\(!c,!s) (Particle _ a) -> (c+cos a, s+sin a)) (0,0) list
             in sqrt (sqr (c / (fromIntegral n)) + sqr (s / (fromIntegral n)))

groupN n list = let (h,!t) = splitAt n list in h:groupN n t

main = do
        g <- getStdGen
        let [x,y,alpha] = take 3 $ groupN n $ randomRs (0, l) g
            initialPosition = create x y alpha
            finalPosition   = move time initialPosition
            orderPar        = order finalPosition

        prettyPrint finalPosition
        printf "Order parameter: %.4f\n" orderPar
