void AdjustBoundByMouse( int X, int Y, int state = 0 )  // state: 0 move, 1 down
{
    static Point32i ptAdjustLine1, ptAdjustLine2, pt3, pt4, ptControl, ptAdjustLineOut1, ptAdjustLineOut2;
    static int index = 0;
    int points[ 8 ];
    int indexArray[4][8] = { {0,1,2,3,4,5,6,7}, {2,3,4,5,6,7,0,1}, {4,5,6,7,0,1,2,3}, {6,7,0,1,2,3,4,5} };


    // calculate x and y on picture
    int x = (int)((X - g_OffsetX) / g_scaleX + 0.5);
    int y = (int)((Y - g_OffsetY) / g_scaleY + 0.5);

    if ( state == 1 )   // mouse down, choose the nearest side line to adjust
    {
        float dist;
        float minDist = DistanceLineSegToPoint( g_cornerPoints[ 0 ], g_cornerPoints[ 1 ], g_cornerPoints[ 2 ], g_cornerPoints[ 3 ], x, y );
        index = 0;
        dist = DistanceLineSegToPoint( g_cornerPoints[ 2 ], g_cornerPoints[ 3 ], g_cornerPoints[ 4 ], g_cornerPoints[ 5 ], x, y );
        if ( dist < minDist ) { index = 1; minDist = dist; };
        dist = DistanceLineSegToPoint( g_cornerPoints[ 4 ], g_cornerPoints[ 5 ], g_cornerPoints[ 6 ], g_cornerPoints[ 7 ], x, y );
        if ( dist < minDist ) { index = 2; minDist = dist; };
        dist = DistanceLineSegToPoint( g_cornerPoints[ 6 ], g_cornerPoints[ 7 ], g_cornerPoints[ 0 ], g_cornerPoints[ 1 ], x, y );
        if ( dist < minDist ) { index = 3; minDist = dist; };
        ptAdjustLine1.x = g_cornerPoints[ indexArray[ index ][ 0 ] ];
        ptAdjustLine1.y = g_cornerPoints[ indexArray[ index ][ 1 ] ];
        ptAdjustLine2.x = g_cornerPoints[ indexArray[ index ][ 2 ] ];
        ptAdjustLine2.y = g_cornerPoints[ indexArray[ index ][ 3 ] ];
        pt3.x = g_cornerPoints[ indexArray[ index ][ 4 ] ];
        pt3.y = g_cornerPoints[ indexArray[ index ][ 5 ] ];
        pt4.x = g_cornerPoints[ indexArray[ index ][ 6 ] ];
        pt4.y = g_cornerPoints[ indexArray[ index ][ 7 ] ];
    }
    ptControl.x = x;
    ptControl.y = y;

    if ( AdjustBound( ptAdjustLine1, ptAdjustLine2, pt3, pt4, ptControl, &ptAdjustLineOut1, &ptAdjustLineOut2, g_linePoints, 20 ) >= 0 )
    {
        points[ 0 ] = ptAdjustLineOut1.x; points[ 1 ] = ptAdjustLineOut1.y;
        points[ 2 ] = ptAdjustLineOut2.x; points[ 3 ] = ptAdjustLineOut2.y;
        points[ 4 ] = pt3.x; points[ 5 ] = pt3.y;
        points[ 6 ] = pt4.x; points[ 7 ] = pt4.y;
        if ( IsValidPoints( points, g_pResultImage->GetWidth(), g_pResultImage->GetHeight() ) )
        {
            g_cornerPoints[ indexArray[ index ][ 0 ] ] = ptAdjustLineOut1.x;
            g_cornerPoints[ indexArray[ index ][ 1 ] ] = ptAdjustLineOut1.y;
            g_cornerPoints[ indexArray[ index ][ 2 ] ] = ptAdjustLineOut2.x;
            g_cornerPoints[ indexArray[ index ][ 3 ] ] = ptAdjustLineOut2.y;
        }
    }
}