#!/usr/bin/env bash

# Simple script to help selectively assemble tiles from an old map and a new
# (partial) remap.
#
# It assumes that the working directory contains 
# - `cells-10` which has the result of pcp_and_meshing_pipeline (aka the new map)
# - `assembled` which contains a copy of the old map
# At the end, `assembled` will contain the assembled map.

set -euo pipefail

# This is the logic to select the tiles: keep the old tiles when this returns 
# true.
# 10# is to force base 10, overwise numbers starting with 0 are interpreted
# as octal values.
keep_old_3d() {
  x=10#$1
  y=10#$2
  (( $y <= 165645 || ($y <= 165647 && $x >= 22830 && $x <= 22832) || ($y <= 165648 && $x <= 22825) ))
}

keep_old_2d() {
  x=10#$1
  y=10#$2
  !(( $x < 11146 && ($x < 11142 || $y > 80885) ))
}

keep_old_3d_tile() {
  tile=$1
  f=$(basename $tile .bin)
  x=$(echo $f | cut -d'-' -f2)
  y=$(echo $f | cut -d'-' -f3)
  keep_old_3d $x $y
}

keep_old_3d_ortho() {
  tile=$1
  f=$(basename $tile .png)
  x=$(echo $f | cut -d'-' -f5)
  y=$(echo $f | cut -d'-' -f6)
  keep_old_3d $x $y
}

keep_old_2d_tile() {
  tile=$1
  f=$(basename $tile .png)
  x=$(echo $f | cut -d'-' -f5)
  y=$(echo $f | cut -d'-' -f6)
  keep_old_2d $x $y
}

# remove existing 3d tiles from the old map
for tile in assembled/Tiles-10S-25-10/*.bin
do
  keep_old_3d_tile $tile || rm $tile
done

# and ortho images
for tile in assembled/images/ortho/Tiles-10S-25-10/*.png
do
  keep_old_3d_ortho $tile || rm $tile
done

# and 2d tiles
for tile in assembled/images/laser/*.png
do
  keep_old_2d_tile $tile || rm $tile
done


# add the new tiles
for tile in cells-10/Tiles/Tiles-10S-25-10/*.bin
do
  keep_old_3d_tile $tile || cp -l $tile assembled/Tiles-10S-25-10/
done

for tile in cells-10/images/ortho/Tiles-10S-25-10/*.png
do
  keep_old_3d_ortho $tile || cp -l $tile assembled/images/ortho/Tiles-10S-25-10/
done

for tile in cells-10/images/laser/*.png
do
  keep_old_2d_tile $tile || cp -l $tile assembled/images/laser/
done
